adding application registrating functionality and partial DAO modefications

4.x.x
lasantha 7 years ago
parent dc6ab1db2f
commit 81be917e10

@ -44,6 +44,9 @@ public class APIUtil {
private static final String DEFAULT_CDMF_API_TAG = "device_management";
private static final String DEFAULT_AGENT_API_TAG = "device_agent";
private static final String DEFAULT_CERT_API_TAG = "scep_management";
private static final String DEFAULT_APP_MGT_TAG = "application_management";
private static final String DEFAULT_APP_MGT_LCYCLE_MGT_TAG = "lifecycle_management";
private static final String DEFAULT_APP_MGT_SUB_MGT_TAG = "subscription_management";
public static final String PERMISSION_PROPERTY_NAME = "name";
public static String getAuthenticatedUser() {
@ -108,6 +111,9 @@ public class APIUtil {
allowedApisTags.add(DEFAULT_CDMF_API_TAG);
allowedApisTags.add(DEFAULT_CERT_API_TAG);
allowedApisTags.add(DEFAULT_AGENT_API_TAG);
allowedApisTags.add(DEFAULT_APP_MGT_TAG);
allowedApisTags.add(DEFAULT_APP_MGT_LCYCLE_MGT_TAG);
allowedApisTags.add(DEFAULT_APP_MGT_SUB_MGT_TAG);
return allowedApisTags;
}

@ -27,8 +27,6 @@ import org.wso2.carbon.device.application.mgt.common.services.ApplicationRelease
import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager;
import org.wso2.carbon.device.application.mgt.common.services.CategoryManager;
import org.wso2.carbon.device.application.mgt.common.services.LifecycleStateManager;
import org.wso2.carbon.device.application.mgt.common.services.PlatformManager;
import org.wso2.carbon.device.application.mgt.common.services.PlatformStorageManager;
import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager;
import javax.ws.rs.core.Response;

@ -36,7 +36,6 @@ import org.wso2.carbon.device.application.mgt.api.beans.ErrorResponse;
import org.wso2.carbon.device.application.mgt.common.Application;
import org.wso2.carbon.device.application.mgt.common.ApplicationList;
import org.wso2.carbon.device.application.mgt.common.ApplicationRelease;
import org.wso2.carbon.device.application.mgt.common.Category;
import java.util.List;
import javax.validation.Valid;
@ -127,95 +126,95 @@ public interface ApplicationManagementAPI {
String SCOPE = "scope";
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "get all applications",
notes = "This will get all applications",
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:get")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully got application list.",
response = ApplicationList.class),
@ApiResponse(
code = 304,
message = "Not Modified. Empty body because the client already has the latest version "
+ "of the requested resource."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting the application list.",
response = ErrorResponse.class)
})
Response getApplications(
@ApiParam(
name = "offset",
value = "Provide from which position apps should return", defaultValue = "20")
@QueryParam("offset") int offset,
@ApiParam(
name = "limit",
value = "Provide how many apps it should return", defaultValue = "0")
@QueryParam("limit") int limit,
@ApiParam(
name = "searchQuery",
value = "Relevant search query to search on", defaultValue = "*")
@QueryParam("searchQuery") String searchQuery
);
@GET
@Path("/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "get the application specified by the UUID",
notes = "This will get the application identified by the UUID, if exists",
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:get")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully retrieved relevant application.",
response = Application.class),
@ApiResponse(
code = 404,
message = "Application not found"),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting relevant application.",
response = ErrorResponse.class)
})
Response getApplication(
@ApiParam(
name = "uuid",
value = "UUID of the application",
required = true)
@PathParam("uuid") String uuid,
@ApiParam(
name = "isWithImages",
value = "Whether to return application with images",
required = false)
@QueryParam("isWithImages") Boolean isWithImages
);
// @GET
// @Produces(MediaType.APPLICATION_JSON)
// @Consumes(MediaType.APPLICATION_JSON)
// @ApiOperation(
// consumes = MediaType.APPLICATION_JSON,
// produces = MediaType.APPLICATION_JSON,
// httpMethod = "GET",
// value = "get all applications",
// notes = "This will get all applications",
// tags = "Application Management",
// extensions = {
// @Extension(properties = {
// @ExtensionProperty(name = SCOPE, value = "perm:application:get")
// })
// }
// )
// @ApiResponses(
// value = {
// @ApiResponse(
// code = 200,
// message = "OK. \n Successfully got application list.",
// response = ApplicationList.class),
// @ApiResponse(
// code = 304,
// message = "Not Modified. Empty body because the client already has the latest version "
// + "of the requested resource."),
// @ApiResponse(
// code = 500,
// message = "Internal Server Error. \n Error occurred while getting the application list.",
// response = ErrorResponse.class)
// })
// Response getApplications(
// @ApiParam(
// name = "offset",
// value = "Provide from which position apps should return", defaultValue = "20")
// @QueryParam("offset") int offset,
// @ApiParam(
// name = "limit",
// value = "Provide how many apps it should return", defaultValue = "0")
// @QueryParam("limit") int limit,
// @ApiParam(
// name = "searchQuery",
// value = "Relevant search query to search on", defaultValue = "*")
// @QueryParam("searchQuery") String searchQuery
// );
//
// @GET
// @Path("/{uuid}")
// @Produces(MediaType.APPLICATION_JSON)
// @Consumes(MediaType.APPLICATION_JSON)
// @ApiOperation(
// consumes = MediaType.APPLICATION_JSON,
// produces = MediaType.APPLICATION_JSON,
// httpMethod = "GET",
// value = "get the application specified by the UUID",
// notes = "This will get the application identified by the UUID, if exists",
// tags = "Application Management",
// extensions = {
// @Extension(properties = {
// @ExtensionProperty(name = SCOPE, value = "perm:application:get")
// })
// }
// )
// @ApiResponses(
// value = {
// @ApiResponse(
// code = 200,
// message = "OK. \n Successfully retrieved relevant application.",
// response = Application.class),
// @ApiResponse(
// code = 404,
// message = "Application not found"),
// @ApiResponse(
// code = 500,
// message = "Internal Server Error. \n Error occurred while getting relevant application.",
// response = ErrorResponse.class)
// })
// Response getApplication(
// @ApiParam(
// name = "uuid",
// value = "UUID of the application",
// required = true)
// @PathParam("uuid") String uuid,
// @ApiParam(
// name = "isWithImages",
// value = "Whether to return application with images",
// required = false)
// @QueryParam("isWithImages") Boolean isWithImages
// );
@PUT
@Produces(MediaType.APPLICATION_JSON)
@ -290,6 +289,44 @@ public interface ApplicationManagementAPI {
required = true)
@Valid Application application);
@POST
@Path("/release")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(
consumes = MediaType.MULTIPART_FORM_DATA,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Create an application release",
notes = "This will create a new application release",
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:create")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 201,
message = "OK. \n Successfully created an application release.",
response = ApplicationRelease.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while releasing the application.",
response = ErrorResponse.class)
})
Response createApplicationRelease(
@ApiParam(
name = "UUID",
value = "Unique identifier of the Application",
required = true)
@PathParam("uuid") String applicationUUID,
@Multipart(value = "applicationRelease", type = "application/json") ApplicationRelease applicationRelease,
@Multipart(value = "binaryFile") Attachment binaryFile);
@POST
@Path("/upload-artifacts/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
@ -762,114 +799,114 @@ public interface ApplicationManagementAPI {
required = false)
@QueryParam("isDefault") boolean isDefault);
//
// @POST
// @Path("/category")
// @Produces(MediaType.APPLICATION_JSON)
// @Consumes(MediaType.APPLICATION_JSON)
// @ApiOperation(
// consumes = MediaType.APPLICATION_JSON,
// produces = MediaType.APPLICATION_JSON,
// httpMethod = "POST",
// value = "Create an application category",
// notes = "This will create a new category",
// tags = "Application Management",
// extensions = {
// @Extension(properties = {
// @ExtensionProperty(name = SCOPE, value = "perm:application-category:create")
// })
// }
// )
// @ApiResponses(
// value = {
// @ApiResponse(
// code = 201,
// message = "OK. \n Successfully created a new category.",
// response = Category.class),
// @ApiResponse(
// code = 400,
// message = "Bad request. Required parameters are not provided"),
// @ApiResponse(
// code = 500,
// message = "Internal Server Error. \n Error occurred while creating application category.",
// response = ErrorResponse.class)
// })
// Response createCategory(
// @ApiParam(
// name = "category",
// value = "The category that need to be created.",
// required = true)
// @Valid Category category);
@POST
@Path("/category")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Create an application category",
notes = "This will create a new category",
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application-category:create")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 201,
message = "OK. \n Successfully created a new category.",
response = Category.class),
@ApiResponse(
code = 400,
message = "Bad request. Required parameters are not provided"),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while creating application category.",
response = ErrorResponse.class)
})
Response createCategory(
@ApiParam(
name = "category",
value = "The category that need to be created.",
required = true)
@Valid Category category);
@GET
@Path("/category")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get existing application categories",
notes = "This will retrieve the existing categories",
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:create")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully retrieved existing categories.",
response = List.class),
@ApiResponse(
code = 400,
message = "Bad request. Required parameters are not provided"),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting the application "
+ "categories.",
response = ErrorResponse.class)
})
Response getCategories();
// @GET
// @Path("/category")
// @Produces(MediaType.APPLICATION_JSON)
// @Consumes(MediaType.APPLICATION_JSON)
// @ApiOperation(
// consumes = MediaType.APPLICATION_JSON,
// produces = MediaType.APPLICATION_JSON,
// httpMethod = "GET",
// value = "Get existing application categories",
// notes = "This will retrieve the existing categories",
// tags = "Application Management",
// extensions = {
// @Extension(properties = {
// @ExtensionProperty(name = SCOPE, value = "perm:application:create")
// })
// }
// )
// @ApiResponses(
// value = {
// @ApiResponse(
// code = 200,
// message = "OK. \n Successfully retrieved existing categories.",
// response = List.class),
// @ApiResponse(
// code = 400,
// message = "Bad request. Required parameters are not provided"),
// @ApiResponse(
// code = 500,
// message = "Internal Server Error. \n Error occurred while getting the application "
// + "categories.",
// response = ErrorResponse.class)
// })
// Response getCategories();
@DELETE
@Path("/category/{name}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "DELETE",
value = "Delete application category with the given name",
notes = "This will delete the application category with the given name",
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application-category:delete")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully deleted the application with the given name.",
response = Application.class),
@ApiResponse(
code = 400,
message = "Bad request. Required parameters are not provided"),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while deleting applcation category.",
response = ErrorResponse.class)
})
Response deleteCategory(
@ApiParam(
name = "Name",
value = "Name of the application category",
required = true)
@PathParam("name") String name);
// @DELETE
// @Path("/category/{name}")
// @Produces(MediaType.APPLICATION_JSON)
// @Consumes(MediaType.APPLICATION_JSON)
// @ApiOperation(
// consumes = MediaType.APPLICATION_JSON,
// produces = MediaType.APPLICATION_JSON,
// httpMethod = "DELETE",
// value = "Delete application category with the given name",
// notes = "This will delete the application category with the given name",
// tags = "Application Management",
// extensions = {
// @Extension(properties = {
// @ExtensionProperty(name = SCOPE, value = "perm:application-category:delete")
// })
// }
// )
// @ApiResponses(
// value = {
// @ApiResponse(
// code = 200,
// message = "OK. \n Successfully deleted the application with the given name.",
// response = Application.class),
// @ApiResponse(
// code = 400,
// message = "Bad request. Required parameters are not provided"),
// @ApiResponse(
// code = 500,
// message = "Internal Server Error. \n Error occurred while deleting applcation category.",
// response = ErrorResponse.class)
// })
// Response deleteCategory(
// @ApiParam(
// name = "Name",
// value = "Name of the application category",
// required = true)
// @PathParam("name") String name);
}

@ -1,417 +0,0 @@
/*
* Copyright (c) 2017, 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.application.mgt.api.services;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Extension;
import io.swagger.annotations.ExtensionProperty;
import io.swagger.annotations.Info;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Tag;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.cxf.jaxrs.ext.multipart.Multipart;
import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.application.mgt.api.beans.ErrorResponse;
import org.wso2.carbon.device.application.mgt.common.Platform;
import javax.validation.constraints.Size;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* API for handling platform related operations in application management.
*/
@SwaggerDefinition(
info = @Info(
version = "1.0.0",
title = "Platform Management Service",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = "name", value = "PlatformManagementService"),
@ExtensionProperty(name = "context", value = "/api/application-mgt/v1.0/platforms"),
})
}
),
tags = {
@Tag(name = "device_management, application_management", description = "Platform Management APIS "
+ "related with Application Management")
}
)
@Scopes (
scopes = {
@org.wso2.carbon.apimgt.annotations.api.Scope(
name = "Get platform details",
description = "Get platform details",
key = "perm:platform:get",
permissions = {"/device-mgt/platform/get"}
),
@org.wso2.carbon.apimgt.annotations.api.Scope(
name = "Add a platform",
description = "Add a platform",
key = "perm:platform:add",
permissions = {"/device-mgt/platform/add"}
),
@org.wso2.carbon.apimgt.annotations.api.Scope(
name = "Update a platform",
description = "Update a platform",
key = "perm:platform:update",
permissions = {"/device-mgt/platform/update"}
),
@org.wso2.carbon.apimgt.annotations.api.Scope(
name = "Remove a platform",
description = "Remove a platform",
key = "perm:platform:remove",
permissions = {"/device-mgt/platform/remove"}
)
}
)
@Api(value = "Platform Management", description = "This API carries all platform management related operations " +
"such as get all the available platform for a tenant, etc.")
@Path("/platforms")
@Produces(MediaType.APPLICATION_JSON)
public interface PlatformManagementAPI {
String SCOPE = "scope";
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "get all platforms",
notes = "This will get all platforms that is visible for tenants",
tags = "Platform Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:platform:get")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully got platforms list.",
response = Platform.class,
responseContainer = "List"),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting the platform list.",
response = ErrorResponse.class)
})
Response getPlatforms(
@ApiParam(name = "status", allowableValues = "ENABLED, DISABLED, ALL", value =
"Provide the status of platform for that tenant:\n"
+ "- ENABLED: The platforms that are currently enabled for the tenant\n"
+ "- DISABLED: The platforms that can be used by the tenant but disabled "
+ "to be used for tenant\n"
+ "- ALL: All the list of platforms that can be used by the tenant")
@QueryParam("status")
@Size(max = 45)
String status,
@ApiParam(name = "tag", defaultValue = "Tag value that we need to search the platform for")
@QueryParam("tag") String tag
);
@GET
@Path("/{identifier}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "get platform",
notes = "This will return the platform which is registered with {identifier}",
tags = "Platform Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:platform:get")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully got requested platform.",
response = Platform.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting the platform.",
response = ErrorResponse.class)
})
Response getPlatform(
@ApiParam(
name = "identifier",
required = true)
@PathParam("identifier")
@Size(max = 45)
String identifier
);
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(
consumes = MediaType.MULTIPART_FORM_DATA,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Add Platform",
notes = "This will a platform for the tenant space",
tags = "Platform Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:platform:add")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully added the platform"),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request parameters passed."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting the platform list.",
response = ErrorResponse.class)
})
Response addPlatform(
@Multipart(value = "Platform", type = "application/json") Platform platform,
@Multipart(value = "icon", required = false) Attachment iconFile
);
@PUT
@Path("/{identifier}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Update Platform",
notes = "This will update the platform configuration for the tenant space",
tags = "Platform Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:platform:update")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully updated the platform"),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request parameters passed."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting the platform list.",
response = ErrorResponse.class)
})
Response updatePlatform(
@ApiParam(
name = "platform",
value = "The payload of the platform",
required = true)
Platform platform,
@ApiParam(
name = "identifier",
required = true)
@PathParam("identifier")
@Size(max = 45)
String identifier
);
@DELETE
@Path("/{identifier}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "DELETE",
value = "Remove Platform",
notes = "This will remove the relevant platform.",
tags = "Platform Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:platform:remove")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully deleted the platform"),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while deleting the platform.",
response = ErrorResponse.class)
})
Response removePlatform(
@ApiParam(
name = "identifier",
required = true)
@PathParam("identifier")
@Size(max = 45)
String identifier
);
@PUT
@Path("update-status/{identifier}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Update Platform status",
notes = "This will update the platform status for the tenant space",
tags = "Platform Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:platform:update")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully updated the platform."),
@ApiResponse(
code = 404,
message = "Not found. \n Non-file based platform not found to update."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting the platform list.",
response = ErrorResponse.class)
})
Response updatePlatformStatus(
@ApiParam(
name = "identifier",
required = true)
@PathParam("identifier")
@Size(max = 45)
String identifier,
@ApiParam(name = "status", allowableValues = "ENABLED, DISABLED", value =
"Provide the status of platform for that tenant:\n"
+ "- ENABLED: The platforms that are currently enabled for the tenant\n"
+ "- DISABLED: The platforms that currently disabled "
+ "to be used for tenant\n", required = true)
@QueryParam("status")
String status
);
@GET
@Path("tags/{name}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "get platform tags that starts with the given character sequence",
notes = "This will get all platform tags that has the given character sequence ",
tags = "Platform Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:platform:add")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully retrieved platform tags.",
response = Platform.class,
responseContainer = "List"),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting the platform tags.",
response = ErrorResponse.class)
})
Response getPlatformTags(
@ApiParam(name = "name", value = "The initial part of the name of platform tags that we need to retrieve",
required = true)
@PathParam("name") @Size(min = 3) String name
);
@POST
@Path("/{identifier}/icon")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(
consumes = MediaType.MULTIPART_FORM_DATA,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Update Platform icon",
notes = "This will update the platform icon",
tags = "Platform Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:platform:update")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully updated the platform icon"),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request parameters passed."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while updating the platform icon.",
response = ErrorResponse.class)
})
Response updatePlatformIcon(
@ApiParam(
name = "identifier",
required = true)
@PathParam("identifier")
@Size(max = 45)
String identifier,
@Multipart(value = "icon") Attachment iconFile
);
}

@ -43,7 +43,7 @@ import javax.ws.rs.core.Response;
}
),
tags = {
@Tag(name = "Subscription_management, device_management", description = "Subscription Management " +
@Tag(name = "subscription_management, device_management", description = "Subscription Management " +
"related "
+ "APIs")
}

@ -28,7 +28,6 @@ import org.wso2.carbon.device.application.mgt.api.services.ApplicationManagement
import org.wso2.carbon.device.application.mgt.common.Application;
import org.wso2.carbon.device.application.mgt.common.ApplicationList;
import org.wso2.carbon.device.application.mgt.common.ApplicationRelease;
import org.wso2.carbon.device.application.mgt.common.Category;
import org.wso2.carbon.device.application.mgt.common.Filter;
import org.wso2.carbon.device.application.mgt.common.ImageArtifact;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
@ -39,6 +38,7 @@ import org.wso2.carbon.device.application.mgt.common.services.ApplicationRelease
import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager;
import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException;
import org.wso2.carbon.device.application.mgt.core.util.Constants;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import java.io.IOException;
import java.io.InputStream;
@ -69,79 +69,79 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
private static final int DEFAULT_LIMIT = 20;
private static Log log = LogFactory.getLog(ApplicationManagementAPIImpl.class);
@GET
@Consumes("application/json")
public Response getApplications(@QueryParam("offset") int offset, @QueryParam("limit") int limit,
@QueryParam("query") String searchQuery) {
ApplicationManager applicationManager = APIUtil.getApplicationManager();
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
try {
if (limit == 0) {
limit = DEFAULT_LIMIT;
}
Filter filter = new Filter();
filter.setOffset(offset);
filter.setLimit(limit);
filter.setSearchQuery(searchQuery);
ApplicationList applications = applicationManager.getApplications(filter);
for (Application application : applications.getApplications()) {
ImageArtifact imageArtifact = applicationStorageManager.getImageArtifact(application.getUuid(),
Constants.IMAGE_ARTIFACTS[0], 0);
application.setIcon(imageArtifact);
}
return Response.status(Response.Status.OK).entity(applications).build();
} catch (NotFoundException e) {
return Response.status(Response.Status.NOT_FOUND).build();
} catch (ApplicationManagementException e) {
String msg = "Error occurred while getting the application list";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).build();
} catch (ApplicationStorageManagementException e) {
log.error("Error occurred while getting the image artifacts of the application", e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
@GET
@Consumes("application/json")
@Path("/{uuid}")
public Response getApplication(@PathParam("uuid") String uuid, @QueryParam("isWithImages") Boolean isWithImages) {
ApplicationManager applicationManager = APIUtil.getApplicationManager();
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
try {
Application application = applicationManager.getApplication(uuid);
if (application == null) {
return Response.status(Response.Status.NOT_FOUND)
.entity("Application with UUID " + uuid + " not found").build();
}
if (isWithImages != null && isWithImages) {
ImageArtifact icon = applicationStorageManager.getImageArtifact(uuid, Constants.IMAGE_ARTIFACTS[0], 0);
ImageArtifact banner = applicationStorageManager.getImageArtifact(uuid, Constants.IMAGE_ARTIFACTS[1],
0);
int screenShotCount = application.getScreenShotCount();
for (int count = 1; count < screenShotCount; count++) {
ImageArtifact screenShot = applicationStorageManager.getImageArtifact(uuid, Constants
.IMAGE_ARTIFACTS[2], count);
application.addScreenShot(screenShot);
}
application.setIcon(icon);
application.setBanner(banner);
}
return Response.status(Response.Status.OK).entity(application).build();
} catch (NotFoundException e) {
return Response.status(Response.Status.NOT_FOUND).build();
} catch (ApplicationManagementException e) {
log.error("Error occurred while getting application with the uuid " + uuid, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} catch (ApplicationStorageManagementException e) {
log.error("Error occurred while getting the image artifacts of the application with the uuid " + uuid, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
// @GET
// @Consumes("application/json")
// public Response getApplications(@QueryParam("offset") int offset, @QueryParam("limit") int limit,
// @QueryParam("query") String searchQuery) {
// ApplicationManager applicationManager = APIUtil.getApplicationManager();
// ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
//
// try {
// if (limit == 0) {
// limit = DEFAULT_LIMIT;
// }
// Filter filter = new Filter();
// filter.setOffset(offset);
// filter.setLimit(limit);
// filter.setSearchQuery(searchQuery);
//
// ApplicationList applications = applicationManager.getApplications(filter);
//
// for (Application application : applications.getApplications()) {
// ImageArtifact imageArtifact = applicationStorageManager.getImageArtifact(application.getUuid(),
// Constants.IMAGE_ARTIFACTS[0], 0);
// application.setIcon(imageArtifact);
// }
// return Response.status(Response.Status.OK).entity(applications).build();
// } catch (NotFoundException e) {
// return Response.status(Response.Status.NOT_FOUND).build();
// } catch (ApplicationManagementException e) {
// String msg = "Error occurred while getting the application list";
// log.error(msg, e);
// return Response.status(Response.Status.BAD_REQUEST).build();
// } catch (ApplicationStorageManagementException e) {
// log.error("Error occurred while getting the image artifacts of the application", e);
// return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
// }
// }
//
// @GET
// @Consumes("application/json")
// @Path("/{uuid}")
// public Response getApplication(@PathParam("uuid") String uuid, @QueryParam("isWithImages") Boolean isWithImages) {
// ApplicationManager applicationManager = APIUtil.getApplicationManager();
// ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
// try {
// Application application = applicationManager.getApplication(uuid);
// if (application == null) {
// return Response.status(Response.Status.NOT_FOUND)
// .entity("Application with UUID " + uuid + " not found").build();
// }
//
// if (isWithImages != null && isWithImages) {
// ImageArtifact icon = applicationStorageManager.getImageArtifact(uuid, Constants.IMAGE_ARTIFACTS[0], 0);
// ImageArtifact banner = applicationStorageManager.getImageArtifact(uuid, Constants.IMAGE_ARTIFACTS[1],
// 0);
// int screenShotCount = application.getScreenShotCount();
// for (int count = 1; count < screenShotCount; count++) {
// ImageArtifact screenShot = applicationStorageManager.getImageArtifact(uuid, Constants
// .IMAGE_ARTIFACTS[2], count);
// application.addScreenShot(screenShot);
// }
// application.setIcon(icon);
// application.setBanner(banner);
// }
// return Response.status(Response.Status.OK).entity(application).build();
// } catch (NotFoundException e) {
// return Response.status(Response.Status.NOT_FOUND).build();
// } catch (ApplicationManagementException e) {
// log.error("Error occurred while getting application with the uuid " + uuid, e);
// return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
// } catch (ApplicationStorageManagementException e) {
// log.error("Error occurred while getting the image artifacts of the application with the uuid " + uuid, e);
// return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
// }
// }
@PUT
@Consumes("application/json")
@ -199,20 +199,66 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
}
}
//working on this//
@POST
@Consumes("application/json")
public Response createApplication(@Valid Application application) {
ApplicationManager applicationManager = APIUtil.getApplicationManager();
try {
application = applicationManager.createApplication(application);
return Response.status(Response.Status.OK).entity(application).build();
} catch (ApplicationManagementException e) {
if (application != null){
return Response.status(Response.Status.OK).entity(application).build();
}else{
String msg = "Given device type is not matched with existing device types";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).build();
}
}catch (DeviceManagementDAOException e) {
String msg = "Error occurred while getting the device type";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).build();
}catch (ApplicationManagementException e) {
String msg = "Error occurred while creating the application";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
@Override
@POST
@Path("/release")
public Response createApplicationRelease(@Multipart("applicationRelease") ApplicationRelease applicationRelease,
@Multipart("binaryFile") Attachment binaryFile) {
ApplicationReleaseManager applicationReleaseManager = APIUtil.getApplicationReleaseManager();
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
try {
applicationRelease = applicationReleaseManager.createRelease(applicationUUID, applicationRelease);
if (binaryFile != null) {
applicationStorageManager.uploadReleaseArtifacts(applicationUUID, applicationRelease.getVersion(),
binaryFile.getDataHandler().getInputStream());
}
return Response.status(Response.Status.CREATED).entity(applicationRelease).build();
} catch (ApplicationManagementException e) {
log.error("Error while creating an application release for the application with UUID " + applicationUUID,
e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} catch (IOException e) {
String errorMessage =
"Error while uploading binary file for the application release of the application with UUID "
+ applicationUUID;
log.error(errorMessage, e);
return APIUtil.getResponse(new ApplicationManagementException(errorMessage, e),
Response.Status.INTERNAL_SERVER_ERROR);
} catch (ResourceManagementException e) {
log.error("Error occurred while uploading the releases artifacts of the application with the uuid "
+ applicationUUID + " for the release " + applicationRelease.getVersion(), e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
//working on this//
@Override
@POST
@Path("/upload-image-artifacts/{uuid}")
@ -346,39 +392,39 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
}
}
@Override
@POST
@Path("/release/{uuid}")
public Response createApplicationRelease(@PathParam("uuid") String applicationUUID,
@Multipart("applicationRelease") ApplicationRelease applicationRelease,
@Multipart("binaryFile") Attachment binaryFile) {
ApplicationReleaseManager applicationReleaseManager = APIUtil.getApplicationReleaseManager();
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
try {
applicationRelease = applicationReleaseManager.createRelease(applicationUUID, applicationRelease);
if (binaryFile != null) {
applicationStorageManager.uploadReleaseArtifacts(applicationUUID, applicationRelease.getVersionName(),
binaryFile.getDataHandler().getInputStream());
}
return Response.status(Response.Status.CREATED).entity(applicationRelease).build();
} catch (ApplicationManagementException e) {
log.error("Error while creating an application release for the application with UUID " + applicationUUID,
e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} catch (IOException e) {
String errorMessage =
"Error while uploading binary file for the application release of the application with UUID "
+ applicationUUID;
log.error(errorMessage, e);
return APIUtil.getResponse(new ApplicationManagementException(errorMessage, e),
Response.Status.INTERNAL_SERVER_ERROR);
} catch (ResourceManagementException e) {
log.error("Error occurred while uploading the releases artifacts of the application with the uuid "
+ applicationUUID + " for the release " + applicationRelease.getVersionName(), e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
// @Override
// @POST
// @Path("/release/{uuid}")
// public Response createApplicationRelease(@PathParam("uuid") String applicationUUID,
// @Multipart("applicationRelease") ApplicationRelease applicationRelease,
// @Multipart("binaryFile") Attachment binaryFile) {
// ApplicationReleaseManager applicationReleaseManager = APIUtil.getApplicationReleaseManager();
// ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
// try {
// applicationRelease = applicationReleaseManager.createRelease(applicationUUID, applicationRelease);
//
// if (binaryFile != null) {
// applicationStorageManager.uploadReleaseArtifacts(applicationUUID, applicationRelease.getVersion(),
// binaryFile.getDataHandler().getInputStream());
// }
// return Response.status(Response.Status.CREATED).entity(applicationRelease).build();
// } catch (ApplicationManagementException e) {
// log.error("Error while creating an application release for the application with UUID " + applicationUUID,
// e);
// return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
// } catch (IOException e) {
// String errorMessage =
// "Error while uploading binary file for the application release of the application with UUID "
// + applicationUUID;
// log.error(errorMessage, e);
// return APIUtil.getResponse(new ApplicationManagementException(errorMessage, e),
// Response.Status.INTERNAL_SERVER_ERROR);
// } catch (ResourceManagementException e) {
// log.error("Error occurred while uploading the releases artifacts of the application with the uuid "
// + applicationUUID + " for the release " + applicationRelease.getVersion(), e);
// return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
// }
// }
@Override
@PUT
@ -393,7 +439,7 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
applicationRelease = applicationReleaseManager.updateRelease(applicationUUID, applicationRelease);
}
if (binaryFile != null) {
String version = applicationRelease == null ? null : applicationRelease.getVersionName();
String version = applicationRelease == null ? null : applicationRelease.getVersion();
if (version == null) {
return Response.status(Response.Status.BAD_REQUEST).entity("Version cannot be null. Version is a "
@ -415,7 +461,7 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
+ applicationUUID), Response.Status.INTERNAL_SERVER_ERROR);
} catch (ResourceManagementException e) {
log.error("Error occurred while updating the releases artifacts of the application with the uuid "
+ applicationUUID + " for the release " + applicationRelease.getVersionName(), e);
+ applicationUUID + " for the release " + applicationRelease.getVersion(), e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
@ -543,51 +589,52 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
@Override
@POST
@Path("/category")
public Response createCategory(@Valid Category category) {
if (category == null) {
return Response.status(Response.Status.BAD_REQUEST).entity("Category is null. cannot create the "
+ "category").build();
}
try {
Category createdCategory = APIUtil.getCategoryManager().createCategory(category);
return Response.status(Response.Status.CREATED).entity(createdCategory).build();
} catch (ApplicationManagementException e) {
log.error("Application Management Exception while trying to create the application category", e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
@Override
@GET
@Path("/category")
public Response getCategories() {
List<Category> categories;
try {
categories = APIUtil.getCategoryManager().getCategories();
return Response.status(Response.Status.OK).entity(categories).build();
} catch (ApplicationManagementException e) {
log.error("Application Management Exception while trying to get application categories", e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
@Override
@DELETE
@Path("/category/{name}")
public Response deleteCategory(@PathParam("name") String name) {
if (name == null || name.isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).entity("Name cannot be null or empty.").build();
}
try {
APIUtil.getCategoryManager().deleteCategory(name);
return Response.status(Response.Status.OK).entity("Successfully deleted the category.").build();
} catch (ApplicationManagementException e) {
log.error("Application Management Exception while trying to delete category", e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
}
// @Override
// @POST
// @Path("/category")
// public Response createCategory(@Valid Category category) {
// if (category == null) {
// return Response.status(Response.Status.BAD_REQUEST).entity("Category is null. cannot create the "
// + "category").build();
// }
// try {
// Category createdCategory = APIUtil.getCategoryManager().createCategory(category);
// return Response.status(Response.Status.CREATED).entity(createdCategory).build();
// } catch (ApplicationManagementException e) {
// log.error("Application Management Exception while trying to create the application category", e);
// return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
// }
// }
//
// @Override
// @GET
// @Path("/category")
// public Response getCategories() {
// List<Category> categories;
// try {
// categories = APIUtil.getCategoryManager().getCategories();
// return Response.status(Response.Status.OK).entity(categories).build();
// } catch (ApplicationManagementException e) {
// log.error("Application Management Exception while trying to get application categories", e);
// return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
// }
// }
//
// @Override
// @DELETE
// @Path("/category/{name}")
// public Response deleteCategory(@PathParam("name") String name) {
// if (name == null || name.isEmpty()) {
// return Response.status(Response.Status.BAD_REQUEST).entity("Name cannot be null or empty.").build();
// }
// try {
// APIUtil.getCategoryManager().deleteCategory(name);
// return Response.status(Response.Status.OK).entity("Successfully deleted the category.").build();
// } catch (ApplicationManagementException e) {
// log.error("Application Management Exception while trying to delete category", e);
// return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
// }
// }
//}

@ -1,284 +0,0 @@
/*
* Copyright (c) 2017, 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.application.mgt.api.services.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.cxf.jaxrs.ext.multipart.Multipart;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.api.APIUtil;
import org.wso2.carbon.device.application.mgt.api.services.PlatformManagementAPI;
import org.wso2.carbon.device.application.mgt.common.ImageArtifact;
import org.wso2.carbon.device.application.mgt.common.Platform;
import org.wso2.carbon.device.application.mgt.common.exception.PlatformManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.PlatformStorageManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException;
import org.wso2.carbon.device.application.mgt.common.services.PlatformStorageManager;
import org.wso2.carbon.device.application.mgt.core.exception.PlatformManagementDAOException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.validation.constraints.Size;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
/**
* Implementation of PlatformManagement APIs.
*/
@Path("/platforms")
public class PlatformManagementAPIImpl implements PlatformManagementAPI {
private static final String ALL_STATUS = "ALL";
private static final String ENABLED_STATUS = "ENABLED";
private static final String DISABLED_STATUS = "DISABLED";
private static Log log = LogFactory.getLog(PlatformManagementAPIImpl.class);
@GET
@Override
public Response getPlatforms(@QueryParam("status") String status, @QueryParam("tag") String tag) {
int tenantID = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
PlatformStorageManager platformStorageManager = APIUtil.getPlatformStorageManager();
if (log.isDebugEnabled()) {
log.debug("API request received for getting the platforms with the status " + status);
}
try {
List<Platform> platforms = APIUtil.getPlatformManager().getPlatforms(tenantID);
List<Platform> results;
List<Platform> filteredPlatforms = new ArrayList<>();
if (status != null) {
if (status.contentEquals(ALL_STATUS)) {
results = platforms;
} else if (status.contentEquals(ENABLED_STATUS)) {
results = new ArrayList<>();
for (Platform platform : platforms) {
if (platform.isEnabled()) {
results.add(platform);
}
}
} else if (status.contentEquals(DISABLED_STATUS)) {
results = new ArrayList<>();
for (Platform platform : platforms) {
if (!platform.isEnabled()) {
results.add(platform);
}
}
} else {
results = platforms;
}
} else {
results = platforms;
}
if (results != null) {
for (Platform platform : results) {
if (tag == null || tag.isEmpty() || (platform.getTags() != null && platform.getTags()
.contains(tag))) {
platform.setIcon(platformStorageManager.getIcon(platform.getIdentifier()));
filteredPlatforms.add(platform);
}
}
if (log.isDebugEnabled()) {
log.debug("Number of platforms with the status " + status + " : " + results.size());
}
}
return Response.status(Response.Status.OK).entity(filteredPlatforms).build();
} catch (PlatformManagementException e) {
log.error("Error while getting the platforms for tenant - " + tenantID, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} catch (PlatformStorageManagementException e) {
log.error("Error while getting platform icons for the tenant : " + tenantID, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
@GET
@Override
@Path("/{identifier}")
public Response getPlatform(@PathParam("identifier") String id) {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
try {
Platform platform = APIUtil.getPlatformManager().getPlatform(tenantId, id);
if (platform == null) {
return Response.status(Response.Status.NOT_FOUND).entity("Platform not found").build();
}
ImageArtifact icon = APIUtil.getPlatformStorageManager().getIcon(id);
if (icon != null) {
platform.setIcon(icon);
}
return Response.status(Response.Status.OK).entity(platform).build();
} catch (PlatformManagementDAOException e) {
log.error("Error while trying the get the platform with the identifier : " + id + " for the tenant :"
+ tenantId, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} catch (PlatformManagementException e) {
log.error("Error while trying the get the platform with the identifier : " + id + " for the tenant :"
+ tenantId, e);
return APIUtil.getResponse(e, Response.Status.NOT_FOUND);
} catch (PlatformStorageManagementException e) {
log.error("Platform Storage Management Exception while trying to get the icon for the platform : " + id
+ " for the tenant : " + tenantId, e);
return APIUtil.getResponse(e, Response.Status.NOT_FOUND);
}
}
@POST
@Override
public Response addPlatform(@Multipart("platform") Platform platform, @Multipart("icon")Attachment icon) {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
try {
if (platform != null) {
if (platform.validate()) {
APIUtil.getPlatformManager().register(tenantId, platform);
if (icon != null) {
InputStream iconFileStream = icon.getDataHandler().getInputStream();
APIUtil.getPlatformStorageManager().uploadIcon(platform.getIdentifier(), iconFileStream);
}
return Response.status(Response.Status.CREATED).build();
} else {
return APIUtil
.getResponse("Invalid payload! Platform 'identifier' and 'name' are mandatory fields!",
Response.Status.BAD_REQUEST);
}
} else {
return APIUtil.getResponse("Invalid payload! Platform needs to be passed as payload!",
Response.Status.BAD_REQUEST);
}
} catch (PlatformManagementException e) {
log.error("Platform Management Exception while trying to add the platform with identifier : " + platform
.getIdentifier() + " for the tenant : " + tenantId, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} catch (IOException e) {
log.error("IO Exception while trying to save platform icon for the platform : " + platform.getIdentifier(),
e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} catch (ResourceManagementException e) {
log.error("Storage Exception while trying to save platform icon for the platform : " + platform
.getIdentifier(), e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
@PUT
@Path("/{identifier}")
@Override
public Response updatePlatform(Platform platform, @PathParam("identifier") @Size(max = 45) String id) {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
try {
APIUtil.getPlatformManager().update(tenantId, id, platform);
return Response.status(Response.Status.OK).build();
} catch (PlatformManagementException e) {
log.error("Error while updating the platform - " + id + " for tenant domain - " + tenantId, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
@DELETE
@Path("/{identifier}")
@Override
public Response removePlatform(@PathParam("identifier") @Size(max = 45) String id) {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
try {
APIUtil.getPlatformStorageManager().deleteIcon(id);
APIUtil.getPlatformManager().unregister(tenantId, id, false);
return Response.status(Response.Status.OK).build();
} catch (PlatformManagementException e) {
log.error(
"Platform Management Exception while trying to un-register the platform with the identifier : " + id
+ " for the tenant : " + tenantId, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} catch (PlatformStorageManagementException e) {
log.error("Platform Storage Management Exception while trying to delete the icon of the platform with "
+ "identifier for the tenant :" + tenantId, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
@PUT
@Path("update-status/{identifier}")
@Override
public Response updatePlatformStatus(@PathParam("identifier") @Size(max = 45) String id, @QueryParam("status")
String status) {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
try {
APIUtil.getPlatformManager().updatePlatformStatus(tenantId, id, status);
return Response.status(Response.Status.OK).build();
} catch (PlatformManagementDAOException e) {
log.error("Platform Management Database Exception while trying to update the status of the platform with "
+ "the identifier : " + id + " for the tenant : " + tenantId, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} catch (PlatformManagementException e) {
log.error("Platform Management Exception while trying to update the status of the platform with the "
+ "identifier : " + id + " for the tenant : " + tenantId, e);
return APIUtil.getResponse(e, Response.Status.NOT_FOUND);
}
}
@GET
@Path("tags/{name}")
@Override
public Response getPlatformTags(@PathParam("name") String name) {
if (name == null || name.isEmpty() || name.length() < 3) {
return APIUtil.getResponse("In order to get platform tags, it is required to pass the first 3 "
+ "characters of the platform tag name", Response.Status.INTERNAL_SERVER_ERROR);
}
try {
List<String> platformTags = APIUtil.getPlatformManager().getPlatformTags(name);
return Response.status(Response.Status.OK).entity(platformTags).build();
} catch (PlatformManagementException e) {
log.error("Platform Management Exception while trying to get the platform tags with starting character "
+ "sequence " + name, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
@POST
@Path("{identifier}/icon")
@Override
public Response updatePlatformIcon(@PathParam("identifier") String identifier, @Multipart("icon") Attachment
icon) {
try {
if (icon != null) {
InputStream iconFileStream = icon.getDataHandler().getInputStream();
APIUtil.getPlatformStorageManager().uploadIcon(identifier, iconFileStream);
return Response.status(Response.Status.OK)
.entity("Icon file is successfully updated for the platform :" + identifier).build();
} else {
return Response.status(Response.Status.BAD_REQUEST).entity("Icon file is not provided to update")
.build();
}
} catch (ResourceManagementException e) {
log.error("Resource Management exception while trying to update the icon for the platform " + identifier);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} catch (IOException e) {
log.error("IO exception while trying to update the icon for the platform " + identifier);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
}

@ -26,7 +26,6 @@ http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxrs:server id="applicationMgtService" address="/">
<jaxrs:serviceBeans>
<ref bean="applicationMgtServiceBean"/>
<ref bean="platformMgtServiceBean"/>
<ref bean="lifecycleMgtServiceBean"/>
<ref bean="subscriptionMgtServiceBean"/>
</jaxrs:serviceBeans>
@ -37,7 +36,6 @@ http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
</jaxrs:server>
<bean id="applicationMgtServiceBean" class="org.wso2.carbon.device.application.mgt.api.services.impl.ApplicationManagementAPIImpl"/>
<bean id="platformMgtServiceBean" class="org.wso2.carbon.device.application.mgt.api.services.impl.PlatformManagementAPIImpl" />
<bean id="lifecycleMgtServiceBean" class="org.wso2.carbon.device.application.mgt.api.services.impl.LifecycleManagementAPIImpl" />
<bean id="subscriptionMgtServiceBean" class="org.wso2.carbon.device.application.mgt.api.services.impl.SubscriptionManagementAPIImpl"/>
<bean id="jsonProvider" class="org.wso2.carbon.device.application.mgt.api.JSONMessageHandler"/>

@ -108,6 +108,10 @@
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
</dependency>
</dependencies>
</project>

@ -20,11 +20,8 @@ package org.wso2.carbon.device.application.mgt.common;
import org.wso2.carbon.device.application.mgt.common.jaxrs.Exclude;
import java.util.ArrayList;
import java.util.Date;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import java.util.List;
import java.util.Map;
/**
* Application represents the an Application in Application Store.
@ -34,219 +31,119 @@ public class Application {
@Exclude
private int id;
private String uuid;
private String name;
private String shortDescription;
private String description;
private String videoName;
private List<String> tags;
private Platform platform;
private List<Comment> comments;
private Category category;
private String appCategory;
private Map<String, String> properties;
private String type;
private Date createdAt;
private int isFree;
private Date modifiedAt;
private String paymentCurrency;
private Payment payment;
private Lifecycle currentLifecycle;
private List<ApplicationRelease> releases;
private Visibility visibility;
private int screenShotCount;
private List<Tag> tags;
private User user;
private ImageArtifact icon;
private List<UnrestrictedRole> unrestrictedRoles;
private ImageArtifact banner;
private int isRestricted;
private List<ImageArtifact> screenShots = new ArrayList<>();
private ApplicationRelease releaseVersion;
private DeviceType devicetype;
public int getId() {
return id;
}
public List<ApplicationRelease> getReleases() {
return releases;
}
public void setReleases(List<ApplicationRelease> releases) {
this.releases = releases;
}
public List<Comment> getComments() {
return comments;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
public Payment getPayment() {
return payment;
}
public void setPayment(Payment payment) {
this.payment = payment;
}
public Lifecycle getCurrentLifecycle() {
return currentLifecycle;
}
public void setCurrentLifecycle(Lifecycle currentLifecycle) {
this.currentLifecycle = currentLifecycle;
}
public void setId(int id) {
this.id = id;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getShortDescription() {
return shortDescription;
}
public void setName(String name) { this.name = name; }
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
public String getAppCategory() {
return appCategory;
}
public String getDescription() {
return description;
public void setAppCategory(String appCategory) {
this.appCategory = appCategory;
}
public void setDescription(String description) {
this.description = description;
}
public String getVideoName() {
return videoName;
}
public void setVideoName(String videoName) {
this.videoName = videoName;
}
public List<String> getTags() {
public List<Tag> getTags() {
return tags;
}
public void setTags(List<String> tags) {
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public Platform getPlatform() {
return platform;
}
public void setPlatform(Platform platform) {
this.platform = platform;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public Map<String, String> getProperties() {
return properties;
public User getUser() {
return user;
}
public void setProperties(Map<String, String> properties) {
this.properties = properties;
public void setUser(User user) {
this.user = user;
}
public Date getCreatedAt() {
return createdAt;
public List<UnrestrictedRole> getUnrestrictedRoles() {
return unrestrictedRoles;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
public void setUnrestrictedRoles(List<UnrestrictedRole> unrestrictedRoles) {
this.unrestrictedRoles = unrestrictedRoles;
}
public Date getModifiedAt() {
return modifiedAt;
public ApplicationRelease getReleaseVersion() {
return releaseVersion;
}
public void setModifiedAt(Date modifiedAt) {
this.modifiedAt = modifiedAt;
public void setReleaseVersion(ApplicationRelease releaseVersion) {
this.releaseVersion = releaseVersion;
}
public Visibility getVisibility() {
return visibility;
public String getType() {
return type;
}
public void setVisibility(Visibility visibility) {
this.visibility = visibility;
public void setType(String type) {
this.type = type;
}
public User getUser() {
return user;
public int getIsFree() {
return isFree;
}
public void setUser(User user) {
this.user = user;
public void setIsFree(int isFree) {
this.isFree = isFree;
}
public void setScreenShotCount(int screenShotCount) {
this.screenShotCount = screenShotCount;
public String getPaymentCurrency() {
return paymentCurrency;
}
public int getScreenShotCount() {
return screenShotCount;
public void setPaymentCurrency(String paymentCurrency) {
this.paymentCurrency = paymentCurrency;
}
public void setIcon(ImageArtifact icon) {
this.icon = icon;
public int getIsRestricted() {
return isRestricted;
}
public void setBanner(ImageArtifact banner) {
this.banner = banner;
public void setIsRestricted(int isRestricted) {
this.isRestricted = isRestricted;
}
public void addScreenShot(ImageArtifact screenShot) {
this.screenShots.add(screenShot);
public DeviceType getDevicetype() {
return devicetype;
}
@Override
public String toString() {
String app = "UUID : " + uuid + "\tName : " + name + "\tShort Description : "
+ shortDescription;
if (currentLifecycle != null) {
app += "\tLifecycle State : " + currentLifecycle.getLifecycleState();
}
return app;
public void setDevicetype(DeviceType devicetype) {
this.devicetype = devicetype;
}
}

@ -20,108 +20,200 @@ package org.wso2.carbon.device.application.mgt.common;
import org.wso2.carbon.device.application.mgt.common.jaxrs.Exclude;
import java.util.Date;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
/**
* This class holds the details when releasing an Application to application store.
*/
public class ApplicationRelease {
private enum Channel {
private enum ReleaseType {
PRODUCTION, ALPHA, BETA
}
@Exclude
private int id;
private int versionId;
private String version;
private String versionName;
private String tenantId;
private String resource;
private String uuid;
private Channel releaseChannel;
private String appStoredLoc;
private String releaseDetails;
private String bannerLoc;
private Date createdAt;
private String screenshotLoc1;
private Application application;
private String screenshotLoc2;
private Map<String, String> properties;
private String screenshotLoc3;
private boolean isDefault;
private ReleaseType releaseType;
public int getId() {
return id;
}
private Double price;
private ImageArtifact icon;
private ImageArtifact banner;
private List<ImageArtifact> screenShots = new ArrayList<>();
private String appHashValue;
private int isSharedWithAllTenants;
private String metaData;
private List<Comment> comments;
private Lifecycle lifecycle;
public void setId(int id) {
this.id = id;
}
public String getVersionName() {
return versionName;
public void setVersion(String version) {
this.version = version;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public void setReleaseType(ReleaseType releaseType) {
this.releaseType = releaseType;
}
public void setIcon(ImageArtifact icon) {
this.icon = icon;
}
public void setBanner(ImageArtifact banner) {
this.banner = banner;
}
public void setScreenShots(List<ImageArtifact> screenShots) {
this.screenShots = screenShots;
}
public void setAppHashValue(String appHashValue) {
this.appHashValue = appHashValue;
}
public void setIsSharedWithAllTenants(int isSharedWithAllTenants) { this.isSharedWithAllTenants = isSharedWithAllTenants; }
public void setMetaData(String metaData) {
this.metaData = metaData;
}
public int getId() { return id; }
public String getVersion() {
return version;
}
public String getTenantId() {
return tenantId;
}
public ReleaseType getReleaseType() {
return releaseType;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public ImageArtifact getIcon() {
return icon;
}
public ImageArtifact getBanner() {
return banner;
}
public List<ImageArtifact> getScreenShots() {
return screenShots;
}
public void setVersionName(String versionName) {
this.versionName = versionName;
public String getAppHashValue() {
return appHashValue;
}
public String getResource() {
return resource;
public int getIsSharedWithAllTenants() {
return isSharedWithAllTenants;
}
public void setResource(String resource) {
this.resource = resource;
public String getMetaData() {
return metaData;
}
public List<Comment> getComments() { return comments; }
public void setComments(List<Comment> comments) {
this.comments = comments;
}
public Channel getReleaseChannel() {
return releaseChannel;
public String getAppStoredLoc() {
return appStoredLoc;
}
public void setReleaseChannel(String releaseChannel) {
this.releaseChannel = Channel.valueOf(releaseChannel);
public void setAppStoredLoc(String appStoredLoc) {
this.appStoredLoc = appStoredLoc;
}
public String getReleaseDetails() {
return releaseDetails;
public String getBannerLoc() {
return bannerLoc;
}
public void setReleaseDetails(String releaseDetails) {
this.releaseDetails = releaseDetails;
public void setBannerLoc(String bannerLoc) {
this.bannerLoc = bannerLoc;
}
public Date getCreatedAt() {
return createdAt;
public String getScreenshotLoc1() {
return screenshotLoc1;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
public void setScreenshotLoc1(String screenshotLoc1) {
this.screenshotLoc1 = screenshotLoc1;
}
public Application getApplication() {
return application;
public String getScreenshotLoc2() {
return screenshotLoc2;
}
public void setApplication(Application application) {
this.application = application;
public void setScreenshotLoc2(String screenshotLoc2) {
this.screenshotLoc2 = screenshotLoc2;
}
public Map<String, String> getProperties() {
return properties;
public String getScreenshotLoc3() {
return screenshotLoc3;
}
public void setProperties(Map<String, String> properties) {
this.properties = properties;
public void setScreenshotLoc3(String screenshotLoc3) {
this.screenshotLoc3 = screenshotLoc3;
}
public boolean isDefault() {
return isDefault;
public Lifecycle getLifecycle() {
return lifecycle;
}
public void setDefault(boolean aDefault) {
isDefault = aDefault;
public void setLifecycle(Lifecycle lifecycle) {
this.lifecycle = lifecycle;
}
}

@ -1,58 +0,0 @@
/*
* Copyright (c) 2017, 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.application.mgt.common;
import org.wso2.carbon.device.application.mgt.common.jaxrs.Exclude;
/**
* Represents the category a particular {@link Application} belongs to.
*/
public class Category {
@Exclude
private int id;
private String name;
private String description;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

@ -1,91 +0,0 @@
/*
* Copyright (c) 2017, 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.application.mgt.common;
import org.wso2.carbon.device.application.mgt.common.jaxrs.Exclude;
import java.util.Date;
/**
* Application represents the an Application in Application Store.
*/
public class DeviceType {
@Exclude
private int id;
private String type;
private String name;
private Date lastUpdated;
private String providerTenantID;
private int sharedWithAllTenants;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getLastUpdated() {
return lastUpdated;
}
public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}
public String getProviderTenantID() {
return providerTenantID;
}
public void setProviderTenantID(String providerTenantID) {
this.providerTenantID = providerTenantID;
}
public int getSharedWithAllTenants() {
return sharedWithAllTenants;
}
public void setSharedWithAllTenants(int sharedWithAllTenants) {
this.sharedWithAllTenants = sharedWithAllTenants;
}
}

@ -18,39 +18,120 @@
package org.wso2.carbon.device.application.mgt.common;
import java.util.Date;
import java.util.List;
/**
* Represents an lifecycle of an {@link Application}.
*/
public class Lifecycle {
private LifecycleState lifecycleState;
private int id;
private Date lifecycleStateModifiedAt;
private Date createdAt;
private String getLifecycleStateModifiedBy;
private String createdBy;
public LifecycleState getLifecycleState() {
return lifecycleState;
private int isApproved;
private String approvedBy;
private Date approvedAt;
private int isPublished;
private String publishedBy;
private Date publishedAt;
private int isRetired;
private List<LifecycleStateTransition> lifecycleStateTransition;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public int getIsApproved() {
return isApproved;
}
public void setIsApproved(int isApproved) {
this.isApproved = isApproved;
}
public String getApprovedBy() {
return approvedBy;
}
public void setApprovedBy(String approvedBy) {
this.approvedBy = approvedBy;
}
public Date getApprovedAt() {
return approvedAt;
}
public void setApprovedAt(Date approvedAt) {
this.approvedAt = approvedAt;
}
public int getIsPublished() {
return isPublished;
}
public void setIsPublished(int isPublished) {
this.isPublished = isPublished;
}
public String getPublishedBy() {
return publishedBy;
}
public void setPublishedBy(String publishedBy) {
this.publishedBy = publishedBy;
}
public Date getPublishedAt() {
return publishedAt;
}
public void setLifecycleState(LifecycleState lifecycleState) {
this.lifecycleState = lifecycleState;
public void setPublishedAt(Date publishedAt) {
this.publishedAt = publishedAt;
}
public Date getLifecycleStateModifiedAt() {
return lifecycleStateModifiedAt;
public int getIsRetired() {
return isRetired;
}
public void setLifecycleStateModifiedAt(Date lifecycleStateModifiedAt) {
this.lifecycleStateModifiedAt = lifecycleStateModifiedAt;
public void setIsRetired(int isRetired) {
this.isRetired = isRetired;
}
public String getGetLifecycleStateModifiedBy() {
return getLifecycleStateModifiedBy;
public List<LifecycleStateTransition> getLifecycleStateTransition() {
return lifecycleStateTransition;
}
public void setGetLifecycleStateModifiedBy(String getLifecycleStateModifiedBy) {
this.getLifecycleStateModifiedBy = getLifecycleStateModifiedBy;
public void setLifecycleStateTransition(List<LifecycleStateTransition> lifecycleStateTransition) {
this.lifecycleStateTransition = lifecycleStateTransition;
}
}

@ -1,233 +0,0 @@
/*
* Copyright (c) 2017, 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.application.mgt.common;
import org.wso2.carbon.device.application.mgt.common.jaxrs.Exclude;
import java.util.ArrayList;
import java.util.List;
/**
* Represents the platform of an {@link Application}.
*/
public class Platform {
/**
* Unique id reference that is used in the database.
*/
@Exclude
private int id;
/**
* The name of the platform. It can contain spaces,etc.
*/
private String name;
private String description;
/**
* Unique human readable identifier used for the platform.
*/
private String identifier;
private String iconName;
private boolean fileBased;
private boolean shared;
private List<String> tags;
private List<Property> properties;
private boolean enabled;
private boolean defaultTenantMapping;
private ImageArtifact icon;
public Platform(Platform platform) {
this.id = platform.getId();
this.name = platform.getName();
this.description = platform.getDescription();
this.identifier = platform.getIdentifier();
this.iconName = platform.getIconName();
this.fileBased = platform.isFileBased();
this.shared = platform.isShared();
this.enabled = platform.isEnabled();
this.defaultTenantMapping = platform.isDefaultTenantMapping();
if (platform.getProperties() != null) {
this.properties = new ArrayList<>();
for (Property property : platform.getProperties()) {
this.properties.add(new Property(property));
}
}
if (platform.getTags() != null) {
this.tags = new ArrayList<>();
for (String tag : platform.getTags()) {
this.tags.add(tag);
}
}
}
public Platform() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getIconName() {
return iconName;
}
public void setIconName(String iconName) {
this.iconName = iconName;
}
public List<Property> getProperties() {
return properties;
}
public void setProperties(List<Property> properties) {
this.properties = properties;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public boolean isFileBased() {
return fileBased;
}
public void setFileBased(boolean fileBased) {
this.fileBased = fileBased;
}
public boolean isShared() {
return shared;
}
public void setShared(boolean shared) {
this.shared = shared;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isDefaultTenantMapping() {
return defaultTenantMapping;
}
public void setDefaultTenantMapping(boolean defaultTenantMapping) {
this.defaultTenantMapping = defaultTenantMapping;
}
public boolean validate() {
return !(name == null || identifier == null);
}
public void setIcon(ImageArtifact icon) {
this.icon = icon;
}
/**
* Represents a property of a {@link Platform}.
*/
public static class Property implements Cloneable {
private String name;
private boolean optional;
private String defaultValue;
public Property(Property property) {
this.name = property.getName();
this.optional = property.isOptional();
this.defaultValue = property.getDefaultValue();
}
public Property() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isOptional() {
return optional;
}
public void setOptional(boolean optional) {
this.optional = optional;
}
public String getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
}
}

@ -25,17 +25,13 @@ import org.wso2.carbon.device.application.mgt.common.jaxrs.Exclude;
/**
* Application represents the an Application in Application Store.
*/
public class UnrestrictedRoles {
public class UnrestrictedRole {
@Exclude
private int id;
private String tenantId;
private String tagName;
private Application application;
private String role;
public int getId() {
@ -54,22 +50,6 @@ public class UnrestrictedRoles {
this.tenantId = tenantId;
}
public String getTagName() {
return tagName;
}
public void setTagName(String tagName) {
this.tagName = tagName;
}
public Application getApplication() {
return application;
}
public void setApplication(Application application) {
this.application = application;
}
public String getRole() {
return role;
}

@ -1,32 +0,0 @@
/*
* Copyright (c) 2017, 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.application.mgt.common.exception;
/**
* Exception caused during the platform management.
*/
public class PlatformManagementException extends ApplicationManagementException {
public PlatformManagementException(String message, Throwable ex) {
super(message, ex);
}
public PlatformManagementException(String message) {
super(message);
}
}

@ -1,33 +0,0 @@
/*
* Copyright (c) 2017, 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.application.mgt.common.exception;
/**
* Represents the exception thrown during storing and retrieving those artifacts.
*/
public class PlatformStorageManagementException extends ResourceManagementException {
public PlatformStorageManagementException(String message, Throwable ex) {
super(message, ex);
}
public PlatformStorageManagementException(String message) {
super(message);
}
}

@ -23,6 +23,7 @@ import org.wso2.carbon.device.application.mgt.common.ApplicationList;
import org.wso2.carbon.device.application.mgt.common.Filter;
import org.wso2.carbon.device.application.mgt.common.LifecycleStateTransition;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import java.util.List;
@ -37,7 +38,8 @@ public interface ApplicationManager {
* @return Created application
* @throws ApplicationManagementException Application Management Exception
*/
Application createApplication(Application application) throws ApplicationManagementException;
Application createApplication(Application application)
throws ApplicationManagementException, DeviceManagementDAOException, DeviceManagementDAOException;
/**
* Updates an already existing application.

@ -18,7 +18,6 @@
*/
package org.wso2.carbon.device.application.mgt.common.services;
import org.wso2.carbon.device.application.mgt.common.Category;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import java.util.List;

@ -1,142 +0,0 @@
/*
* Copyright (c) 2017, 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.application.mgt.common.services;
import org.wso2.carbon.device.application.mgt.common.Platform;
import org.wso2.carbon.device.application.mgt.common.exception.PlatformManagementException;
import java.util.List;
/**
* Platform manager is responsible for handling platforms, which will be used to as a registry of platforms.
* And will be able to provide the platforms related information to other classes which requires.
*/
public interface PlatformManager {
/**
* To initialize the shared platforms for the tenant during the tenant initialization time.
*
* @param tenantId ID of the tenant
* @throws PlatformManagementException Platform Management Exception
*/
void initialize(int tenantId) throws PlatformManagementException;
/**
* To get platforms of the specific tenant.
*
* @param tenantId ID of the tenant
* @return List of platforms
* @throws PlatformManagementException Platform Management Exception
*/
List<Platform> getPlatforms(int tenantId) throws PlatformManagementException;
/**
* To get platform with the given platform identifier and tenant ID.
*
* @param tenantId ID of the tenant
* @param platformIdentifier Unique identifier of the platform.
* @return the Specific platform with the platform identifier and tenant
* @throws PlatformManagementException Platform Management Exception
*/
Platform getPlatform(int tenantId, String platformIdentifier) throws PlatformManagementException;
/**
* To register a platform under particular tenant.
*
* @param tenantId ID of the tenant.
* @param platform Platform to be registered
* @throws PlatformManagementException Platform Management Exception
*/
void register(int tenantId, Platform platform) throws PlatformManagementException;
/**
* To update a platform.
*
* @param tenantId ID of the tenant
* @param oldPlatformIdentifier Old platform Identifier
* @param platform Platform to be updated
* @throws PlatformManagementException Platform Management Exception
*/
void update(int tenantId, String oldPlatformIdentifier, Platform platform) throws PlatformManagementException;
/**
* To un-register the platform.
*
* @param tenantId ID of the tenant.
* @param platformIdentifier ID of the platform
* @param isFileBased To indicate whether a file based or not.
* @throws PlatformManagementException Platform Management Exception.
*/
void unregister(int tenantId, String platformIdentifier, boolean isFileBased) throws PlatformManagementException;
/**
* To add mapping to platform identifiers with the tenant ID.
*
* @param tenantId ID of the tenant
* @param platformIdentifiers Platform Identifiers
* @throws PlatformManagementException Platform Management Exception
*/
void addMapping(int tenantId, List<String> platformIdentifiers) throws PlatformManagementException;
/**
* To add mapping to a platform for a tenant.
*
* @param tenantId ID of the tenant.
* @param platformIdentifier ID of the platform, the mapping should be added.
* @throws PlatformManagementException Platform Management Exception.
*/
void addMapping(int tenantId, String platformIdentifier) throws PlatformManagementException;
/**
* To remove a mapping of a platform to a tenant.
*
* @param tenantId ID of the tenant.
* @param platformIdentifier ID of the platform.
* @throws PlatformManagementException Platform Management Exception.
*/
void removeMapping(int tenantId, String platformIdentifier) throws PlatformManagementException;
/**
* To update the platform status(ENABLED / DISABLED).
*
* @param tenantId Id of the tenant
* @param platformIdentifier ID of the platform
* @param status Status to be updated.
* @throws PlatformManagementException Platform Management Exception.
*/
void updatePlatformStatus(int tenantId, String platformIdentifier, String status)
throws PlatformManagementException;
/**
* To remove platforms that belongs to particular tenant.
*
* @param tenantId ID of the tenant.
* @throws PlatformManagementException Platform Management Exception.
*/
void removePlatforms(int tenantId) throws PlatformManagementException;
/**
* To get the platform tags.
*
* @param name Starting character sequence of the platform name.
* @return list of the platform tags that start with the character sequence.
* @throws PlatformManagementException PlatformManagement Exception
*/
List<String> getPlatformTags(String name) throws PlatformManagementException;
}

@ -1,57 +0,0 @@
/*
* Copyright (c) 2017, 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.application.mgt.common.services;
import org.wso2.carbon.device.application.mgt.common.ImageArtifact;
import org.wso2.carbon.device.application.mgt.common.exception.PlatformStorageManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException;
import java.io.InputStream;
/**
* This class manages all the storage related requirements of Platform.
*/
public interface PlatformStorageManager {
/**
* To upload image artifacts related with an Application.
*
* @param platformIdentifier Identifier of the platform
* @param iconFile Icon File input stream
* @throws ResourceManagementException Resource Management Exception.
*/
void uploadIcon(String platformIdentifier, InputStream iconFile) throws ResourceManagementException;
/**
* To get the icon for a particular platform.
*
* @param platformIdentifier Identifier of the platform.
* @return the icon for the given platform.
* @throws PlatformStorageManagementException Platform Storage Management Exception.
*/
ImageArtifact getIcon(String platformIdentifier) throws PlatformStorageManagementException;
/**
* To delete the icon of a particular platform
*
* @param platformIdentifier Identifier of the platform to which delete icon.
* @throws PlatformStorageManagementException PlatformStorageManagement Exception.
*/
void deleteIcon(String platformIdentifier) throws PlatformStorageManagementException;
}

@ -18,10 +18,7 @@
*/
package org.wso2.carbon.device.application.mgt.core.dao;
import org.wso2.carbon.device.application.mgt.common.Application;
import org.wso2.carbon.device.application.mgt.common.ApplicationList;
import org.wso2.carbon.device.application.mgt.common.Filter;
import org.wso2.carbon.device.application.mgt.common.LifecycleStateTransition;
import org.wso2.carbon.device.application.mgt.common.*;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import java.util.List;
@ -38,7 +35,33 @@ public interface ApplicationDAO {
* @return Created Application.
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
Application createApplication(Application application) throws ApplicationManagementDAOException;
int createApplication(Application application, int deviceId) throws ApplicationManagementDAOException;
/**
* To add tags for a particular application.
*
* @param tags tags that need to be added for a application.
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
void addTags(List<Tag> tags, int applicationId, int tenantId) throws ApplicationManagementDAOException;
/**
* To add unrestricted roles for a particular application.
*
* @param unrestrictedRoles unrestrictedRoles that could available the application.
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
void addUnrestrictedRoles(List<UnrestrictedRole> unrestrictedRoles, int applicationId, int tenantId) throws ApplicationManagementDAOException;
/**
* To check application existence.
*
* @param appName appName that need to identify application.
* @param type type that need to identify application.
* @param tenantId tenantId that need to identify application.
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
int isExistApplication(String appName, String type, int tenantId) throws ApplicationManagementDAOException;
/**
* To get the applications that satisfy the given criteria.

@ -35,7 +35,7 @@ public interface ApplicationReleaseDAO {
* @return Unique ID of the relevant release.
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
ApplicationRelease createRelease(ApplicationRelease applicationRelease) throws
ApplicationRelease createRelease(ApplicationRelease applicationRelease, int appId) throws
ApplicationManagementDAOException;
/**

@ -1,64 +0,0 @@
/*
* Copyright (c) 2017, 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.application.mgt.core.dao;
import org.wso2.carbon.device.application.mgt.common.Category;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import java.util.List;
/**
* This is responsible for Application Category related DAO operations.
*/
public interface CategoryDAO {
/**
* To add a new category.
*
* @param category Category that need to be added.
* @return Newly added category.
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
Category addCategory(Category category) throws ApplicationManagementDAOException;
/**
* To get the existing categories.
*
* @return Existing categories.
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
List<Category> getCategories() throws ApplicationManagementDAOException;
/**
* To get the category with the given name.
*
* @param name Name of the Application category.
* @return Application Category.
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
Category getCategory(String name) throws ApplicationManagementDAOException;
/**
* To delete a particular category.
*
* @param name Name of the category that need to be deleted.
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
void deleteCategory(String name) throws ApplicationManagementDAOException;
}

@ -0,0 +1,43 @@
/*
*
* Copyright (c) ${date}, 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.application.mgt.core.dao;
import org.wso2.carbon.device.application.mgt.common.Lifecycle;
import org.wso2.carbon.device.application.mgt.common.LifecycleState;
import org.wso2.carbon.device.application.mgt.core.exception.LifeCycleManagementDAOException;
import java.util.List;
/**
* This is responsible for all the DAO operations related to Lifecycle state.
*/
public interface LifecycleDAO {
Lifecycle getLifeCycleOfApplication(int identifier) throws LifeCycleManagementDAOException;
List<Lifecycle> getLifecyclesOfAllAppVersions (int identifier) throws LifeCycleManagementDAOException;
void addLifecycle(Lifecycle lifecycle) throws LifeCycleManagementDAOException;
void updateLifecycleOfApplication(LifecycleState state) throws LifeCycleManagementDAOException;
void deleteLifecycleOfApplication(String identifier) throws LifeCycleManagementDAOException;
}

@ -20,7 +20,7 @@ package org.wso2.carbon.device.application.mgt.core.dao;
import org.wso2.carbon.device.application.mgt.common.LifecycleState;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.exception.DAOException;
import org.wso2.carbon.device.application.mgt.core.exception.LifeCycleManagementDAOException;
import java.util.List;
@ -31,10 +31,10 @@ public interface LifecycleStateDAO {
LifecycleState getLifeCycleStateByIdentifier(String identifier) throws ApplicationManagementDAOException;
List<LifecycleState> getLifecycleStates() throws DAOException;
List<LifecycleState> getLifecycleStates() throws LifeCycleManagementDAOException;
void addLifecycleState(LifecycleState state) throws DAOException;
void addLifecycleState(LifecycleState state) throws LifeCycleManagementDAOException;
void deleteLifecycleState(String identifier) throws DAOException;
void deleteLifecycleState(String identifier) throws LifeCycleManagementDAOException;
}

@ -1,59 +0,0 @@
/*
* Copyright (c) 2017, 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.application.mgt.core.dao;
import org.wso2.carbon.device.application.mgt.common.Platform;
import org.wso2.carbon.device.application.mgt.core.exception.PlatformManagementDAOException;
import java.util.List;
/**
* PlatformDAO defines set of DAO operations that are needed for Platform Management.
*/
public interface PlatformDAO {
int register(int tenantId, Platform platform) throws PlatformManagementDAOException;
void update(int tenantId, String oldPlatformIdentifier, Platform platform) throws PlatformManagementDAOException;
void unregister(int tenantId, String platformIdentifier, boolean isFileBased) throws PlatformManagementDAOException;
void addMapping(int tenantId, List<String> platformIdentifiers) throws PlatformManagementDAOException;
void removeMapping(int tenantId, String platformIdentifier) throws PlatformManagementDAOException;
void removeMappingTenants(String platformIdentifier) throws PlatformManagementDAOException;
List<Platform> getPlatforms(int tenantId) throws PlatformManagementDAOException;
Platform getPlatform(String tenantDomain, String platformIdentifier) throws PlatformManagementDAOException;
Platform getPlatform(int tenantId, String identifier) throws PlatformManagementDAOException;
void removePlatforms(int tenantId) throws PlatformManagementDAOException;
int getSuperTenantAndOwnPlatforms(String platformIdentifier, int tenantId) throws PlatformManagementDAOException;
Platform getTenantOwnedPlatform(int tenantId, String platformIdentifier) throws PlatformManagementDAOException;
int getMultiTenantPlatforms(String identifier) throws PlatformManagementDAOException;
List<String> getPlatformTags(String name) throws PlatformManagementDAOException;
}

@ -22,26 +22,20 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.common.exception.UnsupportedDatabaseEngineException;
import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager;
import org.wso2.carbon.device.application.mgt.core.dao.ApplicationDAO;
import org.wso2.carbon.device.application.mgt.core.dao.ApplicationReleaseDAO;
import org.wso2.carbon.device.application.mgt.core.dao.CategoryDAO;
import org.wso2.carbon.device.application.mgt.core.dao.LifecycleStateDAO;
import org.wso2.carbon.device.application.mgt.core.dao.PlatformDAO;
import org.wso2.carbon.device.application.mgt.core.dao.SubscriptionDAO;
import org.wso2.carbon.device.application.mgt.core.dao.VisibilityDAO;
import org.wso2.carbon.device.application.mgt.core.dao.*;
import org.wso2.carbon.device.application.mgt.core.dao.impl.application.GenericApplicationDAOImpl;
import org.wso2.carbon.device.application.mgt.core.dao.impl.application.release.GenericApplicationReleaseDAOImpl;
import org.wso2.carbon.device.application.mgt.core.dao.impl.application.release.OracleApplicationDAOImpl;
import org.wso2.carbon.device.application.mgt.core.dao.impl.category.GenericCategoryDAOImpl;
import org.wso2.carbon.device.application.mgt.core.dao.impl.lifecycle.GenericLifecycleImpl;
import org.wso2.carbon.device.application.mgt.core.dao.impl.lifecyclestate.GenericLifecycleStateImpl;
import org.wso2.carbon.device.application.mgt.core.dao.impl.platform.GenericPlatformDAOImpl;
import org.wso2.carbon.device.application.mgt.core.dao.impl.platform.OracleMsSQLPlatformDAOImpl;
import org.wso2.carbon.device.application.mgt.core.dao.impl.subscription.GenericSubscriptionDAOImpl;
import org.wso2.carbon.device.application.mgt.core.dao.impl.visibility.GenericVisibilityDAOImpl;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.util.ApplicationMgtDatabaseCreator;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
import org.wso2.carbon.device.application.mgt.core.util.Constants;
import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO;
import org.wso2.carbon.device.mgt.core.dao.impl.DeviceTypeDAOImpl;
import org.wso2.carbon.utils.dbcreator.DatabaseCreator;
import java.sql.SQLException;
@ -52,10 +46,10 @@ import java.sql.SQLException;
* different data sources, connection acquisition mechanisms as well as different forms of DAO implementations to the
* high-level implementations that require Application management related metadata persistence.
*/
public class DAOFactory {
public class ApplicationManagementDAOFactory {
private static String databaseEngine;
private static final Log log = LogFactory.getLog(DAOFactory.class);
private static final Log log = LogFactory.getLog(ApplicationManagementDAOFactory.class);
public static void init(String datasourceName) {
ConnectionManagerUtil.resolveDataSource(datasourceName);
@ -78,23 +72,6 @@ public class DAOFactory {
throw new IllegalStateException("Database engine has not initialized properly.");
}
public static PlatformDAO getPlatformDAO() {
if (databaseEngine != null) {
switch (databaseEngine) {
case Constants.DataBaseTypes.DB_TYPE_H2:
case Constants.DataBaseTypes.DB_TYPE_MYSQL:
case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL:
return new GenericPlatformDAOImpl();
case Constants.DataBaseTypes.DB_TYPE_MSSQL:
case Constants.DataBaseTypes.DB_TYPE_ORACLE:
return new OracleMsSQLPlatformDAOImpl();
default:
throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
}
}
throw new IllegalStateException("Database engine has not initialized properly.");
}
public static LifecycleStateDAO getLifecycleStateDAO() {
if (databaseEngine != null) {
switch (databaseEngine) {
@ -132,7 +109,6 @@ public class DAOFactory {
/**
* To get the instance of VisibilityDAOImplementation of the particular database engine.
*
* @return specific VisibilityDAOImplementation
*/
public static VisibilityDAO getVisibilityDAO() {
@ -167,15 +143,16 @@ public class DAOFactory {
}
/**
* To get the instance of CategoryDAOImplementation of the particular database engine.
* @return {@link org.wso2.carbon.device.application.mgt.core.dao.impl.category.GenericCategoryDAOImpl}
* To get the instance of DeviceTypeDAOImpl of the particular database engine.
* @return DeviceTypeDAOImpl
*/
public static CategoryDAO getCategoryDAO() {
public static DeviceTypeDAO getDeviceTypeDAO() {
if (databaseEngine != null) {
switch (databaseEngine) {
case Constants.DataBaseTypes.DB_TYPE_H2:
case Constants.DataBaseTypes.DB_TYPE_MYSQL:
return new GenericCategoryDAOImpl();
case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL:
return new DeviceTypeDAOImpl();
default:
throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
}
@ -183,6 +160,23 @@ public class DAOFactory {
throw new IllegalStateException("Database engine has not initialized properly.");
}
/**
* To get the instance of LifecycleDAOImplementation of the particular database engine.
* @return GenericLifecycleDAOImpl
*/
public static LifecycleDAO getLifecycleDAO() {
if (databaseEngine != null) {
switch (databaseEngine) {
case Constants.DataBaseTypes.DB_TYPE_H2:
case Constants.DataBaseTypes.DB_TYPE_MYSQL:
case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL:
return new GenericLifecycleImpl();
default:
throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
}
}
throw new IllegalStateException("Database engine has not initialized properly.");
}
/**
* This method initializes the databases by creating the database.
*

@ -22,10 +22,8 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.wso2.carbon.device.application.mgt.common.Application;
import org.wso2.carbon.device.application.mgt.common.Category;
import org.wso2.carbon.device.application.mgt.common.Lifecycle;
import org.wso2.carbon.device.application.mgt.common.LifecycleState;
import org.wso2.carbon.device.application.mgt.common.Platform;
import org.wso2.carbon.device.application.mgt.common.User;
import java.sql.PreparedStatement;
@ -67,11 +65,6 @@ public class Util {
application.setModifiedAt(rs.getDate("MODIFIED_AT"));
application.setUser(new User(rs.getString("CREATED_BY"), rs.getInt("TENANT_ID")));
Platform platform = new Platform();
platform.setName(rs.getString("APL_NAME"));
platform.setIdentifier(rs.getString("APL_IDENTIFIER"));
application.setPlatform(platform);
Map<String, String> properties = new HashMap<>();
while (rsProperties.next()) {
properties.put(rsProperties.getString("PROP_KEY"), rsProperties.getString("PROP_VAL"));
@ -84,11 +77,6 @@ public class Util {
}
application.setTags(tags);
Category category = new Category();
category.setId(rs.getInt("CAT_ID"));
category.setName(rs.getString("CAT_NAME"));
application.setCategory(category);
LifecycleState lifecycleState = new LifecycleState();
lifecycleState.setId(rs.getInt("LIFECYCLE_STATE_ID"));
lifecycleState.setName(rs.getString("LS_NAME"));

@ -21,11 +21,7 @@ package org.wso2.carbon.device.application.mgt.core.dao.impl.application;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.wso2.carbon.device.application.mgt.common.Application;
import org.wso2.carbon.device.application.mgt.common.ApplicationList;
import org.wso2.carbon.device.application.mgt.common.Filter;
import org.wso2.carbon.device.application.mgt.common.LifecycleStateTransition;
import org.wso2.carbon.device.application.mgt.common.Pagination;
import org.wso2.carbon.device.application.mgt.common.*;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.core.dao.ApplicationDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.Util;
@ -33,11 +29,7 @@ import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@ -50,52 +42,38 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
private static final Log log = LogFactory.getLog(GenericApplicationDAOImpl.class);
public Application createApplication(Application application) throws ApplicationManagementDAOException {
public int createApplication(Application application, int deviceId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to create an application");
log.debug("Application Details : ");
log.debug("UUID : " + application.getUuid() + " Name : " + application.getName() + " User name : "
+ application.getUser().getUserName());
log.debug("App Name : " + application.getName() + " App Type : "
+ application.getType() + " User Name : " + application.getUser().getUserName());
}
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
String sql = "";
String generatedColumns[] = {"ID"};
boolean isBatchExecutionSupported = ConnectionManagerUtil.isBatchQuerySupported();
int index = 0;
int applicationId = -1;
try {
conn = this.getDBConnection();
sql += "INSERT INTO APPM_APPLICATION (UUID, NAME, SHORT_DESCRIPTION, DESCRIPTION, "
+ "VIDEO_NAME, SCREEN_SHOT_COUNT, CREATED_BY, CREATED_AT, MODIFIED_AT, "
+ "APPLICATION_CATEGORY_ID, PLATFORM_ID, TENANT_ID, LIFECYCLE_STATE_ID, "
+ "LIFECYCLE_STATE_MODIFIED_AT, LIFECYCLE_STATE_MODIFIED_BY) VALUES "
+ "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(sql, generatedColumns);
stmt.setString(++index, application.getUuid());
stmt = conn.prepareStatement("INSERT INTO AP_APP (NAME, TYPE, APP_CATEGORY, "
+ "IS_FREE, PAYMENT_CURRENCY, RESTRICTED, TENANT_ID) VALUES "
+ "(?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
stmt.setString(++index, application.getName());
stmt.setString(++index, application.getShortDescription());
stmt.setString(++index, application.getDescription());
stmt.setString(++index, application.getVideoName());
stmt.setInt(++index, application.getScreenShotCount());
stmt.setString(++index, application.getUser().getUserName());
stmt.setDate(++index, new Date(application.getCreatedAt().getTime()));
stmt.setDate(++index, new Date(application.getModifiedAt().getTime()));
stmt.setInt(++index, application.getCategory().getId());
stmt.setInt(++index, application.getPlatform().getId());
stmt.setString(++index, application.getType());
stmt.setString(++index, application.getAppCategory());
stmt.setInt(++index, application.getIsFree());
stmt.setString(++index, application.getPaymentCurrency());
stmt.setInt(++index, application.getIsRestricted());
stmt.setInt(++index, application.getUser().getTenantId());
stmt.setInt(++index, application.getCurrentLifecycle().getLifecycleState().getId());
stmt.setDate(++index, new Date(application.getCurrentLifecycle().getLifecycleStateModifiedAt().getTime()));
stmt.setString(++index, application.getCurrentLifecycle().getGetLifecycleStateModifiedBy());
stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
application.setId(rs.getInt(1));
applicationId = rs.getInt(1);
}
insertApplicationTagsAndProperties(application, stmt, conn, isBatchExecutionSupported);
return application;
return applicationId;
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
} catch (SQLException e) {
@ -105,8 +83,105 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
}
}
public void addTags(List<Tag> tags, int applicationId, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to add tags");
}
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
int index = 0;
String sql = "INSERT INTO AP_APP_TAG (TAG, TENANT_ID, AP_APP_ID) "
+ "VALUES (?, ?, ?)";
try{
conn = this.getDBConnection();
conn.setAutoCommit(false);
stmt = conn.prepareStatement(sql);
for (Tag tag : tags) {
stmt.setString(++index, tag.getTagName());
stmt.setInt(++index, tenantId);
stmt.setInt(++index, applicationId);
stmt.addBatch();
}
stmt.executeBatch();
@Override
}catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
}catch (SQLException e) {
throw new ApplicationManagementDAOException("Error occurred while adding tags", e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
public void addUnrestrictedRoles(List<UnrestrictedRole> unrestrictedRoles, int applicationId, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to add unrestricted roles");
}
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
int index = 0;
String sql = "INSERT INTO AP_UNRESTRICTED_ROLES (ROLE, TENANT_ID, AP_APP_ID) "
+ "VALUES (?, ?, ?)";
try{
conn = this.getDBConnection();
conn.setAutoCommit(false);
stmt = conn.prepareStatement(sql);
for (UnrestrictedRole role : unrestrictedRoles) {
stmt.setString(++index, role.getRole());
stmt.setInt(++index, tenantId);
stmt.setInt(++index, applicationId);
stmt.addBatch();
}
stmt.executeBatch();
}catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
}catch (SQLException e) {
throw new ApplicationManagementDAOException("Error occurred while adding unrestricted roles", e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
public int isExistApplication(String appName, String type, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to verify whether the registering app is registered or not");
}
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
int isExist = 0;
int index = 0;
String sql = "SELECT * FROM AP_APP WHERE NAME = ? AND TYPE = ? TENANT_ID = ?";
try{
conn = this.getDBConnection();
conn.setAutoCommit(false);
stmt = conn.prepareStatement(sql);
stmt.setString(++index , appName);
stmt.setString(++index , type);
stmt.setInt(++index, tenantId);
rs = stmt.executeQuery();
if (rs.next()) {
isExist = 1;
}
return isExist;
}catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
}catch (SQLException e) {
throw new ApplicationManagementDAOException("Error occurred while adding unrestricted roles", e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
@Override
public ApplicationList getApplications(Filter filter, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting application data from the database");

@ -43,29 +43,35 @@ import java.util.Map;
public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements ApplicationReleaseDAO {
@Override
public ApplicationRelease createRelease(ApplicationRelease applicationRelease) throws
public ApplicationRelease createRelease(ApplicationRelease applicationRelease, int appId) throws
ApplicationManagementDAOException {
Connection connection;
PreparedStatement statement = null;
ResultSet resultSet = null;
if (applicationRelease.isDefault()) {
String sql = "INSERT INTO AP_APP_RELEASE (VERSION,TENANT_ID,UUID,RELEASE_TYPE,APP_PRICE,STORED_LOCATION, "
+ "BANNER_LOCATION, SC_1_LOCATION,SC_2_LOCATION,SC_3_LOCATION, APP_HASH_VALUE,SHARED_WITH_ALL_TENANTS, "
+ "APP_META_INFO,AP_APP_ID) VALUES "
+ "(?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
}
String sql = "insert into APPM_APPLICATION_RELEASE(VERSION_NAME, RELEASE_RESOURCE, RELEASE_CHANNEL ,"
+ "RELEASE_DETAILS, CREATED_AT, APPM_APPLICATION_ID, IS_DEFAULT) values (?, ?, ?, ?, ?, ?, ?)";
int index = 0;
String generatedColumns[] = {"ID"};
try {
connection = this.getDBConnection();
statement = connection.prepareStatement(sql, generatedColumns);
statement.setString(++index, applicationRelease.getVersionName());
statement.setString(++index, applicationRelease.getResource());
statement.setString(++index, String.valueOf(applicationRelease.getReleaseChannel()));
statement.setString(++index, applicationRelease.getReleaseDetails());
statement.setDate(++index, new Date(applicationRelease.getCreatedAt().getTime()));
statement.setInt(++index, applicationRelease.getApplication().getId());
statement.setBoolean(++index, applicationRelease.isDefault());
statement.setString(++index, applicationRelease.getVersion());
statement.setString(++index, applicationRelease.getTenantId());
statement.setString(++index, applicationRelease.getUuid());
statement.setString(++index, String.valueOf(applicationRelease.getReleaseType()));
statement.setDouble(++index, applicationRelease.getPrice());
statement.setString(++index, applicationRelease.getAppStoredLoc());
statement.setString(++index, applicationRelease.getScreenshotLoc1());
statement.setString(++index, applicationRelease.getScreenshotLoc2());
statement.setString(++index, applicationRelease.getScreenshotLoc3());
statement.setString(++index, applicationRelease.getAppHashValue());
statement.setInt(++index, applicationRelease.getIsSharedWithAllTenants());
statement.setString(++index, applicationRelease.getMetaData());
statement.setInt(++index, appId);
statement.executeUpdate();
resultSet = statement.getGeneratedKeys();
if (resultSet.next()) {
@ -75,12 +81,10 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
return applicationRelease;
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
"SQL Exception while trying to release an application (UUID : " + applicationRelease
.getApplication().getUuid() + "), by executing the query " + sql, e);
"SQL Exception while trying to release an application by executing the query " + sql, e);
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
"Database Connection Exception while trying to release the " + "applcation with UUID "
+ applicationRelease.getApplication().getUuid(), e);
"Database Connection Exception while trying to release a new version" , e);
} finally {
Util.cleanupResources(statement, resultSet);
}
@ -107,10 +111,10 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
if (resultSet.next()) {
applicationRelease = new ApplicationRelease();
applicationRelease.setVersionName(versionName);
applicationRelease.setVersion(versionName);
applicationRelease.setDefault(resultSet.getBoolean("IS_DEFAULT"));
applicationRelease.setCreatedAt(resultSet.getDate("CREATED_AT"));
applicationRelease.setReleaseChannel(resultSet.getString("RELEASE_CHANNEL"));
applicationRelease.setReleaseType(resultSet.getString("RELEASE_CHANNEL"));
applicationRelease.setReleaseDetails(resultSet.getString("RELEASE_DETAILS"));
applicationRelease.setResource(resultSet.getString("RELEASE_RESOURCE"));
@ -160,10 +164,10 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
while (resultSet.next()) {
ApplicationRelease applicationRelease = new ApplicationRelease();
applicationRelease.setVersionName(resultSet.getString("VERSION_NAME"));
applicationRelease.setVersion(resultSet.getString("VERSION_NAME"));
applicationRelease.setDefault(resultSet.getBoolean("IS_DEFAULT"));
applicationRelease.setCreatedAt(resultSet.getDate("CREATED_AT"));
applicationRelease.setReleaseChannel(resultSet.getString("RELEASE_CHANNEL"));
applicationRelease.setReleaseType(resultSet.getString("RELEASE_CHANNEL"));
applicationRelease.setReleaseDetails(resultSet.getString("RELEASE_DETAILS"));
applicationRelease.setResource(resultSet.getString("RELEASE_RESOURCE"));
@ -205,11 +209,11 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
connection = this.getDBConnection();
statement = connection.prepareStatement(sql);
statement.setString(1, applicationRelease.getResource());
statement.setString(2, String.valueOf(applicationRelease.getReleaseChannel()));
statement.setString(2, String.valueOf(applicationRelease.getReleaseType()));
statement.setString(3, applicationRelease.getReleaseDetails());
statement.setBoolean(4, applicationRelease.isDefault());
statement.setInt(5, applicationRelease.getApplication().getId());
statement.setString(6, applicationRelease.getVersionName());
statement.setString(6, applicationRelease.getVersion());
statement.executeUpdate();
sql = "DELETE FROM APPM_RELEASE_PROPERTY WHERE APPLICATION_RELEASE_ID = ?";
@ -221,7 +225,7 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Database connection exception while trying to update the "
+ "Application release for the application with UUID " + applicationRelease.getApplication()
.getUuid() + " for the version " + applicationRelease.getVersionName(), e);
.getUuid() + " for the version " + applicationRelease.getVersion(), e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
"SQL exception while updating the release, while executing the query " + sql, e);

@ -1,151 +0,0 @@
/*
* Copyright (c) 2017, 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.application.mgt.core.dao.impl.category;
import org.wso2.carbon.device.application.mgt.common.Category;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.core.dao.CategoryDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.Util;
import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* This is the concrete implementation of {@link CategoryDAO}.
*/
public class GenericCategoryDAOImpl extends AbstractDAOImpl implements CategoryDAO {
@Override
public Category addCategory(Category category) throws ApplicationManagementDAOException {
Connection connection;
PreparedStatement statement = null;
String sql = "INSERT INTO APPM_APPLICATION_CATEGORY (NAME, DESCRIPTION) VALUES (?, ?)";
String[] generatedColumns = { "ID" };
ResultSet rs = null;
try {
connection = this.getDBConnection();
statement = connection.prepareStatement(sql, generatedColumns);
statement.setString(1, category.getName());
statement.setString(2, category.getDescription());
statement.executeUpdate();
rs = statement.getGeneratedKeys();
if (rs.next()) {
category.setId(rs.getInt(1));
}
return category;
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
"Database connection while trying to update the categroy " + category.getName(), e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException("SQL exception while executing the query '" + sql + "' .", e);
} finally {
Util.cleanupResources(statement, rs);
}
}
@Override
public List<Category> getCategories() throws ApplicationManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
String sql = "SELECT * FROM APPM_APPLICATION_CATEGORY";
List<Category> categories = new ArrayList<>();
try {
conn = this.getDBConnection();
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
while (rs.next()) {
Category category = new Category();
category.setId(rs.getInt("ID"));
category.setName(rs.getString("NAME"));
category.setDescription(rs.getString("DESCRIPTION"));
categories.add(category);
}
return categories;
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Database Connection Exception while trying to get the "
+ "application categories", e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException("SQL Exception while trying to get the application "
+ "categories, while executing " + sql, e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
@Override
public Category getCategory(String name) throws ApplicationManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
String sql = "SELECT * FROM APPM_APPLICATION_CATEGORY WHERE NAME = ?";
try {
conn = this.getDBConnection();
stmt = conn.prepareStatement(sql);
stmt.setString(1, name);
rs = stmt.executeQuery();
if (rs.next()) {
Category category = new Category();
category.setId(rs.getInt("ID"));
category.setName(rs.getString("NAME"));
category.setDescription(rs.getString("DESCRIPTION"));
return category;
}
return null;
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Database Connection Exception while trying to get the "
+ "application categories", e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException("SQL Exception while trying to get the application "
+ "categories, while executing " + sql, e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
@Override
public void deleteCategory(String name) throws ApplicationManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
String sql = "DELETE FROM APPM_APPLICATION_CATEGORY WHERE NAME = ?";
try {
conn = this.getDBConnection();
stmt = conn.prepareStatement(sql);
stmt.setString(1, name);
stmt.executeUpdate();
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
"Database Connection Exception while trying to delete the category " + name, e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
"SQL Exception while trying to delete the category " + name + " while executing the query " +
sql, e);
} finally {
Util.cleanupResources(stmt, null);
}
}
}

@ -0,0 +1,187 @@
/*
*
* Copyright (c) ${date}, 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.application.mgt.core.dao.impl.lifecycle;
import org.wso2.carbon.device.application.mgt.common.Lifecycle;
import org.wso2.carbon.device.application.mgt.common.LifecycleState;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.core.dao.LifecycleDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.Util;
import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl;
import org.wso2.carbon.device.application.mgt.core.exception.LifeCycleManagementDAOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* Concrete implementation for Lifecycle related DB operations.
*/
public class GenericLifecycleImpl extends AbstractDAOImpl implements LifecycleDAO {
@Override
public Lifecycle getLifeCycleOfApplication(int identifier) throws LifeCycleManagementDAOException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = this.getDBConnection();
String sql = "SELECT ID, CREATED_BY, CREATED_TIMESTAMP, APPROVED, APPROVED_TIMESTAMP, APPROVED_BY, "
+ "PUBLISHED, PUBLISHED_BY, PUBLISHED_TIMESTAMP, RETIRED FROM AP_APP_LIFECYCLE WHERE "
+ "AP_APP_RELEASE_ID = ? ";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, identifier);
rs = stmt.executeQuery();
Lifecycle lifecycle = null;
if (rs.next()) {
lifecycle = new Lifecycle();
lifecycle.setId(rs.getInt("ID"));
lifecycle.setCreatedBy(rs.getString("CREATED_BY"));
lifecycle.setCreatedAt(rs.getDate("CREATED_TIMESTAMP"));
lifecycle.setIsApproved(rs.getInt("APPROVED"));
lifecycle.setApprovedAt(rs.getDate("APPROVED_TIMESTAMP"));
lifecycle.setApprovedBy(rs.getString("APPROVED_BY"));
lifecycle.setIsPublished(rs.getInt("PUBLISHED"));
lifecycle.setPublishedBy(rs.getString("PUBLISHED_BY"));
lifecycle.setPublishedAt(rs.getDate("PUBLISHED_TIMESTAMP"));
lifecycle.setIsRetired(rs.getInt("RETIRED"));
}
return lifecycle;
} catch (SQLException e) {
throw new LifeCycleManagementDAOException("Error occurred while getting application List", e);
} catch (DBConnectionException e) {
throw new LifeCycleManagementDAOException("Error occurred while obtaining the DB connection.", e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
@Override
public List<Lifecycle> getLifecyclesOfAllAppVersions(int identifier) throws LifeCycleManagementDAOException {
List<Lifecycle> lifecycles = new ArrayList<>();
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = this.getDBConnection();
String sql = "SELECT ID, CREATED_BY, CREATED_TIMESTAMP, APPROVED, APPROVED_TIMESTAMP, APPROVED_BY, "
+ "PUBLISHED, PUBLISHED_BY, PUBLISHED_TIMESTAMP, RETIRED FROM AP_APP_LIFECYCLE WHERE "
+ "AP_APP_ID = ? ";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, identifier);
rs = stmt.executeQuery();
while (rs.next()) {
Lifecycle lifecycle = new Lifecycle();
lifecycle.setId(rs.getInt("ID"));
lifecycle.setCreatedBy(rs.getString("CREATED_BY"));
lifecycle.setCreatedAt(rs.getDate("CREATED_TIMESTAMP"));
lifecycle.setIsApproved(rs.getInt("APPROVED"));
lifecycle.setApprovedAt(rs.getDate("APPROVED_TIMESTAMP"));
lifecycle.setApprovedBy(rs.getString("APPROVED_BY"));
lifecycle.setIsPublished(rs.getInt("PUBLISHED"));
lifecycle.setPublishedBy(rs.getString("PUBLISHED_BY"));
lifecycle.setPublishedAt(rs.getDate("PUBLISHED_TIMESTAMP"));
lifecycle.setIsRetired(rs.getInt("RETIRED"));
lifecycles.add(lifecycle);
}
} catch (DBConnectionException e) {
throw new LifeCycleManagementDAOException("Error occurred while obtaining the DB connection.", e);
} catch (SQLException e) {
throw new LifeCycleManagementDAOException("Error occurred while retrieving lifecycle states.", e);
} finally {
Util.cleanupResources(stmt, rs);
}
return lifecycles;
}
@Override
public void addLifecycle(Lifecycle lifecycle) throws LifeCycleManagementDAOException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = this.getDBConnection();
String sql = "INSERT INTO AP_APP_LIFECYCLE ('CREATED_BY', 'CREATED_TIMESTAMP') VALUES (?, ?)";
stmt = conn.prepareStatement(sql);
stmt.setString(1, lifecycle.getCreatedBy());
stmt.setDate(2, new Date(lifecycle.getCreatedAt().getTime()));
stmt.executeUpdate();
} catch (DBConnectionException e) {
throw new LifeCycleManagementDAOException("Error occurred while obtaining the DB connection.", e);
} catch (SQLException e) {
throw new LifeCycleManagementDAOException("Error occurred while adding lifecycle ", e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
// have to modify
@Override
public void updateLifecycleOfApplication(LifecycleState state) throws LifeCycleManagementDAOException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = this.getDBConnection();
String sql = "INSERT INTO APPM_LIFECYCLE_STATE ('NAME', 'IDENTIFIER',) VALUES (?, ?)";
stmt = conn.prepareStatement(sql);
stmt.setString(1, state.getName());
stmt.setString(2, state.getIdentifier());
stmt.executeUpdate();
} catch (DBConnectionException e) {
throw new LifeCycleManagementDAOException("Error occurred while obtaining the DB connection.", e);
} catch (SQLException e) {
throw new LifeCycleManagementDAOException("Error occurred while adding lifecycle: " + state.getIdentifier(), e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
@Override
public void deleteLifecycleOfApplication(String identifier) throws LifeCycleManagementDAOException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = this.getDBConnection();
String sql = "DELETE FROM APPM_LIFECYCLE_STATE WHERE IDENTIFIER = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, identifier);
stmt.executeUpdate();
} catch (DBConnectionException e) {
throw new LifeCycleManagementDAOException("Error occurred while obtaining the DB connection.", e);
} catch (SQLException e) {
throw new LifeCycleManagementDAOException("Error occurred while deleting lifecycle: " + identifier, e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
// end modification
}

@ -24,7 +24,7 @@ import org.wso2.carbon.device.application.mgt.core.dao.LifecycleStateDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.Util;
import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.exception.DAOException;
import org.wso2.carbon.device.application.mgt.core.exception.LifeCycleManagementDAOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
@ -73,7 +73,7 @@ public class GenericLifecycleStateImpl extends AbstractDAOImpl implements Lifecy
}
@Override
public List<LifecycleState> getLifecycleStates() throws DAOException {
public List<LifecycleState> getLifecycleStates() throws LifeCycleManagementDAOException {
List<LifecycleState> lifecycleStates = new ArrayList<>();
Connection conn = null;
PreparedStatement stmt = null;
@ -91,9 +91,9 @@ public class GenericLifecycleStateImpl extends AbstractDAOImpl implements Lifecy
lifecycleStates.add(lifecycleState);
}
} catch (DBConnectionException e) {
throw new DAOException("Error occurred while obtaining the DB connection.", e);
throw new LifeCycleManagementDAOException("Error occurred while obtaining the DB connection.", e);
} catch (SQLException e) {
throw new DAOException("Error occurred while retrieving lifecycle states.", e);
throw new LifeCycleManagementDAOException("Error occurred while retrieving lifecycle states.", e);
} finally {
Util.cleanupResources(stmt, rs);
}
@ -101,7 +101,7 @@ public class GenericLifecycleStateImpl extends AbstractDAOImpl implements Lifecy
}
@Override
public void addLifecycleState(LifecycleState state) throws DAOException {
public void addLifecycleState(LifecycleState state) throws LifeCycleManagementDAOException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
@ -115,16 +115,16 @@ public class GenericLifecycleStateImpl extends AbstractDAOImpl implements Lifecy
stmt.executeUpdate();
} catch (DBConnectionException e) {
throw new DAOException("Error occurred while obtaining the DB connection.", e);
throw new LifeCycleManagementDAOException("Error occurred while obtaining the DB connection.", e);
} catch (SQLException e) {
throw new DAOException("Error occurred while adding lifecycle: " + state.getIdentifier(), e);
throw new LifeCycleManagementDAOException("Error occurred while adding lifecycle: " + state.getIdentifier(), e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
@Override
public void deleteLifecycleState(String identifier) throws DAOException {
public void deleteLifecycleState(String identifier) throws LifeCycleManagementDAOException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
@ -136,9 +136,9 @@ public class GenericLifecycleStateImpl extends AbstractDAOImpl implements Lifecy
stmt.executeUpdate();
} catch (DBConnectionException e) {
throw new DAOException("Error occurred while obtaining the DB connection.", e);
throw new LifeCycleManagementDAOException("Error occurred while obtaining the DB connection.", e);
} catch (SQLException e) {
throw new DAOException("Error occurred while deleting lifecycle: " + identifier, e);
throw new LifeCycleManagementDAOException("Error occurred while deleting lifecycle: " + identifier, e);
} finally {
Util.cleanupResources(stmt, rs);
}

@ -1,703 +0,0 @@
/*
* Copyright (c) 2017, 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.application.mgt.core.dao.impl.platform;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.common.Platform;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.core.dao.PlatformDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.Util;
import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl;
import org.wso2.carbon.device.application.mgt.core.exception.PlatformManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Generic Implementation for handling Platform management related database operations.
*/
public class GenericPlatformDAOImpl extends AbstractDAOImpl implements PlatformDAO {
private static Log log = LogFactory.getLog(GenericPlatformDAOImpl.class);
@Override
public int register(int tenantId, Platform platform) throws PlatformManagementDAOException {
PreparedStatement preparedStatement = null;
try {
int platformId = getPlatformId(tenantId, platform.getIdentifier());
if (platformId == -1) {
Connection connection = this.getDBConnection();
if (!platform.isFileBased()) {
String insertToPlatform = "INSERT INTO APPM_PLATFORM (IDENTIFIER, TENANT_ID, NAME, FILE_BASED, "
+ "DESCRIPTION, IS_SHARED, ICON_NAME, IS_DEFAULT_TENANT_MAPPING)" + " VALUES (?, ?, ?, ?, "
+ "?, ?, ?, ?)";
preparedStatement = connection.prepareStatement(insertToPlatform);
preparedStatement.setString(1, platform.getIdentifier());
preparedStatement.setInt(2, tenantId);
preparedStatement.setString(3, platform.getName());
preparedStatement.setBoolean(4, false);
preparedStatement.setString(5, platform.getDescription());
preparedStatement.setBoolean(6, platform.isShared());
preparedStatement.setString(7, platform.getIconName());
preparedStatement.setBoolean(8, platform.isDefaultTenantMapping());
preparedStatement.execute();
platformId = getPlatformId(tenantId, platform.getIdentifier());
String insertPlatformProps =
"INSERT INTO APPM_PLATFORM_PROPERTIES (PLATFORM_ID, PROP_NAME, OPTIONAL, "
+ "DEFAULT_VALUE) VALUES ( ? , ?, ? , ?)";
if (platform.getProperties() != null) {
for (Platform.Property property : platform.getProperties()) {
preparedStatement = connection.prepareStatement(insertPlatformProps);
preparedStatement.setInt(1, platformId);
preparedStatement.setString(2, property.getName());
preparedStatement.setBoolean(3, property.isOptional());
preparedStatement.setString(4, property.getDefaultValue());
preparedStatement.execute();
}
}
//Adding tags to the database.
Boolean isBatchExecutionSupported = ConnectionManagerUtil.isBatchQuerySupported();
String insertTags = "INSERT INTO APPM_PLATFORM_TAG (NAME, PLATFORM_ID) VALUES (?, ?)";
preparedStatement = connection.prepareStatement(insertTags);
if (platform.getTags() != null) {
for (String tag : platform.getTags()) {
preparedStatement.setString(1, tag);
preparedStatement.setInt(2, platformId);
if (isBatchExecutionSupported) {
preparedStatement.addBatch();
} else {
preparedStatement.execute();
}
}
if (isBatchExecutionSupported) {
preparedStatement.executeBatch();
}
}
} else {
String insertToPlatform =
"INSERT INTO APPM_PLATFORM (IDENTIFIER, TENANT_ID, FILE_BASED, IS_SHARED, "
+ "IS_DEFAULT_TENANT_MAPPING) VALUES (?, ?, ?, ?, ?)";
preparedStatement = connection.prepareStatement(insertToPlatform);
preparedStatement.setString(1, platform.getIdentifier());
preparedStatement.setInt(2, tenantId);
preparedStatement.setBoolean(3, true);
preparedStatement.setBoolean(4, platform.isShared());
preparedStatement.setBoolean(5, platform.isDefaultTenantMapping());
preparedStatement.execute();
}
if (platformId == -1) {
platformId = getPlatformId(tenantId, platform.getIdentifier());
}
return platformId;
} else {
if (!platform.isFileBased()) {
throw new PlatformManagementDAOException(
"Platform - " + platform.getIdentifier() + " is already registered for tenant - "
+ tenantId);
} else {
return platformId;
}
}
} catch (SQLException e) {
throw new PlatformManagementDAOException("Error while executing the SQL query. ", e);
} catch (DBConnectionException e) {
throw new PlatformManagementDAOException(
"Unable to obtain the connection while trying to register the platform - " + platform
.getIdentifier() + " for tenant - " + tenantId, e);
} finally {
Util.cleanupResources(preparedStatement, null);
}
}
@Override
public void update(int tenantId, String oldPlatformIdentifier, Platform platform)
throws PlatformManagementDAOException {
PreparedStatement preparedStatement = null;
try {
int platformId = getPlatformId(tenantId, oldPlatformIdentifier);
boolean isIdentifierNull = platform.getIdentifier() == null;
boolean isNameNull = platform.getName() == null;
if (platformId != -1) {
Connection connection = this.getDBConnection();
if (!platform.isFileBased()) {
String insertToPlatform = "UPDATE APPM_PLATFORM SET DESCRIPTION=?, IS_SHARED=?, ICON_NAME=?, "
+ "IS_DEFAULT_TENANT_MAPPING=?";
if (!isIdentifierNull) {
insertToPlatform += ",IDENTIFIER = ? ";
}
if (!isNameNull) {
insertToPlatform += ", NAME =?";
}
insertToPlatform += " WHERE ID = ?";
preparedStatement = connection.prepareStatement(insertToPlatform);
preparedStatement.setString(1, platform.getDescription());
preparedStatement.setBoolean(2, platform.isShared());
preparedStatement.setString(3, platform.getIconName());
preparedStatement.setBoolean(4, platform.isDefaultTenantMapping());
if (!isIdentifierNull && !isNameNull) {
preparedStatement.setString(5, platform.getIdentifier());
preparedStatement.setString(6, platform.getName());
preparedStatement.setInt(7, platformId);
} else if (isIdentifierNull && !isNameNull) {
preparedStatement.setString(5, platform.getName());
preparedStatement.setInt(6, platformId);
} else if (!isIdentifierNull) {
preparedStatement.setString(5, platform.getIdentifier());
preparedStatement.setInt(6, platformId);
} else {
preparedStatement.setInt(5, platformId);
}
preparedStatement.execute();
platformId = getPlatformId(tenantId, platform.getIdentifier());
String deletePlatformProps = "DELETE FROM APPM_PLATFORM_PROPERTIES WHERE PLATFORM_ID=?";
preparedStatement = connection.prepareStatement(deletePlatformProps);
preparedStatement.setInt(1, platformId);
preparedStatement.execute();
String insertPlatformProps =
"INSERT INTO APPM_PLATFORM_PROPERTIES (PLATFORM_ID, PROP_NAME, OPTIONAL,"
+ " DEFAULT_VALUE) VALUES ( ? , ?, ? , ?)";
if (platform.getProperties() != null) {
for (Platform.Property property : platform.getProperties()) {
preparedStatement = connection.prepareStatement(insertPlatformProps);
preparedStatement.setInt(1, platformId);
preparedStatement.setString(2, property.getName());
preparedStatement.setBoolean(3, property.isOptional());
preparedStatement.setString(4, property.getDefaultValue());
preparedStatement.execute();
}
}
} else if (!isIdentifierNull) {
String insertToPlatform = "UPDATE APPM_PLATFORM SET IDENTIFIER = ? WHERE ID = ?";
preparedStatement = connection.prepareStatement(insertToPlatform);
preparedStatement.setString(1, platform.getIdentifier());
preparedStatement.setInt(2, platformId);
preparedStatement.execute();
}
} else {
throw new PlatformManagementDAOException(
"Cannot find any platform that was registered with identifier - " + platform.getIdentifier()
+ " for tenant - " + tenantId);
}
} catch (SQLException e) {
throw new PlatformManagementDAOException("Error while executing the SQL query. ", e);
} catch (DBConnectionException e) {
throw new PlatformManagementDAOException(
"Unable to obtain the connection while trying to register the platform - " + platform
.getIdentifier() + " for tenant - " + tenantId, e);
} finally {
Util.cleanupResources(preparedStatement, null);
}
}
private int getPlatformId(int tenantId, String platformIdentifier) throws PlatformManagementDAOException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String query = SQLQueries.queryToGetPlatformId;
try {
Connection connection = this.getDBConnection();
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, tenantId);
preparedStatement.setString(2, platformIdentifier);
preparedStatement.setString(3, platformIdentifier);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return resultSet.getInt("ID");
}
return -1;
} catch (DBConnectionException e) {
throw new PlatformManagementDAOException("Error when trying to obtaining the database connection.", e);
} catch (SQLException e) {
throw new PlatformManagementDAOException("Error in executing the query - " + query, e);
} finally {
Util.cleanupResources(preparedStatement, resultSet);
}
}
@Override
public void unregister(int tenantId, String platformIdenfier, boolean isFileBased)
throws PlatformManagementDAOException {
PreparedStatement preparedStatement = null;
String deletePlatform = null;
try {
Platform platform = getPlatform(tenantId, platformIdenfier);
if (platform != null) {
if (isFileBased == platform.isFileBased()) {
Connection connection = this.getDBConnection();
deletePlatform = "DELETE FROM APPM_PLATFORM WHERE ID = ?";
preparedStatement = connection.prepareStatement(deletePlatform);
preparedStatement.setInt(1, platform.getId());
preparedStatement.execute();
} else {
if (isFileBased) {
throw new PlatformManagementDAOException("Platform with identifier - " + platformIdenfier
+ " is not a file based platform. Try to remove that using PlatformManagement APIs");
} else {
throw new PlatformManagementDAOException("Platform with identifier - " + platformIdenfier
+ " is a file based platform. Try to remove that by un-deploying the relevant file.");
}
}
} else {
throw new PlatformManagementDAOException(
"Platform identifier - " + platformIdenfier + " is not registered for tenant - " + tenantId);
}
} catch (DBConnectionException e) {
throw new PlatformManagementDAOException(
"Unable to obtain the connection while trying to register the platform - " + platformIdenfier
+ " for tenant - " + tenantId, e);
} catch (SQLException e) {
throw new PlatformManagementDAOException("Error while executing the SQL query : " + deletePlatform + " "
+ "while trying to un-register the platform with identifier " + platformIdenfier, e);
} finally {
Util.cleanupResources(preparedStatement, null);
}
}
public void addMapping(int tenantId, List<String> platformIdentifiers) throws PlatformManagementDAOException {
String insertMapping = "INSERT INTO APPM_PLATFORM_TENANT_MAPPING(TENANT_ID, PLATFORM_ID) VALUES (?, ?)";
PreparedStatement preparedStatement = null;
try {
for (String platformIdentifier : platformIdentifiers) {
if (getTenantPlatformMapping(tenantId, platformIdentifier) == -1) {
int platformId = getPlatformId(tenantId, platformIdentifier);
Connection connection = this.getDBConnection();
preparedStatement = connection.prepareStatement(insertMapping);
preparedStatement.setInt(1, tenantId);
preparedStatement.setInt(2, platformId);
preparedStatement.execute();
} else {
log.error("Platform identifier - " + platformIdentifier + " is already assigned to tenant domain"
+ " - " + tenantId);
}
}
} catch (DBConnectionException e) {
throw new PlatformManagementDAOException("Error occurred when getting the connection for the database. ",
e);
} catch (SQLException e) {
throw new PlatformManagementDAOException("Error occured while executing the SQL query - " + insertMapping,
e);
} finally {
Util.cleanupResources(preparedStatement, null);
}
}
private int getTenantPlatformMapping(int tenantId, String platformIdentifier)
throws PlatformManagementDAOException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String getMapping = "SELECT MAPPING.ID as ID FROM (SELECT ID, PLATFORM_ID FROM APPM_PLATFORM_TENANT_MAPPING "
+ "WHERE TENANT_ID=?) MAPPING JOIN (SELECT ID FROM APPM_PLATFORM WHERE APPM_PLATFORM.IDENTIFIER=?) "
+ "PLATFORM ON MAPPING.PLATFORM_ID=PLATFORM.ID";
try {
Connection connection = this.getDBConnection();
preparedStatement = connection.prepareStatement(getMapping);
preparedStatement.setInt(1, tenantId);
preparedStatement.setString(2, platformIdentifier);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return resultSet.getInt("ID");
}
return -1;
} catch (DBConnectionException e) {
throw new PlatformManagementDAOException(
"Error occurred while obtaining the connection to get the existing " + "Tenant - Platform Mapping.",
e);
} catch (SQLException e) {
throw new PlatformManagementDAOException("Error occured while executing the SQL query - " + getMapping, e);
} finally {
Util.cleanupResources(preparedStatement, resultSet);
}
}
@Override
public void removeMapping(int tenantId, String platformIdentifier) throws PlatformManagementDAOException {
String deleteMapping = "DELETE FROM APPM_PLATFORM_TENANT_MAPPING WHERE ID = ?";
PreparedStatement preparedStatement = null;
try {
int mappingId = getTenantPlatformMapping(tenantId, platformIdentifier);
if (mappingId != -1) {
Connection connection = this.getDBConnection();
preparedStatement = connection.prepareStatement(deleteMapping);
preparedStatement.setInt(1, mappingId);
preparedStatement.execute();
} else {
throw new PlatformManagementDAOException(
"Platform - " + platformIdentifier + " is already unassigned for tenant - " + tenantId);
}
} catch (DBConnectionException e) {
throw new PlatformManagementDAOException(
"Error occurred while unassigning the platform - " + platformIdentifier + " for tenant - "
+ tenantId);
} catch (SQLException e) {
throw new PlatformManagementDAOException("Error occurred while executing the query - " + deleteMapping);
} finally {
Util.cleanupResources(preparedStatement, null);
}
}
@Override
public void removeMappingTenants(String platformIdentifier) throws PlatformManagementDAOException {
PreparedStatement preparedStatement = null;
int platformId = getPlatformId(MultitenantConstants.SUPER_TENANT_ID, platformIdentifier);
String getMapping = "DELETE FROM APPM_PLATFORM_TENANT_MAPPING WHERE TENANT_ID != ? AND PLATFORM_ID=?";
try {
Connection connection = this.getDBConnection();
preparedStatement = connection.prepareStatement(getMapping);
preparedStatement.setInt(1, MultitenantConstants.SUPER_TENANT_ID);
preparedStatement.setInt(2, platformId);
preparedStatement.execute();
} catch (DBConnectionException e) {
throw new PlatformManagementDAOException(
"Error occurred while obtaining the connection to remove existing " + "Tenant - Platform Mapping"
+ " for the platform : " + platformIdentifier, e);
} catch (SQLException e) {
throw new PlatformManagementDAOException("Error occurred while executing the SQL query - " + getMapping, e);
} finally {
Util.cleanupResources(preparedStatement, null);
}
}
@Override
public List<Platform> getPlatforms(int tenantId) throws PlatformManagementDAOException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
if (log.isDebugEnabled()) {
log.debug("GetPlaforms request received for the tenant ID " + tenantId);
}
String selectQuery = SQLQueries.queryToGetPlatforms;
try {
Connection connection = this.getDBConnection();
preparedStatement = connection.prepareStatement(selectQuery);
preparedStatement.setInt(1, tenantId);
preparedStatement.setInt(2, tenantId);
resultSet = preparedStatement.executeQuery();
List<Platform> platforms = new ArrayList<>();
if (log.isDebugEnabled()) {
log.debug("Platform retrieved for the tenant Id " + tenantId);
}
while (resultSet.next()) {
int mappingID = resultSet.getInt(1);
String identifier = resultSet.getString(2);
Platform platform = getPlatform(tenantId, identifier);
if (mappingID != 0) {
platform.setEnabled(true);
} else {
platform.setEnabled(false);
}
platforms.add(platform);
if (log.isDebugEnabled()) {
log.debug("Platform Identifier - " + identifier + " isEnabled - " + platform.isEnabled());
}
}
if (log.isDebugEnabled()) {
log.debug("Number of platforms available for the tenant ID - " + tenantId + " :" + platforms.size());
}
return platforms;
} catch (DBConnectionException e) {
throw new PlatformManagementDAOException(
"Error occurred when loading the platforms for tenant - " + tenantId, e);
} catch (SQLException e) {
throw new PlatformManagementDAOException("Error occurred when executing query - " + selectQuery, e);
} finally {
Util.cleanupResources(preparedStatement, resultSet);
}
}
public Platform getPlatform(String tenantDomain, String platformIdentifier) throws PlatformManagementDAOException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String platformQuery = "SELECT * FROM (SELECT * FROM APPM_PLATFORM WHERE (TENANT_DOMAIN=? AND IDENTIFIER=?) "
+ "OR (IS_SHARED = TRUE AND IDENTIFIER=?) AND FILE_BASED = FALSE ) PLATFORM "
+ "LEFT JOIN APPM_PLATFORM_PROPERTIES PROPS ON PLATFORM.ID = PROPS.PLATFORM_ID";
try {
Connection connection = this.getDBConnection();
preparedStatement = connection.prepareStatement(platformQuery);
preparedStatement.setString(1, tenantDomain);
preparedStatement.setString(2, platformIdentifier);
preparedStatement.setString(3, platformIdentifier);
resultSet = preparedStatement.executeQuery();
Platform platform = new Platform();
if (resultSet.next()) {
platform.setId(resultSet.getInt("PLATFORM.ID"));
platform.setIdentifier(platformIdentifier);
platform.setName(resultSet.getString("PLATFORM.NAME"));
platform.setIconName(resultSet.getString("PLATFORM.DESCRIPTION"));
platform.setIconName(resultSet.getString("PLATFORM.ICON_NAME"));
platform.setShared(resultSet.getBoolean("PLATFORM.IS_SHARED"));
platform.setFileBased(false);
List<Platform.Property> properties = new ArrayList<>();
do {
if (resultSet.getString("PROPS.PROP_NAME") != null) {
Platform.Property property = new Platform.Property();
property.setName(resultSet.getString("PROPS.PROP_NAME"));
property.setOptional(resultSet.getBoolean("PROPS.OPTIONAL"));
property.setDefaultValue(resultSet.getString("PROPS.DEFAUL_VALUE"));
properties.add(property);
}
} while (resultSet.next());
platform.setProperties(properties);
} else {
platform.setIdentifier(platformIdentifier);
platform.setFileBased(true);
}
return platform;
} catch (DBConnectionException e) {
throw new PlatformManagementDAOException("Error when loading the platform - " + platformIdentifier, e);
} catch (SQLException e) {
throw new PlatformManagementDAOException("Error in executing the query - " + platformQuery, e);
} finally {
Util.cleanupResources(preparedStatement, resultSet);
}
}
@Override
public Platform getPlatform(int tenantId, String identifier) throws PlatformManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
String sql = "";
try {
conn = this.getDBConnection();
sql = SQLQueries.queryToGetPlatform;
stmt = conn.prepareStatement(sql);
stmt.setString(1, identifier);
stmt.setInt(2, tenantId);
stmt.setInt(3, tenantId);
rs = stmt.executeQuery();
Platform platform = null;
if (rs.next()) {
platform = new Platform();
platform.setFileBased(rs.getBoolean(3));
platform.setIdentifier(rs.getString(2));
platform.setShared(rs.getBoolean(8));
platform.setDefaultTenantMapping(rs.getBoolean(9));
platform.setId(rs.getInt(4));
//Getting tags
sql = "SELECT * FROM APPM_PLATFORM_TAG WHERE PLATFORM_ID=?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, rs.getInt(4));
ResultSet rsTags = stmt.executeQuery();
List<String> tags = new ArrayList<>();
while (rsTags.next()) {
tags.add(rsTags.getString("NAME"));
}
platform.setTags(tags);
if (!platform.isFileBased()) {
platform.setName(rs.getString(5));
platform.setDescription(rs.getString(6));
platform.setIconName(rs.getString(7));
if (rs.getInt(1) != 0) {
platform.setEnabled(true);
} else {
platform.setEnabled(false);
}
}
}
return platform;
} catch (SQLException e) {
throw new PlatformManagementDAOException(
"Error occurred while getting platform with the identifier " + identifier + ", for the tenant : "
+ tenantId, e);
} catch (DBConnectionException e) {
throw new PlatformManagementDAOException("Error occurred while obtaining the DB connection.", e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
@Override
public void removePlatforms(int tenantId) throws PlatformManagementDAOException {
PreparedStatement preparedStatement = null;
String sql = "DELETE FROM APPM_PLATFORM WHERE TENANT_ID = ?";
try {
Connection connection = this.getDBConnection();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, tenantId);
preparedStatement.executeUpdate();
} catch (DBConnectionException e) {
throw new PlatformManagementDAOException(
"Database connection error while removing the platforms for the " + "tenant - " + tenantId);
} catch (SQLException e) {
throw new PlatformManagementDAOException(
"SQL exception while executing the query " + sql + " for " + "the tenant : " + tenantId);
} finally {
Util.cleanupResources(preparedStatement, null);
}
}
@Override
public int getSuperTenantAndOwnPlatforms(String platformIdentifier, int tenantId)
throws PlatformManagementDAOException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String sql = SQLQueries.queryToGetSupertenantAndOwnPlatforms;
try {
Connection connection = this.getDBConnection();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, platformIdentifier);
preparedStatement.setInt(2, tenantId);
preparedStatement.setInt(3, MultitenantConstants.SUPER_TENANT_ID);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return resultSet.getInt(1);
} else {
return -1;
}
} catch (DBConnectionException e) {
throw new PlatformManagementDAOException(
"Database connection error while removing the platfor for the " + "tenant - " + tenantId);
} catch (SQLException e) {
throw new PlatformManagementDAOException(
"SQL exception while executing the query " + sql + " for " + "the tenant : " + tenantId);
} finally {
Util.cleanupResources(preparedStatement, resultSet);
}
}
@Override
public Platform getTenantOwnedPlatform(int tenantId, String platformIdentifier)
throws PlatformManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
String sql = "";
try {
conn = this.getDBConnection();
sql = "SELECT * from APPM_PLATFORM WHERE TENANT_ID = ? AND IDENTIFIER = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
stmt.setString(2, platformIdentifier);
rs = stmt.executeQuery();
Platform platform = null;
if (rs.next()) {
platform = new Platform();
platform.setFileBased(rs.getBoolean("FILE_BASED"));
platform.setIdentifier(rs.getString("IDENTIFIER"));
platform.setShared(rs.getBoolean("IS_SHARED"));
platform.setDefaultTenantMapping(rs.getBoolean("IS_DEFAULT_TENANT_MAPPING"));
if (!platform.isFileBased()) {
platform.setId(rs.getInt("ID"));
platform.setName(rs.getString("NAME"));
platform.setDescription(rs.getString("DESCRIPTION"));
platform.setIconName(rs.getString("ICON_NAME"));
}
}
return platform;
} catch (SQLException e) {
throw new PlatformManagementDAOException("Error occurred while executing the query : " + sql + " for "
+ "getting platforms owned by tenant : " + tenantId, e);
} catch (DBConnectionException e) {
throw new PlatformManagementDAOException(
"Error occurred while obtaining the DB connection for getting " + "platforms owned by tenant : "
+ tenantId, e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
@Override
public int getMultiTenantPlatforms(String identifier) throws PlatformManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
String sql = "";
try {
conn = this.getDBConnection();
sql = "SELECT ID from APPM_PLATFORM WHERE TENANT_ID != ? AND IDENTIFIER=?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, MultitenantConstants.SUPER_TENANT_ID);
stmt.setString(2, identifier);
rs = stmt.executeQuery();
if (rs.next()) {
return rs.getInt(1);
}
return -1;
} catch (DBConnectionException e) {
throw new PlatformManagementDAOException("Database Connection exception while trying to get the tenants "
+ "which has the platforms with the platform identifier : " + identifier, e);
} catch (SQLException e) {
throw new PlatformManagementDAOException("SQL exception while executing the query " + sql + " to get the"
+ " tenants which has the platform with the platform identifier : " + identifier, e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
@Override
public List<String> getPlatformTags(String name) throws PlatformManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
String sql = "";
List<String> tagList = new ArrayList<>();
try {
conn = this.getDBConnection();
sql = "SELECT NAME FROM APPM_PLATFORM_TAG WHERE NAME LIKE ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, name + "%");
rs = stmt.executeQuery();
if (rs.next()) {
tagList.add(rs.getString("NAME"));
}
return tagList;
} catch (DBConnectionException e) {
throw new PlatformManagementDAOException("Database Connection exception while trying to get the platform "
+ "tags that are starting with " + name, e);
} catch (SQLException e) {
throw new PlatformManagementDAOException("SQL exception while executing the query " + sql + " to get the"
+ " platform tags that are starting with " + name, e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
}

@ -1,87 +0,0 @@
/*
* Copyright (c) 2017, 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.application.mgt.core.dao.impl.platform;
import org.wso2.carbon.device.application.mgt.common.Platform;
import org.wso2.carbon.device.application.mgt.core.exception.PlatformManagementDAOException;
import java.util.List;
/**
* Oracle and MsSQL specific implementation for Platform DAO.
*/
public class OracleMsSQLPlatformDAOImpl extends GenericPlatformDAOImpl {
@Override
public int getSuperTenantAndOwnPlatforms(String platformIdentifier, int tenantId)
throws PlatformManagementDAOException {
SQLQueries.queryToGetSupertenantAndOwnPlatforms = "SELECT ID from APPM_PLATFORM where IDENTIFIER "
+ "= ? AND (TENANT_ID = ? OR (TENANT_ID = ? AND IS_SHARED = 1))";
return super.getSuperTenantAndOwnPlatforms(platformIdentifier, tenantId);
}
@Override
public int register(int tenantId, Platform platform) throws PlatformManagementDAOException {
SQLQueries.queryToGetPlatformId =
"SELECT ID FROM APPM_PLATFORM WHERE (TENANT_ID=? AND IDENTIFIER=?) OR (IS_SHARED = 1 AND "
+ "IDENTIFIER=?)";
return super.register(tenantId, platform);
}
@Override
public Platform getPlatform(int tenantId, String identifier) throws PlatformManagementDAOException {
SQLQueries.queryToGetPlatform =
"SELECT MAPPING.ID, PLATFORM.IDENTIFIER, PLATFORM.FILE_BASED, PLATFORM.ID, PLATFORM.NAME, "
+ "PLATFORM.DESCRIPTION, PLATFORM.ICON_NAME, PLATFORM.IS_SHARED, "
+ "PLATFORM.IS_DEFAULT_TENANT_MAPPING FROM (SELECT * FROM APPM_PLATFORM WHERE IDENTIFIER= ? "
+ "AND (TENANT_ID=? OR IS_SHARED = 1)) PLATFORM LEFT JOIN APPM_PLATFORM_TENANT_MAPPING "
+ "MAPPING ON PLATFORM.ID = MAPPING.PLATFORM_ID AND MAPPING.TENANT_ID = ?";
return super.getPlatform(tenantId, identifier);
}
public void removeMappingTenants(String platformIdentifier) throws PlatformManagementDAOException {
SQLQueries.queryToGetPlatformId =
"SELECT ID FROM APPM_PLATFORM WHERE (TENANT_ID=? AND IDENTIFIER=?) OR (IS_SHARED = 1 AND "
+ "IDENTIFIER=?)";
super.removeMappingTenants(platformIdentifier);
}
public void update(int tenantId, String oldPlatformIdentifier, Platform platform)
throws PlatformManagementDAOException {
SQLQueries.queryToGetPlatformId =
"SELECT ID FROM APPM_PLATFORM WHERE (TENANT_ID=? AND IDENTIFIER=?) OR (IS_SHARED = 1 AND "
+ "IDENTIFIER=?)";
super.update(tenantId, oldPlatformIdentifier, platform);
}
public void addMapping(int tenantId, List<String> platformIdentifiers) throws PlatformManagementDAOException {
SQLQueries.queryToGetPlatformId =
"SELECT ID FROM APPM_PLATFORM WHERE (TENANT_ID=? AND IDENTIFIER=?) OR (IS_SHARED = 1 AND "
+ "IDENTIFIER=?)";
super.addMapping(tenantId, platformIdentifiers);
}
public List<Platform> getPlatforms(int tenantId) throws PlatformManagementDAOException {
SQLQueries.queryToGetPlatforms = "SELECT MAPPING.ID, PLATFORM.IDENTIFIER FROM (SELECT * FROM APPM_PLATFORM "
+ "WHERE TENANT_ID=? OR IS_SHARED = 1) PLATFORM LEFT JOIN APPM_PLATFORM_TENANT_MAPPING "
+ "MAPPING ON PLATFORM.ID = MAPPING.PLATFORM_ID AND MAPPING.TENANT_ID = ?";
return super.getPlatforms(tenantId);
}
}

@ -1,40 +0,0 @@
/*
* Copyright (c) 2017, 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.application.mgt.core.dao.impl.platform;
/**
* SQL Queries specific to Platform.
*/
public class SQLQueries {
static String queryToGetSupertenantAndOwnPlatforms = "SELECT ID from APPM_PLATFORM where IDENTIFIER "
+ "= ? AND (TENANT_ID = ? OR (TENANT_ID = ? AND IS_SHARED = true))";
static String queryToGetPlatformId =
"SELECT ID FROM APPM_PLATFORM WHERE (TENANT_ID=? AND IDENTIFIER=?) OR (IS_SHARED = TRUE AND "
+ "IDENTIFIER=?)";
static String queryToGetPlatform =
"SELECT MAPPING.ID, PLATFORM.IDENTIFIER, PLATFORM.FILE_BASED, PLATFORM.ID, PLATFORM.NAME, PLATFORM"
+ ".DESCRIPTION, PLATFORM.ICON_NAME, PLATFORM.IS_SHARED, PLATFORM.IS_DEFAULT_TENANT_MAPPING FROM "
+ "(SELECT * FROM APPM_PLATFORM WHERE IDENTIFIER= ? AND (TENANT_ID=? OR IS_SHARED = TRUE)) "
+ "PLATFORM LEFT JOIN APPM_PLATFORM_TENANT_MAPPING MAPPING ON PLATFORM.ID = MAPPING.PLATFORM_ID "
+ "AND MAPPING.TENANT_ID = ?";
static String queryToGetPlatforms = "SELECT MAPPING.ID, PLATFORM.IDENTIFIER FROM (SELECT * FROM APPM_PLATFORM "
+ "WHERE TENANT_ID=? OR IS_SHARED = TRUE ) PLATFORM LEFT JOIN APPM_PLATFORM_TENANT_MAPPING "
+ "MAPPING ON PLATFORM.ID = MAPPING.PLATFORM_ID AND MAPPING.TENANT_ID = ?";
}

@ -1,101 +0,0 @@
/*
* Copyright (c) 2017, 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.application.mgt.core.deployer;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Platform represents an Application Platform such as Android, IOS, etc.
*/
@XmlRootElement(name = "Platform")
public class Platform {
private String id;
private String name;
private String description;
private String icon;
private boolean shared;
private boolean tenantMapping;
private List<Property> properties;
@XmlAttribute(name = "id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@XmlAttribute(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElement(name = "Property")
public List<Property> getProperties() {
return properties;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setProperties(List<Property> properties) {
this.properties = properties;
}
@XmlAttribute(name = "icon")
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
@XmlAttribute(name = "isShared")
public boolean isShared() {
return shared;
}
public void setShared(boolean shared) {
this.shared = shared;
}
@XmlAttribute(name = "tenantMapping")
public boolean isTenantMapping() {
return tenantMapping;
}
public void setTenantMapping(boolean tenantMapping) {
this.tenantMapping = tenantMapping;
}
}

@ -1,149 +0,0 @@
/*
* Copyright (c) 2017, 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.application.mgt.core.deployer;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.deployment.AbstractDeployer;
import org.apache.axis2.deployment.DeploymentException;
import org.apache.axis2.deployment.repository.util.DeploymentFileData;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.common.exception.PlatformManagementException;
import org.wso2.carbon.device.application.mgt.common.services.PlatformManager;
import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
import org.wso2.carbon.device.application.mgt.core.util.Constants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
/**
* PlatformDeployer is responsible for deploying platforms that are added in the filesystem.
* This will deploy the platforms that are added in <IOT_HOME>/repository/deployment/server/platforms directory.
*/
public class PlatformDeployer extends AbstractDeployer {
private static final Log log = LogFactory.getLog(PlatformDeployer.class);
@Override
public void init(ConfigurationContext configurationContext) {
File deployementDir = new File(
MultitenantUtils.getAxis2RepositoryPath(CarbonContext.getThreadLocalCarbonContext().
getTenantId()) + Constants.PLATFORMS_DEPLOYMENT_DIR_NAME);
if (!deployementDir.exists()) {
if (!deployementDir.mkdir()) {
log.warn("Unable to create the deployment dir at: " + deployementDir.getPath());
}
}
}
@Override
public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException {
File deploymentFile = new File(deploymentFileData.getAbsolutePath());
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Platform.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Platform platformConf = (Platform) unmarshaller.unmarshal(deploymentFile);
if (platformConf.getId().contentEquals(getPlatformID(deploymentFile.getName()))) {
org.wso2.carbon.device.application.mgt.common.Platform platform = convert(platformConf);
PlatformManager platformManager = DataHolder.getInstance().getPlatformManager();
int tenantID = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
org.wso2.carbon.device.application.mgt.common.Platform existingPlatform = platformManager
.getPlatform(tenantID, platform.getIdentifier());
if (existingPlatform != null && existingPlatform.isFileBased()) {
platformManager.update(tenantID, platformConf.getId(), platform);
log.info("Platform configuration : " + deploymentFile.getName() + " updated successfully");
} else {
platformManager.register(CarbonContext.getThreadLocalCarbonContext().getTenantId(), platform);
log.info("Platform configuration : " + deploymentFile.getName() + " deployed successfully");
}
} else {
log.error("Unable to deploy the platform - " + deploymentFile.getAbsolutePath()
+ "!. Platform config file name - " + deploymentFile.getName()
+ " should match with the 'id' provided within the platform configuration!");
}
} catch (JAXBException e) {
log.error("Platform configuration file - " + deploymentFile.getAbsolutePath() + " is invalid!", e);
} catch (PlatformManagementException e) {
log.error("Unable to deploy the platform - " + deploymentFile.getAbsolutePath(), e);
}
}
@Override
public void undeploy(String fileName) throws DeploymentException {
String platformId = getPlatformID(fileName);
try {
DataHolder.getInstance().getPlatformManager()
.unregister(CarbonContext.getThreadLocalCarbonContext().getTenantId(), platformId, true);
log.info("Platform configuration : " + fileName + " un-deployed successfully");
} catch (PlatformManagementException e) {
log.error("Error occurred while un-deploying the platform - " + fileName, e);
}
}
private static String getPlatformID(String deploymentFileName) {
if (deploymentFileName.contains(Constants.PLATFORM_DEPLOYMENT_EXT)) {
return deploymentFileName.substring(0, deploymentFileName.length() -
Constants.PLATFORM_DEPLOYMENT_EXT.length());
}
return deploymentFileName;
}
private org.wso2.carbon.device.application.mgt.common.Platform convert(Platform platformConfig) {
org.wso2.carbon.device.application.mgt.common.Platform platform =
new org.wso2.carbon.device.application.mgt.common.Platform();
platform.setIdentifier(platformConfig.getId());
platform.setName(platformConfig.getName());
platform.setDescription(platformConfig.getDescription());
platform.setIconName(platformConfig.getIcon());
platform.setFileBased(true);
platform.setShared(platformConfig.isShared());
platform.setDefaultTenantMapping(platformConfig.isTenantMapping());
platform.setEnabled(false);
List<org.wso2.carbon.device.application.mgt.common.Platform.Property> properties = new ArrayList<>();
if (platformConfig.getProperties() != null) {
for (Property propertyConfig : platformConfig.getProperties()) {
org.wso2.carbon.device.application.mgt.common.Platform.Property property =
new org.wso2.carbon.device.application.mgt.common.Platform.Property();
property.setName(propertyConfig.getName());
property.setDefaultValue(propertyConfig.getDefaultValue());
property.setOptional(propertyConfig.isOptional());
properties.add(property);
}
}
platform.setProperties(properties);
return platform;
}
@Override
public void setDirectory(String s) {
}
@Override
public void setExtension(String s) {
}
}

@ -20,13 +20,13 @@ package org.wso2.carbon.device.application.mgt.core.exception;
/**
* This exception will be thrown when there is an issue with Lifecycle related DAO operations.
*/
public class DAOException extends Exception {
public class LifeCycleManagementDAOException extends Exception {
public DAOException(String message) {
public LifeCycleManagementDAOException(String message) {
super(message);
}
public DAOException(String message, Throwable cause) {
public LifeCycleManagementDAOException(String message, Throwable cause) {
super(message, cause);
}
}

@ -1,34 +0,0 @@
/*
* Copyright (c) 2017, 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.application.mgt.core.exception;
import org.wso2.carbon.device.application.mgt.common.exception.PlatformManagementException;
/**
* Exception that will be thrown when there is a issue during Platform level DAO operations.
*/
public class PlatformManagementDAOException extends PlatformManagementException {
public PlatformManagementDAOException(String message, Throwable ex) {
super(message, ex);
}
public PlatformManagementDAOException(String message) {
super(message);
}
}

@ -22,32 +22,24 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.common.Application;
import org.wso2.carbon.device.application.mgt.common.ApplicationList;
import org.wso2.carbon.device.application.mgt.common.Category;
import org.wso2.carbon.device.application.mgt.common.Filter;
import org.wso2.carbon.device.application.mgt.common.Lifecycle;
import org.wso2.carbon.device.application.mgt.common.LifecycleState;
import org.wso2.carbon.device.application.mgt.common.LifecycleStateTransition;
import org.wso2.carbon.device.application.mgt.common.Platform;
import org.wso2.carbon.device.application.mgt.common.User;
import org.wso2.carbon.device.application.mgt.common.Visibility;
import org.wso2.carbon.device.application.mgt.common.*;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.application.mgt.core.dao.ApplicationDAO;
import org.wso2.carbon.device.application.mgt.core.dao.LifecycleDAO;
import org.wso2.carbon.device.application.mgt.core.dao.LifecycleStateDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.DAOFactory;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory;
import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException;
import org.wso2.carbon.device.application.mgt.core.exception.ValidationException;
import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
import org.wso2.carbon.device.application.mgt.core.util.HelperUtil;
import org.wso2.carbon.device.mgt.core.dao.*;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@ -57,293 +49,356 @@ import java.util.List;
public class ApplicationManagerImpl implements ApplicationManager {
private static final Log log = LogFactory.getLog(ApplicationManagerImpl.class);
private static final String CREATED = "CREATED";
private DeviceTypeDAO deviceTypeDAO;
private LifecycleDAO lifecycleDAO;
private LifecycleStateDAO lifecycleStateDAO;
private ApplicationDAO applicationDAO;
public ApplicationManagerImpl(){
initDataAccessObjects();
}
private void initDataAccessObjects() {
this.deviceTypeDAO = ApplicationManagementDAOFactory.getDeviceTypeDAO();
this.lifecycleDAO = ApplicationManagementDAOFactory.getLifecycleDAO();
this.lifecycleStateDAO = ApplicationManagementDAOFactory.getLifecycleStateDAO();
this.applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO();
}
@Override
public Application createApplication(Application application) throws ApplicationManagementException {
public Application createApplication(Application application)
throws ApplicationManagementException, DeviceManagementDAOException {
application.setUser(new User(PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(),
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true)));
if (log.isDebugEnabled()) {
log.debug("Create Application received for the tenant : " + application.getUser().getTenantId() + " From"
+ " the user : " + application.getUser().getUserName());
}
validateApplication(application);
application.setUuid(HelperUtil.generateApplicationUuid());
application.setCreatedAt(new Date());
application.setModifiedAt(new Date());
Platform platform = DataHolder.getInstance().getPlatformManager()
.getPlatform(application.getUser().getTenantId(), application.getPlatform().getIdentifier());
if (platform == null) {
throw new NotFoundException("Invalid platform is provided for the application " + application.getUuid());
}
application.setPlatform(platform);
Category category = DataHolder.getInstance().getCategoryManager()
.getCategory(application.getCategory().getName());
if (category == null) {
throw new NotFoundException("Invalid Category is provided for the application " + application.getUuid());
}
application.setCategory(category);
DeviceType deviceType;
try {
ConnectionManagerUtil.beginDBTransaction();
if (log.isDebugEnabled()) {
log.debug("Application creation pre-conditions are met and the platform mentioned by identifier "
+ platform.getIdentifier() + " is found");
int tenantId = application.getUser().getTenantId();
deviceType = this.deviceTypeDAO.getDeviceType(application.getType(), application.getUser().getTenantId());
if (deviceType == null){
log.error("Device type is not matched with application type");
return null;
}
LifecycleStateDAO lifecycleStateDAO = DAOFactory.getLifecycleStateDAO();
LifecycleState lifecycleState = lifecycleStateDAO.getLifeCycleStateByIdentifier(CREATED);
if (lifecycleState == null) {
application.setDevicetype(deviceType);
int appId = this.applicationDAO.createApplication(application, deviceType.getId());
if (appId != -1){
log.error("Application creation Failed");
ConnectionManagerUtil.rollbackDBTransaction();
}else{
if (!application.getTags().isEmpty()){
this.applicationDAO.addTags(application.getTags(), appId, tenantId);
}
if (application.getIsRestricted() == 1 && !application.getUnrestrictedRoles().isEmpty()){
this.applicationDAO.addUnrestrictedRoles(application.getUnrestrictedRoles(), appId, tenantId);
}else{
application.setIsRestricted(0);
}
ConnectionManagerUtil.commitDBTransaction();
throw new NotFoundException("Invalid lifecycle state.");
}
Lifecycle lifecycle = new Lifecycle();
lifecycle.setLifecycleState(lifecycleState);
lifecycle.setLifecycleStateModifiedAt(new Date());
lifecycle.setGetLifecycleStateModifiedBy(application.getUser().getUserName());
application.setCurrentLifecycle(lifecycle);
application = DAOFactory.getApplicationDAO().createApplication(application);
DataHolder.getInstance().getVisibilityManager().put(application.getId(), application.getVisibility());
ConnectionManagerUtil.commitDBTransaction();
return application;
} catch (ApplicationManagementException e) {
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while getting device type id of " + application.getType();
log.error(msg, e);
ConnectionManagerUtil.rollbackDBTransaction();
throw e;
} finally {
throw new DeviceManagementDAOException(msg, e);
} catch(ApplicationManagementException e){
String msg = "Error occurred while adding application";
log.error(msg, e);
ConnectionManagerUtil.rollbackDBTransaction();
throw new ApplicationManagementException(msg, e);
}finally {
ConnectionManagerUtil.closeDBConnection();
}
// validateApplication(application);
// application.setUuid(HelperUtil.generateApplicationUuid());
//// application.setCreatedAt(new Date());
//// application.setModifiedAt(new Date());
//
//// Category category = DataHolder.getInstance().getCategoryManager()
//// .getCategory(application.getCategory().getName());
//// if (category == null) {
//// throw new NotFoundException("Invalid Category is provided for the application " + application.getUuid());
//// }
//// application.setCategory(category);
// try {
// ConnectionManagerUtil.beginDBTransaction();
//// if (log.isDebugEnabled()) {
//// log.debug("Application creation pre-conditions are met and the platform mentioned by identifier "
//// + platform.getIdentifier() + " is found");
//// }
// LifecycleStateDAO lifecycleStateDAO = ApplicationManagementDAOFactory.getLifecycleStateDAO();
// LifecycleState lifecycleState = lifecycleStateDAO.getLifeCycleStateByIdentifier(CREATED);
//
// if (lifecycleState == null) {
// ConnectionManagerUtil.commitDBTransaction();
// throw new NotFoundException("Invalid lifecycle state.");
// }
//
// Lifecycle lifecycle = new Lifecycle();
// lifecycle.setCreatedAt(new Date());
// lifecycle.setCreatedBy(application.getUser().getUserName());
//
//
//// application.setCurrentLifecycle(lifecycle);
// application = ApplicationManagementDAOFactory.getApplicationDAO().createApplication(application);
//// DataHolder.getInstance().getVisibilityManager().put(application.getId(), application.getVisibility());
// ConnectionManagerUtil.commitDBTransaction();
// return application;
// } catch (ApplicationManagementException e) {
// ConnectionManagerUtil.rollbackDBTransaction();
// throw e;
// } finally {
// ConnectionManagerUtil.closeDBConnection();
// }
}
@Override
public Application editApplication(Application application) throws ApplicationManagementException {
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
if (application.getUuid() == null) {
throw new ValidationException("Application UUID cannot be empty");
}
if (!isApplicationOwnerOrAdmin(application.getUuid(), userName, tenantId)) {
throw new ApplicationManagementException(
"User " + userName + " does not have permissions to edit the " + "application with the UUID "
+ application.getUuid());
}
if (this.getApplication(application.getUuid()) != null) {
if (application.getPlatform() == null || application.getPlatform().getIdentifier() == null) {
throw new NotFoundException("Platform information not available with the application!");
}
Platform platform = DataHolder.getInstance().getPlatformManager()
.getPlatform(tenantId, application.getPlatform().getIdentifier());
if (platform == null) {
throw new NotFoundException(
"Platform specified by identifier " + application.getPlatform().getIdentifier()
+ " is not found. Please give a valid platform identifier.");
}
application.setPlatform(platform);
if (application.getCategory() != null) {
String applicationCategoryName = application.getCategory().getName();
if (applicationCategoryName == null || applicationCategoryName.isEmpty()) {
throw new ApplicationManagementException(
"Application category name cannot be null or " + "empty. Cannot edit the application.");
}
Category category = DataHolder.getInstance().getCategoryManager()
.getCategory(application.getCategory().getName());
if (category == null) {
throw new NotFoundException(
"Invalid Category is provided for the application " + application.getUuid() + ". "
+ "Cannot edit application");
}
application.setCategory(category);
}
try {
ConnectionManagerUtil.beginDBTransaction();
ApplicationDAO applicationDAO = DAOFactory.getApplicationDAO();
application.setModifiedAt(new Date());
Application modifiedApplication = applicationDAO.editApplication(application, tenantId);
Visibility visibility = DataHolder.getInstance().getVisibilityManager()
.put(application.getId(), application.getVisibility());
modifiedApplication.setVisibility(visibility);
ConnectionManagerUtil.commitDBTransaction();
return modifiedApplication;
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw e;
} finally {
ConnectionManagerUtil.closeDBConnection();
}
} else {
throw new NotFoundException("No applications found with application UUID - " + application.getUuid());
}
// String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
// int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
// if (application.getUuid() == null) {
// throw new ValidationException("Application UUID cannot be empty");
// }
//
// if (!isApplicationOwnerOrAdmin(application.getUuid(), userName, tenantId)) {
// throw new ApplicationManagementException(
// "User " + userName + " does not have permissions to edit the " + "application with the UUID "
// + application.getUuid());
// }
// if (this.getApplication(application.getUuid()) != null) {
// if (application.getPlatform() == null || application.getPlatform().getIdentifier() == null) {
// throw new NotFoundException("Platform information not available with the application!");
// }
// Platform platform = DataHolder.getInstance().getPlatformManager()
// .getPlatform(tenantId, application.getPlatform().getIdentifier());
// if (platform == null) {
// throw new NotFoundException(
// "Platform specified by identifier " + application.getPlatform().getIdentifier()
// + " is not found. Please give a valid platform identifier.");
// }
// application.setPlatform(platform);
// if (application.getCategory() != null) {
// String applicationCategoryName = application.getCategory().getName();
// if (applicationCategoryName == null || applicationCategoryName.isEmpty()) {
// throw new ApplicationManagementException(
// "Application category name cannot be null or " + "empty. Cannot edit the application.");
// }
// Category category = DataHolder.getInstance().getCategoryManager()
// .getCategory(application.getCategory().getName());
// if (category == null) {
// throw new NotFoundException(
// "Invalid Category is provided for the application " + application.getUuid() + ". "
// + "Cannot edit application");
// }
// application.setCategory(category);
// }
// try {
// ConnectionManagerUtil.beginDBTransaction();
// ApplicationDAO applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO();
// application.setModifiedAt(new Date());
// Application modifiedApplication = applicationDAO.editApplication(application, tenantId);
// Visibility visibility = DataHolder.getInstance().getVisibilityManager()
// .put(application.getId(), application.getVisibility());
// modifiedApplication.setVisibility(visibility);
// ConnectionManagerUtil.commitDBTransaction();
// return modifiedApplication;
// } catch (ApplicationManagementDAOException e) {
// ConnectionManagerUtil.rollbackDBTransaction();
// throw e;
// } finally {
// ConnectionManagerUtil.closeDBConnection();
// }
// } else {
// throw new NotFoundException("No applications found with application UUID - " + application.getUuid());
// }
return application;
}
@Override
public void deleteApplication(String uuid) throws ApplicationManagementException {
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
if (!isApplicationOwnerOrAdmin(uuid, userName, tenantId)) {
throw new ApplicationManagementException("User '" + userName + "' of tenant - " + tenantId + " does have"
+ " the permission to delete the application with UUID " + uuid);
}
try {
ApplicationDAO applicationDAO = DAOFactory.getApplicationDAO();
ConnectionManagerUtil.beginDBTransaction();
int appId = applicationDAO.getApplicationId(uuid, tenantId);
if (appId != -1) {
applicationDAO.deleteTags(appId);
applicationDAO.deleteProperties(appId);
DataHolder.getInstance().getVisibilityManager().remove(appId);
applicationDAO.deleteApplication(uuid, tenantId);
}
ConnectionManagerUtil.commitDBTransaction();
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Failed to delete application: " + uuid;
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
// String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
// int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
// if (!isApplicationOwnerOrAdmin(uuid, userName, tenantId)) {
// throw new ApplicationManagementException("User '" + userName + "' of tenant - " + tenantId + " does have"
// + " the permission to delete the application with UUID " + uuid);
// }
// try {
// ApplicationDAO applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO();
// ConnectionManagerUtil.beginDBTransaction();
// int appId = applicationDAO.getApplicationId(uuid, tenantId);
// if (appId != -1) {
// applicationDAO.deleteTags(appId);
// applicationDAO.deleteProperties(appId);
// DataHolder.getInstance().getVisibilityManager().remove(appId);
// applicationDAO.deleteApplication(uuid, tenantId);
// }
// ConnectionManagerUtil.commitDBTransaction();
// } catch (ApplicationManagementDAOException e) {
// ConnectionManagerUtil.rollbackDBTransaction();
// String msg = "Failed to delete application: " + uuid;
// throw new ApplicationManagementException(msg, e);
// } finally {
// ConnectionManagerUtil.closeDBConnection();
// }
}
@Override
public ApplicationList getApplications(Filter filter) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
try {
if (isAuthorized(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
userName = "ALL";
}
} catch (UserStoreException e) {
throw new ApplicationManagementException("User-store exception while checking whether the user " +
userName + " of tenant " + tenantId + " has the publisher permission");
}
filter.setUserName(userName);
try {
ConnectionManagerUtil.openDBConnection();
ApplicationDAO applicationDAO = DAOFactory.getApplicationDAO();
ApplicationList applicationList = applicationDAO.getApplications(filter, tenantId);
for (Application application : applicationList.getApplications()) {
application.setVisibility(DataHolder.getInstance().getVisibilityManager().get(application.getId()));
}
return applicationList;
} finally {
ConnectionManagerUtil.closeDBConnection();
}
// int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
// String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
//
// try {
// if (isAuthorized(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
// userName = "ALL";
// }
// } catch (UserStoreException e) {
// throw new ApplicationManagementException("User-store exception while checking whether the user " +
// userName + " of tenant " + tenantId + " has the publisher permission");
// }
// filter.setUserName(userName);
//
// try {
// ConnectionManagerUtil.openDBConnection();
// ApplicationDAO applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO();
// ApplicationList applicationList = applicationDAO.getApplications(filter, tenantId);
// for (Application application : applicationList.getApplications()) {
// application.setVisibility(DataHolder.getInstance().getVisibilityManager().get(application.getId()));
// }
// return applicationList;
// } finally {
// ConnectionManagerUtil.closeDBConnection();
// }
}
@Override
public void changeLifecycle(String applicationUuid, String lifecycleIdentifier) throws
ApplicationManagementException {
boolean isAvailableNextState = false;
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
List<LifecycleStateTransition> nextLifeCycles = getLifeCycleStates(applicationUuid);
for (LifecycleStateTransition lifecycleStateTransition : nextLifeCycles) {
if (log.isDebugEnabled()) {
log.debug("Lifecycle state of the application " + applicationUuid + " can be changed to"
+ lifecycleStateTransition.getNextState());
}
if (lifecycleStateTransition.getNextState().equalsIgnoreCase(lifecycleIdentifier)) {
isAvailableNextState = true;
break;
}
}
if (!isAvailableNextState) {
throw new ApplicationManagementException("User " + userName + " does not have the permission to change "
+ "the lifecycle state of the application " + applicationUuid + " to lifecycle state "
+ lifecycleIdentifier);
}
try {
ConnectionManagerUtil.beginDBTransaction();
ApplicationDAO applicationDAO = DAOFactory.getApplicationDAO();
applicationDAO.changeLifecycle(applicationUuid, lifecycleIdentifier, userName, tenantId);
ConnectionManagerUtil.commitDBTransaction();
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw e;
} finally {
ConnectionManagerUtil.closeDBConnection();
}
// boolean isAvailableNextState = false;
// String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
// int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
// List<LifecycleStateTransition> nextLifeCycles = getLifeCycleStates(applicationUuid);
//
// for (LifecycleStateTransition lifecycleStateTransition : nextLifeCycles) {
// if (log.isDebugEnabled()) {
// log.debug("Lifecycle state of the application " + applicationUuid + " can be changed to"
// + lifecycleStateTransition.getNextState());
// }
// if (lifecycleStateTransition.getNextState().equalsIgnoreCase(lifecycleIdentifier)) {
// isAvailableNextState = true;
// break;
// }
// }
// if (!isAvailableNextState) {
// throw new ApplicationManagementException("User " + userName + " does not have the permission to change "
// + "the lifecycle state of the application " + applicationUuid + " to lifecycle state "
// + lifecycleIdentifier);
// }
// try {
// ConnectionManagerUtil.beginDBTransaction();
// ApplicationDAO applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO();
// applicationDAO.changeLifecycle(applicationUuid, lifecycleIdentifier, userName, tenantId);
// ConnectionManagerUtil.commitDBTransaction();
// } catch (ApplicationManagementDAOException e) {
// ConnectionManagerUtil.rollbackDBTransaction();
// throw e;
// } finally {
// ConnectionManagerUtil.closeDBConnection();
// }
}
@Override
public List<LifecycleStateTransition> getLifeCycleStates(String applicationUUID)
throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
boolean isAdminOrApplicationOwner = isApplicationOwnerOrAdmin(applicationUUID, userName, tenantId);
if (log.isDebugEnabled()) {
log.debug("User " + userName + " in tenant " + tenantId + " is an Admin or Application owner of the "
+ "application " + applicationUUID);
}
try {
ConnectionManagerUtil.openDBConnection();
List<LifecycleStateTransition> transitions = DAOFactory.getApplicationDAO()
.getNextLifeCycleStates(applicationUUID, tenantId);
List<LifecycleStateTransition> filteredTransitions = new ArrayList<>();
if (log.isDebugEnabled()) {
log.debug("Lifecycle of the application with UUID : " + applicationUUID + " can be changed to "
+ transitions.size() + ". The number may vary according to the permission level of user : "
+ userName + " of tenant " + tenantId);
}
for (LifecycleStateTransition transition : transitions) {
String permission = transition.getPermission();
if (permission != null) {
if (log.isDebugEnabled()) {
log.debug("In order to make the state change to " + transition.getNextState() + " permission "
+ permission + " is required");
}
if (isAuthorized(userName, tenantId, permission)) {
filteredTransitions.add(transition);
} else {
if (log.isDebugEnabled()) {
log.debug("User " + userName + " does not have the permission " + permission + " to "
+ "change the life-cycle state to " + transition.getNextState() + " of the "
+ "application " + applicationUUID);
}
}
} else if (isAdminOrApplicationOwner) {
filteredTransitions.add(transition);
}
}
if (log.isDebugEnabled()) {
log.debug("User " + userName + " can do " + filteredTransitions.size() + " life-cyle state changes "
+ "currently on application with the UUID " + applicationUUID);
}
return filteredTransitions;
} catch (UserStoreException e) {
throw new ApplicationManagementException(
"Userstore exception while checking whether user " + userName + " from tenant " + tenantId
+ " is authorized to do a life-cycle status change in an application ", e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
// int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
// String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
// boolean isAdminOrApplicationOwner = isApplicationOwnerOrAdmin(applicationUUID, userName, tenantId);
//
// if (log.isDebugEnabled()) {
// log.debug("User " + userName + " in tenant " + tenantId + " is an Admin or Application owner of the "
// + "application " + applicationUUID);
// }
// try {
// ConnectionManagerUtil.openDBConnection();
// List<LifecycleStateTransition> transitions = ApplicationManagementDAOFactory.getApplicationDAO()
// .getNextLifeCycleStates(applicationUUID, tenantId);
// List<LifecycleStateTransition> filteredTransitions = new ArrayList<>();
//
// if (log.isDebugEnabled()) {
// log.debug("Lifecycle of the application with UUID : " + applicationUUID + " can be changed to "
// + transitions.size() + ". The number may vary according to the permission level of user : "
// + userName + " of tenant " + tenantId);
// }
// for (LifecycleStateTransition transition : transitions) {
// String permission = transition.getPermission();
// if (permission != null) {
// if (log.isDebugEnabled()) {
// log.debug("In order to make the state change to " + transition.getNextState() + " permission "
// + permission + " is required");
// }
// if (isAuthorized(userName, tenantId, permission)) {
// filteredTransitions.add(transition);
// } else {
// if (log.isDebugEnabled()) {
// log.debug("User " + userName + " does not have the permission " + permission + " to "
// + "change the life-cycle state to " + transition.getNextState() + " of the "
// + "application " + applicationUUID);
// }
// }
// } else if (isAdminOrApplicationOwner) {
// filteredTransitions.add(transition);
// }
// }
// if (log.isDebugEnabled()) {
// log.debug("User " + userName + " can do " + filteredTransitions.size() + " life-cyle state changes "
// + "currently on application with the UUID " + applicationUUID);
// }
// return filteredTransitions;
// } catch (UserStoreException e) {
// throw new ApplicationManagementException(
// "Userstore exception while checking whether user " + userName + " from tenant " + tenantId
// + " is authorized to do a life-cycle status change in an application ", e);
// } finally {
// ConnectionManagerUtil.closeDBConnection();
// }
}
@Override
public Application getApplication(String uuid) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
try {
if (isAuthorized(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
userName = "ALL";
}
} catch (UserStoreException e) {
throw new ApplicationManagementException(
"User-store exception while getting application with the UUID " + uuid);
}
try {
ConnectionManagerUtil.openDBConnection();
Application application = DAOFactory.getApplicationDAO().getApplication(uuid, tenantId, userName);
if (application != null) {
application.setVisibility(DataHolder.getInstance().getVisibilityManager().get(application.getId()));
}
return application;
} finally {
ConnectionManagerUtil.closeDBConnection();
}
// int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
// String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
//
// try {
// if (isAuthorized(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
// userName = "ALL";
// }
// } catch (UserStoreException e) {
// throw new ApplicationManagementException(
// "User-store exception while getting application with the UUID " + uuid);
// }
// try {
// ConnectionManagerUtil.openDBConnection();
// Application application = ApplicationManagementDAOFactory.getApplicationDAO().getApplication(uuid, tenantId, userName);
// if (application != null) {
// application.setVisibility(DataHolder.getInstance().getVisibilityManager().get(application.getId()));
// }
// return application;
// } finally {
// ConnectionManagerUtil.closeDBConnection();
// }
}
/**
@ -355,22 +410,22 @@ public class ApplicationManagerImpl implements ApplicationManager {
*/
private boolean isApplicationOwnerOrAdmin(String applicationUUID, String userName, int tenantId)
throws ApplicationManagementException {
try {
if (isAuthorized(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
return true;
}
} catch (UserStoreException e) {
throw new ApplicationManagementException("Userstore exception while checking whether user is an admin", e);
}
try {
ConnectionManagerUtil.openDBConnection();
Application application = DAOFactory.getApplicationDAO()
.getApplication(applicationUUID, tenantId, userName);
return application.getUser().getUserName().equals(userName)
&& application.getUser().getTenantId() == tenantId;
} finally {
ConnectionManagerUtil.closeDBConnection();
}
// try {
// if (isAuthorized(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
// return true;
// }
// } catch (UserStoreException e) {
// throw new ApplicationManagementException("Userstore exception while checking whether user is an admin", e);
// }
// try {
// ConnectionManagerUtil.openDBConnection();
// Application application = ApplicationManagementDAOFactory.getApplicationDAO()
// .getApplication(applicationUUID, tenantId, userName);
// return application.getUser().getUserName().equals(userName)
// && application.getUser().getTenantId() == tenantId;
// } finally {
// ConnectionManagerUtil.closeDBConnection();
// }
}
/**
@ -400,19 +455,12 @@ public class ApplicationManagerImpl implements ApplicationManager {
if (application.getName() == null) {
throw new ValidationException("Application name cannot be empty");
}
if (application.getUser() == null || application.getUser().getUserName() == null ||
application.getUser().getTenantId() == 0) {
throw new ValidationException("Username and tenant Id cannot be empty");
}
if (application.getCategory() == null || application.getCategory().getName() == null || application
.getCategory().getName().isEmpty()) {
throw new ValidationException("Category name cannot be empty");
}
if (application.getPlatform() == null || application.getPlatform().getIdentifier() == null) {
throw new ValidationException("Platform identifier cannot be empty");
if (application.getAppCategory() == null) {
throw new ValidationException("Username and tenant Id cannot be empty");
}
try {
validateApplicationExistence(application);

@ -25,7 +25,7 @@ import org.wso2.carbon.device.application.mgt.common.Application;
import org.wso2.carbon.device.application.mgt.common.ApplicationRelease;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationReleaseManager;
import org.wso2.carbon.device.application.mgt.core.dao.common.DAOFactory;
import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException;
import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
@ -52,7 +52,7 @@ public class ApplicationReleaseManagerImpl implements ApplicationReleaseManager
try {
ConnectionManagerUtil.beginDBTransaction();
applicationRelease.setApplication(application);
applicationRelease = DAOFactory.getApplicationReleaseDAO().createRelease(applicationRelease);
applicationRelease = ApplicationManagementDAOFactory.getApplicationReleaseDAO().createRelease(applicationRelease);
ConnectionManagerUtil.commitDBTransaction();
return applicationRelease;
} catch (ApplicationManagementDAOException e) {
@ -74,7 +74,8 @@ public class ApplicationReleaseManagerImpl implements ApplicationReleaseManager
}
try {
ConnectionManagerUtil.openDBConnection();
return DAOFactory.getApplicationReleaseDAO().getRelease(applicationUuid, version, tenantId);
return ApplicationManagementDAOFactory
.getApplicationReleaseDAO().getRelease(applicationUuid, version, tenantId);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
@ -90,7 +91,8 @@ public class ApplicationReleaseManagerImpl implements ApplicationReleaseManager
}
try {
ConnectionManagerUtil.openDBConnection();
return DAOFactory.getApplicationReleaseDAO().getApplicationReleases(applicationUuid, tenantId);
return ApplicationManagementDAOFactory
.getApplicationReleaseDAO().getApplicationReleases(applicationUuid, tenantId);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
@ -108,7 +110,7 @@ public class ApplicationReleaseManagerImpl implements ApplicationReleaseManager
try {
ConnectionManagerUtil.beginDBTransaction();
DAOFactory.getApplicationReleaseDAO()
ApplicationManagementDAOFactory.getApplicationReleaseDAO()
.changeReleaseDefault(uuid, version, isDefault, releaseChannel, tenantId);
ConnectionManagerUtil.commitDBTransaction();
} catch (ApplicationManagementDAOException e) {
@ -122,33 +124,33 @@ public class ApplicationReleaseManagerImpl implements ApplicationReleaseManager
@Override
public ApplicationRelease updateRelease(String applicationUuid, ApplicationRelease applicationRelease)
throws ApplicationManagementException {
Application application = validateApplication(applicationUuid);
ApplicationRelease oldApplicationRelease = null;
if (applicationRelease == null || applicationRelease.getVersionName() != null) {
throw new ApplicationManagementException(
"Version is important to update the release of the application " + "with application UUID "
+ applicationUuid);
}
oldApplicationRelease = getRelease(applicationUuid, applicationRelease.getVersionName());
if (oldApplicationRelease == null) {
throw new ApplicationManagementException(
"Application release for the application " + applicationUuid + " with version " + applicationRelease
.getVersionName() + " does not exist. Cannot update the "
+ "release that is not existing.");
}
applicationRelease.setApplication(application);
try {
ConnectionManagerUtil.beginDBTransaction();
ApplicationRelease newApplicationRelease = DAOFactory.getApplicationReleaseDAO()
.updateRelease(applicationRelease);
ConnectionManagerUtil.commitDBTransaction();
return newApplicationRelease;
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw e;
} finally {
ConnectionManagerUtil.closeDBConnection();
}
// Application application = validateApplication(applicationUuid);
// ApplicationRelease oldApplicationRelease = null;
// if (applicationRelease == null || applicationRelease.getVersion() != null) {
// throw new ApplicationManagementException(
// "Version is important to update the release of the application " + "with application UUID "
// + applicationUuid);
// }
// oldApplicationRelease = getRelease(applicationUuid, applicationRelease.getVersion());
// if (oldApplicationRelease == null) {
// throw new ApplicationManagementException(
// "Application release for the application " + applicationUuid + " with version " + applicationRelease
// .getVersion() + " does not exist. Cannot update the "
// + "release that is not existing.");
// }
// applicationRelease.setApplication(application);
// try {
// ConnectionManagerUtil.beginDBTransaction();
// ApplicationRelease newApplicationRelease = ApplicationManagementDAOFactory.getApplicationReleaseDAO()
// .updateRelease(applicationRelease);
// ConnectionManagerUtil.commitDBTransaction();
// return newApplicationRelease;
// } catch (ApplicationManagementDAOException e) {
// ConnectionManagerUtil.rollbackDBTransaction();
// throw e;
// } finally {
// ConnectionManagerUtil.closeDBConnection();
// }
}
@Override
@ -163,8 +165,8 @@ public class ApplicationReleaseManagerImpl implements ApplicationReleaseManager
}
try {
ConnectionManagerUtil.beginDBTransaction();
DAOFactory.getApplicationReleaseDAO().deleteRelease(application.getId(), version);
DAOFactory.getApplicationReleaseDAO().deleteReleaseProperties(applicationRelease.getId());
ApplicationManagementDAOFactory.getApplicationReleaseDAO().deleteRelease(application.getId(), version);
ApplicationManagementDAOFactory.getApplicationReleaseDAO().deleteReleaseProperties(applicationRelease.getId());
ConnectionManagerUtil.commitDBTransaction();
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
@ -179,7 +181,7 @@ public class ApplicationReleaseManagerImpl implements ApplicationReleaseManager
List<ApplicationRelease> applicationReleases = getReleases(applicationUuid);
for (ApplicationRelease applicationRelease : applicationReleases) {
deleteApplicationRelease(applicationUuid, applicationRelease.getVersionName());
deleteApplicationRelease(applicationUuid, applicationRelease.getVersion());
}
}
@ -211,14 +213,14 @@ public class ApplicationReleaseManagerImpl implements ApplicationReleaseManager
*/
private void validateReleaseCreateRequest(String applicationUuid, ApplicationRelease applicationRelease)
throws ApplicationManagementException {
if (applicationRelease == null || applicationRelease.getVersionName() == null) {
if (applicationRelease == null || applicationRelease.getVersion() == null) {
throw new ApplicationManagementException("ApplicationRelease version name is a mandatory parameter for "
+ "creating release. It cannot be found.");
}
if (getRelease(applicationUuid, applicationRelease.getVersionName()) != null) {
if (getRelease(applicationUuid, applicationRelease.getVersion()) != null) {
throw new ApplicationManagementException(
"Application Release for the Application UUID " + applicationUuid + " " + "with the version "
+ applicationRelease.getVersionName() + " already exists. Cannot create an "
+ applicationRelease.getVersion() + " already exists. Cannot create an "
+ "application release with the same version.");
}
}

@ -21,20 +21,14 @@ package org.wso2.carbon.device.application.mgt.core.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.common.Application;
import org.wso2.carbon.device.application.mgt.common.ApplicationRelease;
import org.wso2.carbon.device.application.mgt.common.ImageArtifact;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationStorageManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.TransactionManagementException;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager;
import org.wso2.carbon.device.application.mgt.core.dao.common.DAOFactory;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
import org.wso2.carbon.device.application.mgt.core.util.Constants;
import org.wso2.carbon.device.application.mgt.core.util.StorageManagementUtil;
@ -70,86 +64,86 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
@Override
public void uploadImageArtifacts(String applicationUUID, InputStream iconFileStream, InputStream bannerFileStream,
List<InputStream> screenShotStreams) throws ResourceManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
Application application = validateApplication(applicationUUID);
String artifactDirectoryPath = storagePath + application.getId();
if (log.isDebugEnabled()) {
log.debug("Artifact Directory Path for saving the artifacts related with application " + applicationUUID
+ " is " + artifactDirectoryPath);
}
StorageManagementUtil.createArtifactDirectory(artifactDirectoryPath);
if (iconFileStream != null) {
try {
saveFile(iconFileStream, artifactDirectoryPath + File.separator + Constants.IMAGE_ARTIFACTS[0]);
} catch (IOException e) {
throw new ApplicationStorageManagementException(
"IO Exception while saving the icon file in the server for " + "the application "
+ applicationUUID, e);
}
}
if (bannerFileStream != null) {
try {
saveFile(bannerFileStream, artifactDirectoryPath + File.separator + Constants.IMAGE_ARTIFACTS[1]);
} catch (IOException e) {
throw new ApplicationStorageManagementException(
"IO Exception while saving the banner file in the server for" + " the application "
+ applicationUUID, e);
}
}
if (screenShotStreams != null) {
int count = application.getScreenShotCount() + 1;
boolean maxCountReached = false;
if (count > screenShotMaxCount) {
log.error("Maximum limit for the screen-shot is " + screenShotMaxCount
+ " Cannot upload another screenshot for the application with the UUID " + applicationUUID);
maxCountReached = true;
}
String screenshotName;
if (maxCountReached) {
return;
}
for (InputStream screenshotStream : screenShotStreams) {
try {
screenshotName = Constants.IMAGE_ARTIFACTS[2] + count;
saveFile(screenshotStream, artifactDirectoryPath + File.separator + screenshotName);
count++;
if (count > screenShotMaxCount) {
log.error("Maximum limit for the screen-shot is " + screenShotMaxCount
+ " Cannot upload another screenshot for the application with the UUID "
+ applicationUUID);
break;
}
} catch (IOException e) {
throw new ApplicationStorageManagementException(
"IO Exception while saving the screens hots for the " + "application " + applicationUUID,
e);
}
}
try {
ConnectionManagerUtil.beginDBTransaction();
DAOFactory.getApplicationDAO().updateScreenShotCount(applicationUUID, tenantId, count - 1);
ConnectionManagerUtil.commitDBTransaction();
} catch (TransactionManagementException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new ApplicationStorageManagementException("Transaction Management exception while trying to "
+ "update the screen-shot count of the application " + applicationUUID + " for the tenant "
+ tenantId, e);
} catch (DBConnectionException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new ApplicationStorageManagementException("Database connection management exception while "
+ "trying to update the screen-shot count for the application " + applicationUUID + " for the"
+ " tenant " + tenantId, e);
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new ApplicationStorageManagementException("Application Management DAO exception while trying to"
+ " update the screen-shot count for the application " + applicationUUID + " for the tenant "
+ tenantId, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
// int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
// Application application = validateApplication(applicationUUID);
// String artifactDirectoryPath = storagePath + application.getId();
// if (log.isDebugEnabled()) {
// log.debug("Artifact Directory Path for saving the artifacts related with application " + applicationUUID
// + " is " + artifactDirectoryPath);
// }
// StorageManagementUtil.createArtifactDirectory(artifactDirectoryPath);
// if (iconFileStream != null) {
// try {
// saveFile(iconFileStream, artifactDirectoryPath + File.separator + Constants.IMAGE_ARTIFACTS[0]);
// } catch (IOException e) {
// throw new ApplicationStorageManagementException(
// "IO Exception while saving the icon file in the server for " + "the application "
// + applicationUUID, e);
// }
// }
// if (bannerFileStream != null) {
// try {
// saveFile(bannerFileStream, artifactDirectoryPath + File.separator + Constants.IMAGE_ARTIFACTS[1]);
// } catch (IOException e) {
// throw new ApplicationStorageManagementException(
// "IO Exception while saving the banner file in the server for" + " the application "
// + applicationUUID, e);
// }
// }
// if (screenShotStreams != null) {
// int count = application.getScreenShotCount() + 1;
// boolean maxCountReached = false;
//
// if (count > screenShotMaxCount) {
// log.error("Maximum limit for the screen-shot is " + screenShotMaxCount
// + " Cannot upload another screenshot for the application with the UUID " + applicationUUID);
// maxCountReached = true;
// }
// String screenshotName;
//
// if (maxCountReached) {
// return;
// }
// for (InputStream screenshotStream : screenShotStreams) {
// try {
// screenshotName = Constants.IMAGE_ARTIFACTS[2] + count;
// saveFile(screenshotStream, artifactDirectoryPath + File.separator + screenshotName);
// count++;
// if (count > screenShotMaxCount) {
// log.error("Maximum limit for the screen-shot is " + screenShotMaxCount
// + " Cannot upload another screenshot for the application with the UUID "
// + applicationUUID);
// break;
// }
// } catch (IOException e) {
// throw new ApplicationStorageManagementException(
// "IO Exception while saving the screens hots for the " + "application " + applicationUUID,
// e);
// }
// }
// try {
// ConnectionManagerUtil.beginDBTransaction();
// ApplicationManagementDAOFactory.getApplicationDAO().updateScreenShotCount(applicationUUID, tenantId, count - 1);
// ConnectionManagerUtil.commitDBTransaction();
// } catch (TransactionManagementException e) {
// ConnectionManagerUtil.rollbackDBTransaction();
// throw new ApplicationStorageManagementException("Transaction Management exception while trying to "
// + "update the screen-shot count of the application " + applicationUUID + " for the tenant "
// + tenantId, e);
// } catch (DBConnectionException e) {
// ConnectionManagerUtil.rollbackDBTransaction();
// throw new ApplicationStorageManagementException("Database connection management exception while "
// + "trying to update the screen-shot count for the application " + applicationUUID + " for the"
// + " tenant " + tenantId, e);
// } catch (ApplicationManagementDAOException e) {
// ConnectionManagerUtil.rollbackDBTransaction();
// throw new ApplicationStorageManagementException("Application Management DAO exception while trying to"
// + " update the screen-shot count for the application " + applicationUUID + " for the tenant "
// + tenantId, e);
// } finally {
// ConnectionManagerUtil.closeDBConnection();
// }
// }
}
@Override
@ -228,7 +222,7 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
List<ApplicationRelease> applicationReleases = DataHolder.getInstance().getReleaseManager()
.getReleases(applicationUUID);
for (ApplicationRelease applicationRelease : applicationReleases) {
deleteApplicationReleaseArtifacts(applicationUUID, applicationRelease.getVersionName());
deleteApplicationReleaseArtifacts(applicationUUID, applicationRelease.getVersion());
}
} catch (ApplicationManagementException e) {
throw new ApplicationStorageManagementException(

@ -1,110 +0,0 @@
/*
* Copyright (c) 2017, 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.application.mgt.core.impl;
import org.wso2.carbon.device.application.mgt.common.Category;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationCategoryManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.services.CategoryManager;
import org.wso2.carbon.device.application.mgt.core.dao.common.DAOFactory;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
import java.util.List;
/**
* This class is the default implementation for the CategoryManager.
*
*/
public class CategoryManagerImpl implements CategoryManager {
@Override
public Category createCategory(Category category) throws ApplicationManagementException {
if (category == null) {
throw new ApplicationCategoryManagementException("Category is null. Cannot create a category.");
}
if (category.getName() == null) {
throw new ApplicationCategoryManagementException(
"Application category name cannot be null. Application category creation failed.");
}
if (getCategory(category.getName()) != null) {
throw new ApplicationCategoryManagementException("Application category wth the name " + category.getName()
+ "exists already. Please select a different name");
}
try {
ConnectionManagerUtil.beginDBTransaction();
Category createdCategory = DAOFactory.getCategoryDAO().addCategory(category);
ConnectionManagerUtil.commitDBTransaction();
return createdCategory;
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw e;
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public List<Category> getCategories() throws ApplicationManagementException {
try {
ConnectionManagerUtil.openDBConnection();
return DAOFactory.getCategoryDAO().getCategories();
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public Category getCategory(String name) throws ApplicationManagementException {
if (name == null || name.isEmpty()) {
throw new ApplicationCategoryManagementException("Name cannot be empty or null. Cannot get category");
}
try {
ConnectionManagerUtil.openDBConnection();
return DAOFactory.getCategoryDAO().getCategory(name);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public void deleteCategory(String name) throws ApplicationManagementException {
Category category = getCategory(name);
if (category == null) {
throw new NotFoundException(
"Category with the name '" + name + "' not found. Cannot delete the " + "non-existing category");
}
try {
ConnectionManagerUtil.beginDBTransaction();
boolean isApplicationExistForCategory = DAOFactory.getApplicationDAO().isApplicationExist(name);
if (isApplicationExistForCategory) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new ApplicationCategoryManagementException(
"Cannot delete the the category " + name + ". Applications " + "exists for this category");
}
DAOFactory.getCategoryDAO().deleteCategory(name);
ConnectionManagerUtil.commitDBTransaction();
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw e;
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
}

@ -24,8 +24,8 @@ import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionExcep
import org.wso2.carbon.device.application.mgt.common.exception.LifecycleManagementException;
import org.wso2.carbon.device.application.mgt.common.services.LifecycleStateManager;
import org.wso2.carbon.device.application.mgt.core.dao.LifecycleStateDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.DAOFactory;
import org.wso2.carbon.device.application.mgt.core.exception.DAOException;
import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory;
import org.wso2.carbon.device.application.mgt.core.exception.LifeCycleManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
import java.util.List;
@ -42,9 +42,9 @@ public class LifecycleStateManagerImpl implements LifecycleStateManager {
List<LifecycleState> lifecycleStates = null;
try {
ConnectionManagerUtil.openDBConnection();
LifecycleStateDAO lifecycleStateDAO = DAOFactory.getLifecycleStateDAO();
LifecycleStateDAO lifecycleStateDAO = ApplicationManagementDAOFactory.getLifecycleStateDAO();
lifecycleStates = lifecycleStateDAO.getLifecycleStates();
} catch (DAOException | DBConnectionException e) {
} catch (LifeCycleManagementDAOException | DBConnectionException e) {
throw new LifecycleManagementException("Failed get lifecycle states.", e);
} finally {
ConnectionManagerUtil.closeDBConnection();
@ -56,9 +56,9 @@ public class LifecycleStateManagerImpl implements LifecycleStateManager {
public void addLifecycleState(LifecycleState state) throws LifecycleManagementException {
try {
ConnectionManagerUtil.openDBConnection();
LifecycleStateDAO lifecycleStateDAO = DAOFactory.getLifecycleStateDAO();
LifecycleStateDAO lifecycleStateDAO = ApplicationManagementDAOFactory.getLifecycleStateDAO();
lifecycleStateDAO.addLifecycleState(state);
} catch (DAOException | DBConnectionException e) {
} catch (LifeCycleManagementDAOException | DBConnectionException e) {
throw new LifecycleManagementException("Failed to add lifecycle state", e);
} finally {
ConnectionManagerUtil.closeDBConnection();
@ -70,9 +70,9 @@ public class LifecycleStateManagerImpl implements LifecycleStateManager {
try {
ConnectionManagerUtil.openDBConnection();
LifecycleStateDAO lifecycleStateDAO = DAOFactory.getLifecycleStateDAO();
LifecycleStateDAO lifecycleStateDAO = ApplicationManagementDAOFactory.getLifecycleStateDAO();
lifecycleStateDAO.deleteLifecycleState(identifier);
} catch (DAOException | DBConnectionException e) {
} catch (LifeCycleManagementDAOException | DBConnectionException e) {
throw new LifecycleManagementException("Failed to add lifecycle state: " + identifier, e);
} finally {
ConnectionManagerUtil.closeDBConnection();

@ -1,561 +0,0 @@
/*
* Copyright (c) 2017, 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.application.mgt.core.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.common.Platform;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.common.exception.PlatformManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.TransactionManagementException;
import org.wso2.carbon.device.application.mgt.common.services.PlatformManager;
import org.wso2.carbon.device.application.mgt.core.dao.common.DAOFactory;
import org.wso2.carbon.device.application.mgt.core.exception.PlatformManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
import org.wso2.carbon.user.api.Tenant;
import org.wso2.carbon.user.api.TenantManager;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Implementation of {@link PlatformManager}, which manages the CRUD operations on Application platforms.
*/
public class PlatformManagerImpl implements PlatformManager {
private Map<Integer, Map<String, Platform>> inMemoryStore;
private static Log log = LogFactory.getLog(PlatformManagerImpl.class);
public PlatformManagerImpl() {
this.inMemoryStore = new HashMap<>();
}
@Override
public void initialize(int tenantId) throws PlatformManagementException {
try {
ConnectionManagerUtil.beginDBTransaction();
List<Platform> platforms = DAOFactory.getPlatformDAO().getPlatforms(tenantId);
List<String> platformIdentifiers = new ArrayList<>();
for (Platform platform : platforms) {
if (!platform.isEnabled() & platform.isDefaultTenantMapping()) {
platformIdentifiers.add(platform.getIdentifier());
}
}
DAOFactory.getPlatformDAO().addMapping(tenantId, platformIdentifiers);
ConnectionManagerUtil.commitDBTransaction();
} catch (TransactionManagementException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new PlatformManagementDAOException(
"Transaction Management Exception while initializing the " + "platforms for the tenant : "
+ tenantId, e);
} catch (DBConnectionException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new PlatformManagementDAOException(
"Database Connection Exception while initializing the " + "platforms for the tenant : " + tenantId,
e);
} catch (PlatformManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw e;
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public List<Platform> getPlatforms(int tenantId) throws PlatformManagementException {
int platformIndex = 0;
List<Platform> platforms;
if (log.isDebugEnabled()) {
log.debug("Request for getting platforms received for the tenant ID " + tenantId + " at "
+ "PlatformManager level");
}
try {
ConnectionManagerUtil.openDBConnection();
platforms = DAOFactory.getPlatformDAO().getPlatforms(tenantId);
} catch (DBConnectionException e) {
throw new PlatformManagementDAOException(
"Database Connection Exception while getting the platforms for the tenant : " + tenantId, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
if (log.isDebugEnabled()) {
log.debug("Number of platforms received from DAO layer is " + platforms.size() + " for the tenant "
+ tenantId);
}
for (Platform platform : platforms) {
if (platform.isFileBased()) {
Map<String, Platform> superTenantPlatforms = this.inMemoryStore
.get(MultitenantConstants.SUPER_TENANT_ID);
Platform registeredPlatform = superTenantPlatforms.get(platform.getIdentifier());
if (registeredPlatform != null) {
platforms.set(platformIndex, new Platform(registeredPlatform));
if (log.isDebugEnabled()) {
log.debug("Platform Name - " + platform.getName() + ", IsRegistered - " + true);
}
} else {
platforms.remove(platformIndex);
if (log.isDebugEnabled()) {
log.debug("Platform Name - " + platform.getName() + ", IsRegistered - " + false);
}
}
}
platformIndex++;
}
if (log.isDebugEnabled()) {
log.debug("Number of effective platforms for the tenant " + tenantId + " : " + platforms.size());
}
return platforms;
}
@Override
public Platform getPlatform(int tenantId, String identifier) throws PlatformManagementException {
Platform platform = getPlatformFromInMemory(tenantId, identifier);
if (platform == null) {
try {
ConnectionManagerUtil.openDBConnection();
platform = DAOFactory.getPlatformDAO().getPlatform(tenantId, identifier);
if (platform != null) {
return platform;
}
} catch (DBConnectionException e) {
throw new PlatformManagementDAOException(
"Database Connection Exception while trying to get the " + "platform with the id :" + identifier
+ " for the tenant : " + tenantId, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
} else {
return new Platform(platform);
}
return null;
}
private Platform getPlatformFromInMemory(int tenantId, String identifier) {
Map<String, Platform> platformMap = this.inMemoryStore.get(tenantId);
if (platformMap != null) {
Platform platform = platformMap.get(identifier);
if (platform != null) {
return platform;
}
}
if (tenantId != MultitenantConstants.SUPER_TENANT_ID) {
platformMap = this.inMemoryStore.get(MultitenantConstants.SUPER_TENANT_ID);
if (platformMap != null) {
Platform platform = platformMap.get(identifier);
if (platform != null && platform.isShared()) {
return platform;
}
}
}
return null;
}
@Override
public synchronized void register(int tenantId, Platform platform) throws PlatformManagementException {
validateBeforeRegister(tenantId, platform);
try {
ConnectionManagerUtil.beginDBTransaction();
int platformId = DAOFactory.getPlatformDAO().register(tenantId, platform);
if (platform.isFileBased()) {
platform.setId(platformId);
Map<String, Platform> tenantPlatforms = this.inMemoryStore.get(tenantId);
if (tenantPlatforms == null) {
tenantPlatforms = new HashMap<>();
this.inMemoryStore.put(tenantId, tenantPlatforms);
}
if (tenantPlatforms.get(platform.getIdentifier()) == null) {
tenantPlatforms.put(platform.getIdentifier(), platform);
} else {
ConnectionManagerUtil.rollbackDBTransaction();
throw new PlatformManagementException(
"Platform - " + platform.getIdentifier() + " is already registered!");
}
}
if (platform.isDefaultTenantMapping()) {
try {
if (platform.isShared()) {
sharePlatformWithOtherTenants(platform.getIdentifier());
}
DAOFactory.getPlatformDAO().addMapping(tenantId, getListOfString(platform.getIdentifier()));
} catch (UserStoreException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new PlatformManagementException("Error occurred while assigning the platforms for tenants!",
e);
}
}
ConnectionManagerUtil.commitDBTransaction();
} catch (TransactionManagementException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new PlatformManagementDAOException(
"Transaction Management Exception while trying to register a " + "platform with id " + platform
.getIdentifier() + " for tenant " + tenantId);
} catch (DBConnectionException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new PlatformManagementDAOException(
"Database Connection Exception while trying to register a " + "platform with id " + platform
.getIdentifier() + " for tenant " + tenantId);
} catch (PlatformManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw e;
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public void update(int tenantId, String oldPlatformIdentifier, Platform platform) throws
PlatformManagementException {
Platform oldPlatform = validateBeforeUpdate(tenantId, oldPlatformIdentifier, platform);
try {
ConnectionManagerUtil.beginDBTransaction();
if (platform.isFileBased()) {
Map<String, Platform> tenantPlatforms = this.inMemoryStore.get(tenantId);
// File based configurations will be updated in the server start-up as well.So in that case, cache,
// will be empty.
if (tenantPlatforms != null) {
if (tenantPlatforms.get(oldPlatformIdentifier) == null) {
throw new PlatformManagementException(
"Cannot update platform with identifier " + oldPlatformIdentifier + " as it is not "
+ " existing already for the tenant " + tenantId);
}
} else {
tenantPlatforms = new HashMap<>();
this.inMemoryStore.put(tenantId, tenantPlatforms);
}
DAOFactory.getPlatformDAO().update(tenantId, oldPlatformIdentifier, platform);
platform.setId(oldPlatform.getId());
tenantPlatforms.put(platform.getIdentifier(), platform);
} else {
DAOFactory.getPlatformDAO().update(tenantId, oldPlatformIdentifier, platform);
}
try {
if (platform.isShared() && !oldPlatform.isShared()) {
sharePlatformWithOtherTenants(platform.getIdentifier());
}
} catch (UserStoreException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new PlatformManagementException("Error occurred while assigning the platforms for tenants!",
e);
}
if (!platform.isShared() && oldPlatform.isShared()) {
DAOFactory.getPlatformDAO().removeMappingTenants(platform.getIdentifier());
}
ConnectionManagerUtil.commitDBTransaction();
} catch (TransactionManagementException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new PlatformManagementDAOException(
"Transaction Management Exception while trying to update " + "platform : " + oldPlatformIdentifier
+ " of tenant :" + tenantId);
} catch (DBConnectionException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new PlatformManagementDAOException(
"Database Connection Exception while trying to update " + "platform : " + oldPlatformIdentifier
+ " of tenant :" + tenantId);
} catch (PlatformManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw e;
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public void unregister(int tenantId, String identifier, boolean isFileBased) throws PlatformManagementException {
try {
ConnectionManagerUtil.beginDBTransaction();
DAOFactory.getPlatformDAO().unregister(tenantId, identifier, isFileBased);
if (isFileBased) {
Map<String, Platform> tenantPlatforms = this.inMemoryStore.get(tenantId);
if (tenantPlatforms != null) {
tenantPlatforms.remove(identifier);
}
}
ConnectionManagerUtil.commitDBTransaction();
} catch (TransactionManagementException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new PlatformManagementDAOException(
"Transaction Management Exception while trying to un-register " + "the platform with identifier : "
+ identifier + " tenant :" + tenantId, e);
} catch (DBConnectionException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new PlatformManagementDAOException(
"Database Connection Exception while trying to un-register " + "the platform with identifier : "
+ identifier + " tenant :" + tenantId, e);
} catch (PlatformManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw e;
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public void addMapping(int tenantId, List<String> platformIdentifiers) throws PlatformManagementException {
try {
ConnectionManagerUtil.beginDBTransaction();
DAOFactory.getPlatformDAO().addMapping(tenantId, platformIdentifiers);
ConnectionManagerUtil.commitDBTransaction();
} catch (DBConnectionException | TransactionManagementException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new PlatformManagementDAOException(
"Database Connection Exception while trying to add tenant " + "mapping for tenant ID : "
+ tenantId);
} catch (PlatformManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw e;
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public void addMapping(int tenantId, String platformIdentifier) throws PlatformManagementException {
List<String> identifiers = new ArrayList<>();
identifiers.add(platformIdentifier);
addMapping(tenantId, identifiers);
}
@Override
public void removeMapping(int tenantId, String platformIdentifier) throws PlatformManagementException {
try {
ConnectionManagerUtil.beginDBTransaction();
DAOFactory.getPlatformDAO().removeMapping(tenantId, platformIdentifier);
ConnectionManagerUtil.commitDBTransaction();
} catch (DBConnectionException | TransactionManagementException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new PlatformManagementDAOException(
"Database Connection Exception while trying to remove tenant mapping for tenant ID : " + tenantId);
} catch (PlatformManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw e;
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public void updatePlatformStatus(int tenantId, String platformIdentifier, String status)
throws PlatformManagementException {
try {
ConnectionManagerUtil.beginDBTransaction();
Platform platform = DAOFactory.getPlatformDAO().getPlatform(tenantId, platformIdentifier);
if (platform == null) {
ConnectionManagerUtil.commitDBTransaction();
throw new PlatformManagementException("Platform with identifier : " + platformIdentifier + " does not"
+ " exist for the tenant with id " + tenantId);
} else {
boolean isEnabledNewStatus = status.equalsIgnoreCase("ENABLED");
// If the platform is already in the same status. No need to enable the platform again
if (isEnabledNewStatus == platform.isEnabled()) {
if (log.isDebugEnabled()) {
log.debug("Platform with identifier : " + platformIdentifier + " is already in " +
(isEnabledNewStatus ? "Enabled" : "Disabled") + " status. No need to update.");
}
ConnectionManagerUtil.commitDBTransaction();
return;
} else {
if (isEnabledNewStatus) {
DAOFactory.getPlatformDAO().addMapping(tenantId, getListOfString(platform.getIdentifier()));
} else {
DAOFactory.getPlatformDAO().removeMapping(tenantId, platform.getIdentifier());
}
if (log.isDebugEnabled()) {
log.debug("Platform with identifier : " + platformIdentifier + " successfully " +
(isEnabledNewStatus ? "Enabled" : "Disabled"));
}
}
}
ConnectionManagerUtil.commitDBTransaction();
} catch (TransactionManagementException | DBConnectionException ex) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new PlatformManagementDAOException("Database exception while trying to update the status of platform "
+ "with identifier '" + platformIdentifier + "' for the tenant" + tenantId);
} catch (PlatformManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw e;
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public void removePlatforms(int tenantId) throws PlatformManagementException {
try {
ConnectionManagerUtil.beginDBTransaction();
DAOFactory.getPlatformDAO().removePlatforms(tenantId);
ConnectionManagerUtil.commitDBTransaction();
} catch (TransactionManagementException | DBConnectionException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw new PlatformManagementDAOException("Database exception while trying to remove all the platforms for"
+ " the tenant " + tenantId);
} catch (PlatformManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
throw e;
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public List<String> getPlatformTags(String name) throws PlatformManagementException {
try {
ConnectionManagerUtil.openDBConnection();
return DAOFactory.getPlatformDAO().getPlatformTags(name);
} catch (DBConnectionException e) {
throw new PlatformManagementException("Database Connection Exception while getting the platform tags that"
+ " are starting with the character sequence " + name, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
/**
* To share the super-tenant platform with other tenants
* @param platformIdentifier Identifier of the platform
* @throws UserStoreException User Store Exception
* @throws PlatformManagementDAOException Platform Management DAO Exception
*/
private void sharePlatformWithOtherTenants(String platformIdentifier)
throws UserStoreException, PlatformManagementDAOException {
TenantManager tenantManager = DataHolder.getInstance().getRealmService().getTenantManager();
Tenant[] tenants = tenantManager.getAllTenants();
for (Tenant tenant : tenants) {
DAOFactory.getPlatformDAO()
.addMapping(tenant.getId(), getListOfString(platformIdentifier));
}
}
/**
* Validation need to be done before registering the platform
*
* @param tenantId ID of the tenant which the platform need to registered to
* @param platform Platform that need to be registered
* @throws PlatformManagementException Platform Management Exception
*/
private void validateBeforeRegister(int tenantId, Platform platform) throws PlatformManagementException {
validatePlatformSharing(tenantId, platform);
try {
ConnectionManagerUtil.openDBConnection();
int existingPlatformId = DAOFactory.getPlatformDAO()
.getSuperTenantAndOwnPlatforms(platform.getIdentifier(), tenantId);
if (existingPlatformId != -1) {
throw new PlatformManagementException(
"Another platform exists with the identifier " + platform.getIdentifier() + " in the tenant "
+ tenantId + " or super-tenant. Please choose a "
+ "different identifier for your platform");
}
} catch (DBConnectionException e) {
throw new PlatformManagementException(
"Error while checking pre-conditions before registering" + " platform identifier '" + platform
.getIdentifier() + "' for the tenant :" + tenantId);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
/**
* Validations that need to be done before updating the platform
*
* @param tenantId ID of the tenant
* @param oldPlatformIdentifier Identifier of the old platform
* @param platform Updated platform
* @return Old platform if all the validation succeeds
* @throws PlatformManagementException Platform ManagementException
*/
private Platform validateBeforeUpdate(int tenantId, String oldPlatformIdentifier, Platform platform) throws
PlatformManagementException {
validatePlatformSharing(tenantId, platform);
try {
ConnectionManagerUtil.openDBConnection();
Platform oldPlatform = DAOFactory.getPlatformDAO().getTenantOwnedPlatform(tenantId, oldPlatformIdentifier);
if (oldPlatform == null) {
throw new PlatformManagementException(
"Cannot update platform. Platform with identifier : " + oldPlatformIdentifier
+ " does not exist for the tenant : " + tenantId);
}
if (platform.getIdentifier() != null && !platform.getIdentifier().equals(oldPlatformIdentifier)) {
int existingPlatformID = DAOFactory.getPlatformDAO()
.getSuperTenantAndOwnPlatforms(platform.getIdentifier(), tenantId);
if (existingPlatformID == -1) {
throw new PlatformManagementException(
"Cannot update the identifier of the platform from '" + oldPlatformIdentifier + "' to '"
+ platform.getIdentifier() + "'. Another platform exists "
+ "already with the identifier '" + platform.getIdentifier() + "' for the tenant : "
+ tenantId + " or in super-tenant");
}
}
return oldPlatform;
} catch (DBConnectionException e) {
throw new PlatformManagementException(
"Database error while validating the platform update with the " + "platform identifier: "
+ oldPlatformIdentifier + " for the tenant :" + tenantId);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
/**
* To validate whether this platform can be shared or not before registering and updating the platform
*
* @param tenantId ID of the tenant
* @param platform Platform to be validated for sharing
*/
private void validatePlatformSharing(int tenantId, Platform platform) throws PlatformManagementException {
if (platform.isShared() && tenantId != MultitenantConstants.SUPER_TENANT_ID) {
throw new PlatformManagementException(
"Platform sharing is a restricted operation, therefore Platform - " + platform.getIdentifier()
+ " cannot be shared by the tenant domain - " + tenantId);
}
try {
ConnectionManagerUtil.openDBConnection();
if (platform.isShared()) {
int sharedPlatform = DAOFactory.getPlatformDAO().getMultiTenantPlatforms(platform.getIdentifier());
if (sharedPlatform != -1) {
throw new PlatformManagementException(
"Platform '" + platform.getIdentifier() + "' cannot be shared as some other tenants have "
+ "platforms with the same identifier.");
}
}
} catch (DBConnectionException e) {
throw new PlatformManagementException(
"Error while checking platform sharing conditions for " + " platform identifier '" + platform
.getIdentifier() + "' for the tenant :" + tenantId);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
/**
* To get the list of the given platform Identifier
* @param platformIdentifier Identifier of the Platform
* @return Platform Identifier as a list
*/
private List<String> getListOfString(String platformIdentifier) {
List<String> identifiers = new ArrayList<>();
identifiers.add(platformIdentifier);
return identifiers;
}
}

@ -1,167 +0,0 @@
/*
* Copyright (c) 2017, 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.application.mgt.core.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.common.ImageArtifact;
import org.wso2.carbon.device.application.mgt.common.Platform;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationStorageManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.PlatformManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.PlatformStorageManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException;
import org.wso2.carbon.device.application.mgt.common.services.PlatformManager;
import org.wso2.carbon.device.application.mgt.common.services.PlatformStorageManager;
import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
import org.wso2.carbon.device.application.mgt.core.util.Constants;
import org.wso2.carbon.device.application.mgt.core.util.StorageManagementUtil;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import static org.wso2.carbon.device.application.mgt.core.util.StorageManagementUtil.saveFile;
/**
* This is the concrete implementation of {@link PlatformStorageManager}
*/
public class PlatformStorageManagerImpl implements PlatformStorageManager {
private static final Log log = LogFactory.getLog(ApplicationStorageManagerImpl.class);
private String storagePath;
/**
* This creates a new instance of PlatformStorageManager.
* @param storagePath Storage path to store the artifacts related with platform.
*/
public PlatformStorageManagerImpl(String storagePath) {
this.storagePath = storagePath;
}
@Override
public void uploadIcon(String platformIdentifier, InputStream iconFileStream) throws ResourceManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
Platform platform = validatePlatform(tenantId, platformIdentifier);
if (platform.isFileBased()) {
throw new ApplicationStorageManagementException("Icons for the file based platforms need to be added "
+ "directly to the deployment location inside icon folder");
}
if (platform.isShared() && tenantId != MultitenantConstants.SUPER_TENANT_ID) {
throw new PlatformStorageManagementException("Platform " + platformIdentifier
+ " is a shared platform from super-tenant. Only the super-tenant users can modify it");
}
if (log.isDebugEnabled()) {
log.debug("Artifact Directory Path for saving the artifacts related with application " + platformIdentifier
+ " is " + storagePath);
}
StorageManagementUtil.createArtifactDirectory(storagePath);
if (iconFileStream != null) {
try {
saveFile(iconFileStream, storagePath + File.separator + platform.getId());
} catch (IOException e) {
throw new ApplicationStorageManagementException(
"IO Exception while saving the icon file in the server for the platform " + platformIdentifier,
e);
}
}
}
@Override
public ImageArtifact getIcon(String platformIdentifier) throws PlatformStorageManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
Platform platform = validatePlatform(tenantId, platformIdentifier);
String imageArtifactPath = storagePath + platform.getId();
File imageFile = null;
if (platform.isFileBased()) {
imageFile = new File(MultitenantUtils.getAxis2RepositoryPath(CarbonContext.getThreadLocalCarbonContext().
getTenantId()) + Constants.PLATFORMS_DEPLOYMENT_DIR_NAME + File.separator
+ Constants.IMAGE_ARTIFACTS[0] + File.separator + platformIdentifier);
} else {
imageFile = new File(imageArtifactPath);
}
if (!imageFile.exists()) {
return null;
} else {
try {
return StorageManagementUtil.createImageArtifact(imageFile, imageArtifactPath);
} catch (FileNotFoundException e) {
throw new PlatformStorageManagementException(
"File not found exception while trying to get the icon for the " + "platform "
+ platformIdentifier, e);
} catch (IOException e) {
throw new PlatformStorageManagementException(
"IO Exception while trying to detect the file type of the platform icon of "
+ platformIdentifier, e);
}
}
}
@Override
public void deleteIcon(String platformIdentifier) throws PlatformStorageManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
Platform platform = validatePlatform(tenantId, platformIdentifier);
String imageArtifactPath = storagePath + platform.getId();
if (platform.isShared() && tenantId != MultitenantConstants.SUPER_TENANT_ID) {
throw new PlatformStorageManagementException("Platform " + platformIdentifier + " is a shared platform "
+ "from super-tenant. Only the super-tenant users can modify it");
}
if (platform.isFileBased()) {
throw new PlatformStorageManagementException("Platform " + platformIdentifier + " is a file based one. "
+ "Please remove the relevant icon file directly from file system.");
}
File imageFile = new File(imageArtifactPath);
if (imageFile.exists()) {
imageFile.delete();
}
}
/**
* To validate the platform, whether the given identifier has a valid platform.
*
* @param tenantId ID of the tenant
* @param identifier Identifier of the platform
* @return Platform related with the particular identifier.
*/
private Platform validatePlatform(int tenantId, String identifier) throws PlatformStorageManagementException {
Platform platform;
try {
PlatformManager platformManager = DataHolder.getInstance().getPlatformManager();
platform = platformManager.getPlatform(tenantId, identifier);
} catch (PlatformManagementException e) {
throw new PlatformStorageManagementException(
"Platform Management Exception while getting the platform " + "related with the identifier "
+ identifier);
}
if (platform == null) {
throw new PlatformStorageManagementException("Platform does not exist with the identifier " + identifier);
}
return platform;
}
}

@ -22,8 +22,6 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager;
import org.wso2.carbon.device.application.mgt.core.dao.common.DAOFactory;
import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
import org.wso2.carbon.device.application.mgt.core.util.HelperUtil;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
@ -32,12 +30,9 @@ import org.wso2.carbon.device.mgt.common.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.app.mgt.DeviceApplicationMapping;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@ -139,7 +134,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
deviceApp.setInstalled(false);
dmpService.addDeviceApplicationMapping(deviceApp);
// DeviceManagementDAOFactory.openConnection();
// DAOFactory.getSubscriptionDAO().addDeviceApplicationMapping(device.getId(), applicationUUID, false);
// ApplicationManagementDAOFactory.getSubscriptionDAO().addDeviceApplicationMapping(device.getId(), applicationUUID, false);
failedDeviceList.remove(device);
}
} catch (DeviceManagementException | OperationManagementException | InvalidDeviceException e) {

@ -22,7 +22,7 @@ import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManage
import org.wso2.carbon.device.application.mgt.common.exception.VisibilityManagementException;
import org.wso2.carbon.device.application.mgt.common.services.VisibilityManager;
import org.wso2.carbon.device.application.mgt.core.dao.VisibilityDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.DAOFactory;
import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
/**
@ -46,7 +46,7 @@ public class VisibilityManagerImpl implements VisibilityManager {
if (!isTransactionStarted) {
ConnectionManagerUtil.beginDBTransaction();
}
VisibilityDAO visibilityDAO = DAOFactory.getVisibilityDAO();
VisibilityDAO visibilityDAO = ApplicationManagementDAOFactory.getVisibilityDAO();
int visibilityTypeId = visibilityDAO.getVisibilityID(visibility.getType());
visibilityDAO.delete(applicationID);
visibilityDAO.add(applicationID, visibilityTypeId, visibility.getAllowedList());
@ -70,7 +70,7 @@ public class VisibilityManagerImpl implements VisibilityManager {
@Override
public Visibility get(int applicationID) throws VisibilityManagementException {
try {
VisibilityDAO visibilityDAO = DAOFactory.getVisibilityDAO();
VisibilityDAO visibilityDAO = ApplicationManagementDAOFactory.getVisibilityDAO();
Visibility visibility = visibilityDAO.get(applicationID);
if (visibility.getType() == null && (visibility.getAllowedList() == null ||
visibility.getAllowedList().isEmpty())) {
@ -91,7 +91,7 @@ public class VisibilityManagerImpl implements VisibilityManager {
if (!isTransactionStarted) {
ConnectionManagerUtil.beginDBTransaction();
}
VisibilityDAO visibilityDAO = DAOFactory.getVisibilityDAO();
VisibilityDAO visibilityDAO = ApplicationManagementDAOFactory.getVisibilityDAO();
visibilityDAO.delete(applicationID);
if (!isTransactionStarted) {
ConnectionManagerUtil.commitDBTransaction();

@ -24,8 +24,6 @@ import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorage
import org.wso2.carbon.device.application.mgt.common.services.CategoryManager;
import org.wso2.carbon.device.application.mgt.common.services.CommentsManager;
import org.wso2.carbon.device.application.mgt.common.services.LifecycleStateManager;
import org.wso2.carbon.device.application.mgt.common.services.PlatformManager;
import org.wso2.carbon.device.application.mgt.common.services.PlatformStorageManager;
import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager;
import org.wso2.carbon.device.application.mgt.common.services.VisibilityManager;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
@ -50,16 +48,12 @@ public class DataHolder {
private LifecycleStateManager lifecycleStateManager;
private PlatformManager platformManager;
private SubscriptionManager subscriptionManager;
private VisibilityManager visibilityManager;
private ApplicationStorageManager applicationStorageManager;
private PlatformStorageManager platformStorageManager;
private static final DataHolder applicationMgtDataHolder = new DataHolder();
private DataHolder() {
@ -118,14 +112,6 @@ public class DataHolder {
this.lifecycleStateManager = lifecycleStateManager;
}
public PlatformManager getPlatformManager() {
return platformManager;
}
public void setPlatformManager(PlatformManager platformManager) {
this.platformManager = platformManager;
}
public SubscriptionManager getSubscriptionManager() {
return subscriptionManager;
}
@ -157,12 +143,4 @@ public class DataHolder {
public ApplicationStorageManager getApplicationStorageManager() {
return applicationStorageManager;
}
public void setPlatformStorageManager(PlatformStorageManager platformStorageManager) {
this.platformStorageManager = platformStorageManager;
}
public PlatformStorageManager getPlatformStorageManager() {
return platformStorageManager;
}
}

@ -1,63 +0,0 @@
/*
* Copyright (c) 2017, 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.application.mgt.core.internal;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.common.exception.PlatformManagementException;
import org.wso2.carbon.utils.AbstractAxis2ConfigurationContextObserver;
/**
* PlatformManagementAxis2ConfigurationObserverImpl is responsible for adding relevant platform mapping of shared
* platforms during the tenant creation time.
*/
public class PlatformManagementAxis2ConfigurationObserverImpl extends AbstractAxis2ConfigurationContextObserver {
private static Log log = LogFactory.getLog(PlatformManagementAxis2ConfigurationObserverImpl.class);
/**
* Whenever a new tenant creation happens, shared platforms need to be added for the relevant tenant.
* @param tenantId Id of the tenant that is being created
*/
@Override
public void creatingConfigurationContext(int tenantId) {
try {
DataHolder.getInstance().getPlatformManager().initialize(tenantId);
} catch (PlatformManagementException e) {
log.error("Error while trying add platforms to the newly created tenant " + tenantId, e);
}
}
/**
* Whenever terminating a tenant,the platforms added by the tenant need to be removed.
* @param configContext Configuration context.
*/
@Override
public void terminatingConfigurationContext(ConfigurationContext configContext) {
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
int tenantId = carbonContext.getTenantId();
try {
DataHolder.getInstance().getPlatformManager().removePlatforms(tenantId);
} catch (PlatformManagementException e) {
log.error("Error while removing shared platforms while removing the tenant: " + tenantId, e);
}
}
}

@ -29,12 +29,10 @@ import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorage
import org.wso2.carbon.device.application.mgt.common.services.CategoryManager;
import org.wso2.carbon.device.application.mgt.common.services.CommentsManager;
import org.wso2.carbon.device.application.mgt.common.services.LifecycleStateManager;
import org.wso2.carbon.device.application.mgt.common.services.PlatformManager;
import org.wso2.carbon.device.application.mgt.common.services.PlatformStorageManager;
import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager;
import org.wso2.carbon.device.application.mgt.common.services.VisibilityManager;
import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager;
import org.wso2.carbon.device.application.mgt.core.dao.common.DAOFactory;
import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.util.ApplicationManagementUtil;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
@ -75,7 +73,7 @@ public class ServiceComponent {
BundleContext bundleContext = componentContext.getBundleContext();
try {
String datasourceName = ConfigurationManager.getInstance().getConfiguration().getDatasourceName();
DAOFactory.init(datasourceName);
// ApplicationManagementDAOFactory.init(datasourceName);
ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance();
DataHolder.getInstance().setApplicationManager(applicationManager);
@ -98,6 +96,7 @@ public class ServiceComponent {
DataHolder.getInstance().setLifecycleStateManager(lifecycleStateManager);
bundleContext.registerService(LifecycleStateManager.class.getName(), lifecycleStateManager, null);
//remove this
PlatformManager platformManager = ApplicationManagementUtil.getPlatformManagerInstance();
DataHolder.getInstance().setPlatformManager(platformManager);
bundleContext.registerService(PlatformManager.class.getName(), platformManager, null);
@ -115,16 +114,18 @@ public class ServiceComponent {
DataHolder.getInstance().setApplicationStorageManager(applicationStorageManager);
bundleContext.registerService(ApplicationStorageManager.class.getName(), applicationStorageManager, null);
//can remove
PlatformStorageManager platformStorageManager = ApplicationManagementUtil
.getPlatformStorageManagerInstance();
DataHolder.getInstance().setPlatformStorageManager(platformStorageManager);
bundleContext.registerService(PlatformStorageManager.class.getName(), platformStorageManager, null);
//can remove
bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(),
new PlatformManagementAxis2ConfigurationObserverImpl(), null);
DAOFactory.init(datasourceName);
DAOFactory.initDatabases();
ApplicationManagementDAOFactory.init(datasourceName);
ApplicationManagementDAOFactory.initDatabases();
log.info("ApplicationManagement core bundle has been successfully initialized");
} catch (InvalidConfigurationException e) {
log.error("Error while activating Application Management core component. ", e);

@ -27,8 +27,6 @@ import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorage
import org.wso2.carbon.device.application.mgt.common.services.CategoryManager;
import org.wso2.carbon.device.application.mgt.common.services.CommentsManager;
import org.wso2.carbon.device.application.mgt.common.services.LifecycleStateManager;
import org.wso2.carbon.device.application.mgt.common.services.PlatformManager;
import org.wso2.carbon.device.application.mgt.common.services.PlatformStorageManager;
import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager;
import org.wso2.carbon.device.application.mgt.common.services.VisibilityManager;
import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager;
@ -100,6 +98,7 @@ public class ApplicationManagementUtil {
return getInstance(extension, ApplicationStorageManager.class);
}
//can remove
public static PlatformStorageManager getPlatformStorageManagerInstance() throws
InvalidConfigurationException {
ConfigurationManager configurationManager = ConfigurationManager.getInstance();

@ -31,6 +31,7 @@ public class Constants {
public static final String DEFAULT_CONFIG_FILE_LOCATION = CarbonUtils.getCarbonConfigDirPath() + File.separator +
Constants.APPLICATION_CONFIG_XML_FILE;
//can remove
public static final String PLATFORMS_DEPLOYMENT_DIR_NAME = "platforms";
public static final String PLATFORM_DEPLOYMENT_EXT = ".xml";

@ -22,7 +22,7 @@ var uriMatcher = new URIMatcher(String(uri));
var log = new Log("api/device-api.jag");
var constants = require("/app/modules/constants.js");
var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var deviceModule = require("/app/modules/business-controllers/app.js")["storeModule"];
var utility = require("/app/modules/utility.js").utility;
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
@ -45,11 +45,11 @@ if (!user) {
} else {
queryString = "?" + queryString;
}
var deviceType = request.getParameter("deviceType"); // need a better solution here
deviceTypeConfig = utility.getDeviceTypeConfig(deviceType);
if (deviceTypeConfig && deviceTypeConfig.deviceType.downloadAgentUri) {
var type = request.getParameter("type"); // need a better solution here
deviceTypeConfig = utility.getDeviceTypeConfig(type);
if (deviceTypeConfig && deviceTypeConfig.type.downloadAgentUri) {
hearders = [{"name": constants["ACCEPT_IDENTIFIER"], "value": constants["APPLICATION_ZIP"]}];
sketchDownloadEndPoint = devicemgtProps["httpsURL"] + "/" + deviceTypeConfig.deviceType.downloadAgentUri;
sketchDownloadEndPoint = devicemgtProps["httpsURL"] + "/" + deviceTypeConfig.type.downloadAgentUri;
serviceInvokers.HttpClient.get(sketchDownloadEndPoint + queryString, function (responsePayload, responseHeaders) {
if (responseHeaders) {
for (var i = 0; i < responseHeaders.length; i++) {
@ -83,18 +83,18 @@ if (!user) {
} else if (uriMatcher.match("/{context}/api/devices/types")) {
result = deviceModule.listDeviceTypes();
} else if (uriMatcher.match("/{context}/api/devices/{deviceType}/{deviceId}/remove")) {
} else if (uriMatcher.match("/{context}/api/devices/{type}/{deviceId}/remove")) {
var elements = uriMatcher.elements();
var deviceId = elements.deviceId;
var deviceType = elements.deviceType;
result = deviceModule.removeDevice(deviceType, deviceId);
var type = elements.type;
result = deviceModule.removeDevice(type, deviceId);
} else if (uriMatcher.match("/{context}/api/devices/{deviceType}/{deviceId}/update")) {
} else if (uriMatcher.match("/{context}/api/devices/{type}/{deviceId}/update")) {
var elements = uriMatcher.elements();
var deviceId = elements.deviceId;
var deviceType = elements.deviceType;
var type = elements.type;
var deviceName = request.getParameter("name");
result = deviceModule.updateDevice(deviceType, deviceId, deviceName);
result = deviceModule.updateDevice(type, deviceId, deviceName);
} else if (uriMatcher.match("/{context}/api/devices")) {
var url = request.getParameter("url");
var draw = request.getParameter("draw");
@ -163,7 +163,7 @@ if (!user) {
deviceId = elements.deviceId;
type = elements.type;
if (userModule.isAuthorized("/permission/admin/device-mgt/devices/list")) {
result = deviceModule.viewDevice(type, deviceId);
result = deviceModule.viewApps(type, deviceId);
}else {
response.sendError(403);
}

@ -26,7 +26,7 @@ var serviceInvokers = require("/app/modules/oauth/token-protected-service-invoke
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
if (uriMatcher.match("/{context}/api/operation/paginate")) {
var deviceType = request.getParameter("deviceType");
var type = request.getParameter("type");
var deviceId = request.getParameter("deviceId");
var owner = request.getParameter("owner");
var index = request.getParameter("start");
@ -34,7 +34,7 @@ if (uriMatcher.match("/{context}/api/operation/paginate")) {
var search = request.getParameter("search[value]");
var restAPIEndpoint = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
"/devices/" + deviceType + "/" + deviceId + "/operations?owner=" + owner + "&offset=" + index + "&limit=" + length;
"/devices/" + type + "/" + deviceId + "/operations?owner=" + owner + "&offset=" + index + "&limit=" + length;
serviceInvokers.XMLHttp.get(
restAPIEndpoint,

@ -26,7 +26,7 @@ var serviceInvokers = require("/app/modules/oauth/token-protected-service-invoke
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
if (uriMatcher.match("/{context}/api/stats/paginate")) {
var deviceType = request.getParameter("deviceType");
var type = request.getParameter("type");
var deviceId = request.getParameter("deviceId");
var from = request.getParameter("from");
var to = request.getParameter("to");
@ -35,7 +35,7 @@ if (uriMatcher.match("/{context}/api/stats/paginate")) {
var keys = request.getParameter("attributes");
keys = JSON.parse(keys);
var restAPIEndpoint = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/events/"
+ deviceType + "/" + deviceId + "?offset=" + index +"&limit=" + length + "&from="+ from + "&to=" + to;
+ type + "/" + deviceId + "?offset=" + index +"&limit=" + length + "&from="+ from + "&to=" + to;
serviceInvokers.XMLHttp.get(
restAPIEndpoint,
function (restAPIResponse) {

@ -25,7 +25,7 @@ var log = new Log("api/user-api.jag");
var constants = require("/app/modules/constants.js");
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var deviceModule = require("/app/modules/business-controllers/device.js")["storeModule"];
var utility = require("/app/modules/utility.js")["utility"];
var apiWrapperUtil = require("/app/modules/oauth/token-handlers.js")["handlers"];
var util = require("/app/modules/oauth/token-handler-utils.js")["utils"];

@ -3,7 +3,6 @@
"cachingEnabled": false,
"debuggingEnabled": false,
"permissionRoot": "/",
"portalURL": "https://${server.ip}:9445",
"loginPage": "cdmf.page.sign-in",
"adminServicesUrl": "https://${server.ip}:${server.https_port}/admin/services/",
"authModule": {
@ -28,10 +27,10 @@
},
"sso": {
"enabled": true,
"issuer" : "devicemgt",
"appName" : "devicemgt",
"issuer" : "store",
"appName" : "store",
"identityProviderUrl" : "https://%iot.keymanager.host%:%iot.keymanager.https.port%/samlsso",
"acs": "https://%iot.manager.host%:%iot.manager.https.port%/devicemgt/uuf/sso/acs",
"acs": "https://%iot.manager.host%:%iot.manager.https.port%/store/uuf/sso/acs",
"identityAlias": "wso2carbon",
"responseSigningEnabled" : true,
"validateAssertionValidityPeriod": true,

@ -1,5 +1,5 @@
{
"appContext": "/devicemgt/",
"appContext": "/store/",
"isCloud": false,
"isDeviceOwnerEnabled": false,
"httpsURL": "https://%iot.gateway.host%:%iot.gateway.https.port%",
@ -7,11 +7,7 @@
"wssURL": "https://%iot.analytics.host%:%iot.analytics.https.port%",
"portalURL": "https://%iot.analytics.host%:%iot.analytics.https.port%",
"dashboardServerURL": "%https.ip%",
"androidEnrollmentDir": "/android-web-agent/enrollment",
"windowsEnrollmentDir": "/windows-web-agent/enrollment",
"iOSEnrollmentDir": "/ios-web-agent/enrollment",
"iOSConfigRoot": "%https.ip%/ios-enrollment/",
"iOSAPIRoot": "%https.ip%/ios/",
"version": "1.0.0",
"adminService": "%https.ip%",
"gatewayEnabled": true,
"oauthProvider": {
@ -55,8 +51,8 @@
},
"generalConfig": {
"host": "%http.ip%",
"companyName": "WSO2 Carbon Device Manager",
"browserTitle": "WSO2 Device Manager",
"companyName": "WSO2 IoTS App Manager",
"browserTitle": "WSO2 IoTS App Store",
"copyrightPrefix": "\u00A9 %date-year%, ",
"copyrightOwner": "WSO2 Inc.",
"copyrightOwnersSite": "http://www.wso2.org",
@ -83,27 +79,8 @@
"perm:dashboard:filtered-count",
"perm:dashboard:details",
"perm:get-activity",
"perm:devices:delete",
"perm:devices:applications",
"perm:devices:effective-policy",
"perm:devices:compliance-data",
"perm:devices:features",
"perm:devices:operations",
"perm:devices:search",
"perm:devices:details",
"perm:devices:update",
"perm:devices:view",
"perm:view-configuration",
"perm:manage-configuration",
"perm:policies:remove",
"perm:policies:priorities",
"perm:policies:deactivate",
"perm:policies:get-policy-details",
"perm:policies:manage",
"perm:policies:activate",
"perm:policies:update",
"perm:policies:changes",
"perm:policies:get-details",
"perm:users:add",
"perm:users:details",
"perm:users:count",
@ -116,22 +93,15 @@
"perm:users:update",
"perm:users:send-invitation",
"perm:admin-users:view",
"perm:groups:devices",
"perm:groups:update",
"perm:groups:add",
"perm:groups:device",
"perm:groups:devices-count",
"perm:groups:remove",
"perm:groups:groups",
"perm:groups:groups-view",
"perm:groups:share",
"perm:groups:count",
"perm:groups:roles",
"perm:groups:devices-remove",
"perm:groups:devices-add",
"perm:groups:assign",
"perm:device-types:features",
"perm:device-types:types",
"perm:applications:install",
"perm:applications:uninstall",
"perm:admin-groups:count",
@ -143,17 +113,12 @@
"perm:admin:certificates:view",
"perm:admin:certificates:add",
"perm:admin:certificates:verify",
"perm:admin",
"perm:devicetype:deployment",
"perm:device-types:events",
"perm:device-types:events:view",
"perm:admin:device-type",
"perm:device:enroll",
"perm:admin", ,
"perm:geo-service:analytics-view",
"perm:geo-service:alerts-manage"
],
"isOAuthEnabled": true,
"backendRestEndpoints": {
"deviceMgt": "/api/device-mgt/v1.0"
"deviceMgt": "/api/application-mgt/v1.0"
}
}

@ -21,20 +21,6 @@ var UNSPECIFIED = "Unspecified";
var httpURL = "httpURL";
var httpsURL = "httpsURL";
var DEVICE_IDENTIFIER = "deviceIdentifier";
var DEVICE_NAME = "name";
var DEVICE_OWNERSHIP = "ownership";
var DEVICE_OWNER = "owner";
var DEVICE_TYPE = "type";
var DEVICE_VENDOR = "vendor";
var DEVICE_MODEL = "model";
var DEVICE_PRODUCT = "PRODUCT";
var DEVICE_OS_VERSION = "osVersion";
var DEVICE_OS_BUILD_DATE = "osBuildDate";
var DEVICE_PROPERTIES = "properties";
var DEVICE_ENROLLMENT_INFO = "enrolmentInfo";
var DEVICE_STATUS = "status";
var DEVICE_INFO = "deviceInfo";
var FEATURE_NAME = "featureName";
var FEATURE_DESCRIPTION = "featureDescription";

@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* Copyright (c) 2017, 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
@ -17,12 +17,11 @@
*/
function onRequest(context) {
var log = new Log("cdmf.page.dashboard");
var constants = require("/app/modules/constants.js");
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var groupModule = require("/app/modules/business-controllers/group.js")["groupModule"];
var policyModule = require("/app/modules/business-controllers/policy.js")["policyModule"];
var storeProps = require("/app/modules/conf-reader/main.js")["conf"];
if(!session.get(constants["TOKEN_PAIR"])){
response.sendRedirect(context.app.context + "/welcome");
@ -31,25 +30,14 @@ function onRequest(context) {
var user = session.get(constants["USER_SESSION_KEY"]);
var permissions = userModule.getUIPermissions();
log.error(permissions);
if (!permissions.VIEW_DASHBOARD) {
response.sendRedirect(devicemgtProps["appContext"] + "devices");
response.sendRedirect(devicemgtProps["appContext"] + "/");
return;
}
var viewModel = {};
viewModel.permissions = permissions;
viewModel.enrollmentURL = devicemgtProps.enrollmentURL;
viewModel.deviceCount = deviceModule.getDevicesCount();
viewModel.groupCount = groupModule.getGroupCount();
viewModel.userCount = userModule.getUsersCount();
viewModel.policyCount = policyModule.getPoliciesCount();
viewModel.deviceTypeCount = deviceModule.getDeviceTypeCount();
viewModel.isCloud = devicemgtProps.isCloud;
if (devicemgtProps.isCloud) {
viewModel.roleCount = userModule.getFilteredRoles("devicemgt").content.count;
} else {
viewModel.roleCount = userModule.getRolesCount();
}
return viewModel;
}

@ -1,5 +1,6 @@
{
"version": "1.0.0",
"uri": "/",
"layout": "cdmf.layout.default"
"layout": "cdmf.layout.default",
"isAnonymous" : true
}

@ -22,7 +22,7 @@
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4 col-sm-offset-3 col-md-offset-3 col-lg-offset-4">
<p class="page-sub-title">Login</p>
<p class="page-sub-title">Login###############################</p>
<hr />
{{#if message}}
<div class="alert alert-danger" style="padding-right: 15px;">

@ -18,6 +18,11 @@ function onRequest(context) {
var viewModel = {};
var loginActionUrl = context.app.context + "/uuf/login";
var log = new Log();
log.error("cdmf.page.sign-in/sign-in.js");
log.error(loginActionUrl);
if (sessionDataKey) {
loginActionUrl = "/commonauth";
}

@ -19,7 +19,7 @@
<tr data-type="selectable" data-id="{{id}}">
<td data-display="{{description}}" data-grid-label="Description">{{description}}</td>
<td style="text-align: center;">
<a href="device/{{deviceType}}?id={{deviceIdentifier}}" data-id="{{id}}" data-url="device/{{deviceType}}?id={{deviceIdentifier}}" class="new-notification" data-click-event="remove-form">
<a href="device/{{type}}?id={{deviceIdentifier}}" data-id="{{id}}" data-url="device/{{type}}?id={{deviceIdentifier}}" class="new-notification" data-click-event="remove-form">
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i class="fw fw-view fw-stack-1x"></i>
@ -57,7 +57,7 @@
<tr data-type="selectable" data-id="{{id}}">
<td data-display="{{description}}" data-grid-label="Description">{{description}}</td>
<td style="text-align: center;">
<a href="device/{{deviceType}}?id={{deviceIdentifier}}" data-click-event="remove-form">
<a href="device/{{type}}?id={{deviceIdentifier}}" data-click-event="remove-form">
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i class="fw fw-view fw-stack-1x"></i>

@ -2,11 +2,11 @@
<li class="message message-info" data-type="selectable" >
<h4>
<i class="icon fw fw-info"></i>
<a href="{{../context}}/device/{{deviceType}}?id={{deviceIdentifier}}"
<a href="{{../context}}/device/{{type}}?id={{deviceIdentifier}}"
data-id="{{id}}"
data-url="device?type={{deviceType}}&id={{deviceIdentifier}}"
data-url="device?type={{type}}&id={{deviceIdentifier}}"
class="new-notification" data-click-event="remove-form">
{{deviceType}} : {{deviceName}}
{{type}} : {{deviceName}}
</a>
</h4>
<p>{{description}}</p>

@ -262,11 +262,14 @@ var module = {};
var redirectUri;
if (event == EVENT_SUCCESS) {
redirectUri = getRelayState(operation);
log.error("auth.js ----- Success "+redirectUri);
} else {
// event == EVENT_FAIL
redirectUri = getRedirectUri(operation, EVENT_FAIL) + "?error=" + scriptArgument.message
+ "&" + constants.URL_PARAM_REFERER + "=" + getRelayState(operation);
log.error("auth.js ----- Not Success"+redirectUri);
}
log.error("Redirect URL "+encodeURI(module.getAppContext() + redirectUri));
response.sendRedirect(encodeURI(module.getAppContext() + redirectUri));
}
@ -389,6 +392,8 @@ var module = {};
*/
module.isSsoEnabled = function () {
var ssoConfigs = getSsoConfigurations();
log.error("auth.js/sso configs");
log.error(ssoConfigs);
return utils.parseBoolean(ssoConfigs[constants.APP_CONF_AUTH_MODULE_SSO_ENABLED]);
};
@ -414,6 +419,8 @@ var module = {};
* @param response {Object} HTTP response
*/
module.renderSsoIntermediatePage = function (operation, response) {
log.error(operation);
log.error(response);
var requestParams, uri;
if (operation == OPERATION_LOGIN) {
requestParams = getSsoLoginRequestParams();
@ -490,6 +497,12 @@ var module = {};
var ssoClient = require("sso").client;
var samlResponseObj;
log.error("request");
log.error(request);
log.error("response");
log.error(response);
if (samlResponse) {
try {
samlResponseObj = ssoClient.getSamlObject(samlResponse);
@ -693,6 +706,7 @@ var module = {};
input: {username: username, password: password},
user: module.getCurrentUser()
};
// log.error("auth.js/isAuthenticated");
handleEvent(OPERATION_LOGIN, EVENT_SUCCESS, scriptArgument);
} else {
handleEvent(OPERATION_LOGIN, EVENT_FAIL, new Error("Incorrect username or password."));

@ -36,15 +36,19 @@ require("/lib/error-pages-router.js");
}
var referer = request.getHeader("referer");
var redirectUrl = (referer) ? referer : (authModule.getAppContext() + "/");
log.error("login.jag/currentUser");
log.error(redirectUrl);
response.sendRedirect(redirectUrl);
return;
}
if (authModule.isSsoEnabled()) {
log.error("login.jag/authModule.isSsoEnabled()");
// SSO is enabled.
authModule.renderSsoIntermediatePage("login", response);
} else {
// Generic login process is enabled.
log.error("login.jag/authModule.isSsoEnabled() ----- Not");
authModule.login(request, response);
}
})();

@ -35,11 +35,13 @@ var route;
function getPageData(pageUri, lookupTable) {
var uriPagesMap = lookupTable.uriPagesMap;
var uriMatcher = new URIMatcher(pageUri);
// log.error(pageUri);
var uriPatterns = Object.keys(uriPagesMap);
var numberOfUriPatterns = uriPatterns.length;
for (var i = 0; i < numberOfUriPatterns; i++) {
var uriPattern = uriPatterns[i];
// log.error(uriPattern);
if (uriMatcher.match(uriPattern)) {
return {
page: lookupTable.pages[uriPagesMap[uriPattern]],
@ -60,14 +62,17 @@ var route;
function getLoginPageUri(renderingContext, lookupTable) {
var appData = renderingContext.app;
var loginPageFullName = appData.conf[constants.APP_CONF_LOGIN_PAGE];
log.error(loginPageFullName);
if (loginPageFullName) {
var loginPage = lookupTable.pages[loginPageFullName];
log.error(loginPage);
if (loginPage) {
loginPage = utils.getFurthestChild(loginPage);
if (loginPage.disabled) {
log.warn("Login page '" + loginPage.fullName + " mentioned in application "
+ "configuration file '" + constants.FILE_APP_CONF + "' is disabled.");
} else {
log.error(appData.context + loginPage.definition[constants.PAGE_DEFINITION_URI]);
return (appData.context + loginPage.definition[constants.PAGE_DEFINITION_URI]);
}
} else {
@ -178,6 +183,7 @@ var route;
}
var renderer = require("/lib/dynamic-files-renderer.js").renderer;
log.error("pages-router.js --------------------");
renderer.renderUiComponent(pageData.page, {}, renderingContext, lookupTable, response);
};
})();

@ -18,7 +18,6 @@
package org.wso2.carbon.device.mgt.core.app.mgt;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
@ -33,7 +32,6 @@ import org.wso2.carbon.device.mgt.common.app.mgt.DeviceApplicationMapping;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfig;
import org.wso2.carbon.device.mgt.core.dao.ApplicationDAO;
import org.wso2.carbon.device.mgt.core.dao.ApplicationMappingDAO;
@ -78,13 +76,13 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
@Override
public void updateApplicationStatus(DeviceIdentifier deviceId, Application application,
String status) throws ApplicationManagementException {
String status) throws ApplicationManagementException {
}
@Override
public String getApplicationStatus(DeviceIdentifier deviceId,
Application application) throws ApplicationManagementException {
Application application) throws ApplicationManagementException {
return null;
}
@ -210,7 +208,6 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
public void updateApplicationListInstalledInDevice(
DeviceIdentifier deviceIdentifier,
List<Application> applications) throws ApplicationManagementException {
<<<<<<< HEAD
try {
DeviceManagementDAOFactory.beginTransaction();
@ -275,19 +272,17 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
}
=======
if (log.isDebugEnabled()) {
log.debug("Updating application list for device: " + deviceIdentifier.toString());
}
>>>>>>> 9cbc4a5da3dbc45ea572d94212b7577655aa365e
List<Application> installedAppList = getApplicationListForDevice(deviceIdentifier);
try {
Device device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier,
false);
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
if (log.isDebugEnabled()) {
log.debug("Device:" + device.getId() + ":identifier:" + deviceIdentifier.getId());
}
if (log.isDebugEnabled()) {
log.debug("Number of apps installed:" + installedAppList.size());
log.debug("num of apps installed:" + installedAppList.size());
}
List<Application> appsToAdd = new ArrayList<>();
List<Integer> appIdsToRemove = new ArrayList<>(installedAppList.size());
@ -306,15 +301,6 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
List<Integer> applicationIds = new ArrayList<>();
for (Application application : applications) {
// Adding N/A if application doesn't have a version. Also truncating the application version,
// if length of the version is greater than maximum allowed length.
if (application.getVersion() == null) {
application.setVersion("N/A");
} else if (application.getVersion().length() >
DeviceManagementConstants.OperationAttributes.APPLIST_VERSION_MAX_LENGTH) {
application.setVersion(StringUtils.abbreviate(application.getVersion(),
DeviceManagementConstants.OperationAttributes.APPLIST_VERSION_MAX_LENGTH));
}
if (!installedAppList.contains(application)) {
installedApp = applicationDAO.getApplication(application.getApplicationIdentifier(),
application.getVersion(), tenantId);
@ -338,34 +324,24 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
if (log.isDebugEnabled()) {
log.debug("num of remove app Ids:" + appIdsToRemove.size());
}
DeviceManagementDAOFactory.commitTransaction();
} catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred saving application list of the device " + deviceIdentifier.toString();
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
throw new ApplicationManagementException("Error occurred saving application list to the device", e);
} catch (TransactionManagementException e) {
String msg = "Error occurred while initializing transaction for saving application list to the device "
+ deviceIdentifier.toString();
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
throw new ApplicationManagementException("Error occurred while initializing transaction", e);
} catch (DeviceManagementException e) {
String msg = "Error occurred obtaining the device object for device " + deviceIdentifier.toString();
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (Exception e) {
String msg = "Exception occurred saving application list of the device " + deviceIdentifier.toString();
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
throw new ApplicationManagementException("Error occurred obtaining the device object.", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
}
@Override
public List<Application> getApplicationListForDevice(DeviceIdentifier deviceId)
throws ApplicationManagementException {
Device device;
public List<Application> getApplicationListForDevice(
DeviceIdentifier deviceId) throws ApplicationManagementException {
Device device = null;
try {
device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceId,
false);
@ -376,26 +352,18 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
if (device == null) {
if (log.isDebugEnabled()) {
log.debug("No device is found upon the device identifier '" + deviceId.getId() +
"' and type '" + deviceId.getType() + "'. Therefore returning empty app list");
"' and type '" + deviceId.getType() + "'. Therefore returning null");
}
return new ArrayList<>();
return null;
}
try {
DeviceManagementDAOFactory.openConnection();
return applicationDAO.getInstalledApplications(device.getId());
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while fetching the Application List of device " + deviceId.toString();
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
throw new ApplicationManagementException("Error occurred while fetching the Application List of '" +
deviceId.getType() + "' device carrying the identifier'" + deviceId.getId(), e);
} catch (SQLException e) {
String msg = "Error occurred while opening a connection to the data source to get application " +
"list of the device " + deviceId.toString();
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (Exception e) {
String msg = "Exception occurred getting application list of the device " + deviceId.toString();
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
throw new ApplicationManagementException("Error occurred while opening a connection to the data source", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}

@ -26,11 +26,8 @@ import org.wso2.carbon.device.mgt.common.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.MonitoringOperation;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
<<<<<<< HEAD
import org.wso2.carbon.device.mgt.common.app.mgt.DeviceApplicationMapping;
=======
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
>>>>>>> 9cbc4a5da3dbc45ea572d94212b7577655aa365e
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;

@ -28,14 +28,11 @@ import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.DeviceNotFoundException;
<<<<<<< HEAD
import org.wso2.carbon.device.mgt.common.app.mgt.DeviceApplicationMapping;
import org.wso2.carbon.device.mgt.common.pull.notification.PullNotificationExecutionFailedException;
import org.wso2.carbon.device.mgt.common.pull.notification.PullNotificationSubscriber;
import org.wso2.carbon.device.mgt.core.dao.ApplicationMappingDAO;
import org.wso2.carbon.device.mgt.core.dto.DeviceTypeServiceIdentifier;
=======
>>>>>>> 9cbc4a5da3dbc45ea572d94212b7577655aa365e
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.InitialOperationConfig;

@ -20,4 +20,8 @@ select id , latitude, longitude,timeStamp, type, speed, heading ,eventId , "NORM
insert into dataOut;
from dataIn[id != "$deviceId"]
select id , latitude, longitude,timeStamp, type, speed, heading ,eventId , "NORMAL" as state, "" as information
<<<<<<< Updated upstream
insert into dataOut;
=======
insert into dataOut;
>>>>>>> Stashed changes

@ -20,4 +20,8 @@ select id , latitude, longitude,timeStamp, type ,speed, heading ,eventId , "NORM
insert into dataOut;
from dataIn[id != "$deviceId"]
select id , latitude, longitude,timeStamp, type, speed, heading ,eventId , "NORMAL" as state, "" as information
<<<<<<< Updated upstream
insert into dataOut;
=======
insert into dataOut;
>>>>>>> Stashed changes

@ -45,12 +45,18 @@ if (!user) {
} else {
queryString = "?" + queryString;
}
<<<<<<< Updated upstream
var deviceType = request.getParameter("deviceType"); // need a better solution here
deviceTypeConfig = utility.getDeviceTypeConfig(deviceType);
if (deviceTypeConfig && deviceTypeConfig.deviceType.downloadAgentUri) {
=======
var type = request.getParameter("type"); // need a better solution here
deviceTypeConfig = utility.getDeviceTypeConfig(type);
if (deviceTypeConfig && deviceTypeConfig.type.downloadAgentUri) {
>>>>>>> Stashed changes
hearders = [{"name": constants["ACCEPT_IDENTIFIER"], "value": constants["APPLICATION_ZIP"]}];
sketchDownloadEndPoint = devicemgtProps["httpsURL"] + "/" + deviceTypeConfig.deviceType.downloadAgentUri;
sketchDownloadEndPoint = devicemgtProps["httpsURL"] + "/" + deviceTypeConfig.type.downloadAgentUri;
serviceInvokers.HttpClient.get(sketchDownloadEndPoint + queryString, function (responsePayload, responseHeaders) {
if (responseHeaders) {
for (var i = 0; i < responseHeaders.length; i++) {
@ -109,18 +115,18 @@ if (!user) {
} else if (uriMatcher.match("/{context}/api/devices/types")) {
result = deviceModule.listDeviceTypes();
} else if (uriMatcher.match("/{context}/api/devices/{deviceType}/{deviceId}/remove")) {
} else if (uriMatcher.match("/{context}/api/devices/{type}/{deviceId}/remove")) {
var elements = uriMatcher.elements();
var deviceId = elements.deviceId;
var deviceType = elements.deviceType;
result = deviceModule.removeDevice(deviceType, deviceId);
var type = elements.type;
result = deviceModule.removeDevice(type, deviceId);
} else if (uriMatcher.match("/{context}/api/devices/{deviceType}/{deviceId}/update")) {
} else if (uriMatcher.match("/{context}/api/devices/{type}/{deviceId}/update")) {
var elements = uriMatcher.elements();
var deviceId = elements.deviceId;
var deviceType = elements.deviceType;
var type = elements.type;
var deviceName = request.getParameter("name");
result = deviceModule.updateDevice(deviceType, deviceId, deviceName);
result = deviceModule.updateDevice(type, deviceId, deviceName);
} else if (uriMatcher.match("/{context}/api/devices")) {
var url = request.getParameter("url");
var draw = request.getParameter("draw");

@ -26,7 +26,7 @@ var serviceInvokers = require("/app/modules/oauth/token-protected-service-invoke
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
if (uriMatcher.match("/{context}/api/operation/paginate")) {
var deviceType = request.getParameter("deviceType");
var type = request.getParameter("type");
var deviceId = request.getParameter("deviceId");
var owner = request.getParameter("owner");
var index = request.getParameter("start");
@ -34,7 +34,7 @@ if (uriMatcher.match("/{context}/api/operation/paginate")) {
var search = request.getParameter("search[value]");
var restAPIEndpoint = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
"/devices/" + deviceType + "/" + deviceId + "/operations?owner=" + owner + "&offset=" + index + "&limit=" + length;
"/devices/" + type + "/" + deviceId + "/operations?owner=" + owner + "&offset=" + index + "&limit=" + length;
serviceInvokers.XMLHttp.get(
restAPIEndpoint,

@ -26,7 +26,7 @@ var serviceInvokers = require("/app/modules/oauth/token-protected-service-invoke
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
if (uriMatcher.match("/{context}/api/stats/paginate")) {
var deviceType = request.getParameter("deviceType");
var type = request.getParameter("type");
var deviceId = request.getParameter("deviceId");
var from = request.getParameter("from");
var to = request.getParameter("to");
@ -35,7 +35,7 @@ if (uriMatcher.match("/{context}/api/stats/paginate")) {
var keys = request.getParameter("attributes");
keys = JSON.parse(keys);
var restAPIEndpoint = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/events/"
+ deviceType + "/" + deviceId + "?offset=" + index +"&limit=" + length + "&from="+ from + "&to=" + to;
+ type + "/" + deviceId + "?offset=" + index +"&limit=" + length + "&from="+ from + "&to=" + to;
serviceInvokers.XMLHttp.get(
restAPIEndpoint,
function (restAPIResponse) {

@ -37,7 +37,7 @@
</a>
</li>
<li>
<a href="{{@app.context}}/device/{{deviceType}}?id={{deviceId}}">
<a href="{{@app.context}}/device/{{type}}?id={{deviceId}}">
{{deviceName}}
</a>
</li>

@ -39,7 +39,7 @@
</a>
</li>
<li>
<a href="{{@app.context}}/device/{{deviceType}}/enroll">
<a href="{{@app.context}}/device/{{type}}/enroll">
{{label}}
</a>
</li>
@ -50,7 +50,7 @@
<div class="wr-hidden-operations wr-advance-operations"></div>
<div class="col-md-12 wr-page-content">
<div>
{{! dynamically resolves device type-view unit according to deviceType URI param }}
{{! dynamically resolves device type-view unit according to type URI param }}
{{unit deviceTypeViewUnitName}}
</div>
</div>

@ -182,7 +182,7 @@
{{#each policyListToView}}
<tr data-type="selectable" data-id="{{id}}" data-status="{{status}}">
<td class="remove-padding icon-only content-fill viewEnabledIcon"
data-url="{{@app.context}}/policy/view?id={{id}}&deviceType={{platform}}" data-id="{{id}}">
data-url="{{@app.context}}/policy/view?id={{id}}&type={{platform}}" data-id="{{id}}">
<div class="thumbnail icon">
<img src="{{icon}}">
</div>
@ -239,7 +239,7 @@
</td>
<td class="text-right content-fill text-left-on-grid-view no-wrap tooltip-overflow-fix">
<!--suppress HtmlUnknownTarget -->
<a href="{{@app.context}}/policy/edit?id={{id}}&deviceType={{platform}}"
<a href="{{@app.context}}/policy/edit?id={{id}}&type={{platform}}"
data-id="{{id}}"
data-toggle="tooltip"
data-original-title="Edit"

@ -1,11 +1,11 @@
<div class="col-lg-12 margin-top-double">
<h1 class="grey ">{{deviceType}}</h1>
<h1 class="grey ">{{type}}</h1>
<hr>
</div>
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-3 padding-top add-margin-bottom-5x">
<img src="{{@unit.publicUri}}/images/deviceType.png" class="img-responsive">
<img src="{{@unit.publicUri}}/images/type.png" class="img-responsive">
</div>
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 padding-top">
@ -127,7 +127,7 @@
<li class="padding-top-double"><span><h4 class="uppercase">Create Device</h4></span>
<code>curl -X POST {{httpsGateway}}/api/device-mgt/v1.0/device/agent/enroll -H 'accept: application/json'
-H 'authorization: Bearer %accessToken%'
-H 'content-type: application/json' -d '{ "name": "devicename", "type": "{{deviceType}}",
-H 'content-type: application/json' -d '{ "name": "devicename", "type": "{{type}}",
"description": "descritption", "deviceIdentifier": "1234", "enrolmentInfo":
{"ownership": "BYOD", "status": "ACTIVE"}
,"properties": [{"name": "propertyName","value": "propertyValue"}]}'</code>
@ -149,7 +149,7 @@
<i class="icon fw fw-error"></i><span></span>
</div>
<input aria-describedby="basic-addon1" type="text" id="deviceTypeName" style="display: none;"
data-error-msg="invalid device type name" class="form-control" value="{{deviceType}}"/>
data-error-msg="invalid device type name" class="form-control" value="{{type}}"/>
<br>
<label class="wr-input-label">Name</label>
<input aria-describedby="basic-addon1" type="text" id="deviceName"

@ -18,7 +18,7 @@
{{#defineZone "contentTitle"}}
<div class="row wr-device-board">
<div class="col-lg-12 wr-secondary-bar">
<span class="page-sub-title">{{@uriParams.deviceType}} Agent Download</span>
<span class="page-sub-title">{{@uriParams.type}} Agent Download</span>
</div>
</div>
{{/defineZone}}
@ -63,22 +63,22 @@
<div class="container">
<div class="col-lg-12 margin-top-double">
<h1 class="grey ">{{deviceType.displayName}}</h1>
<h1 class="grey ">{{type.displayName}}</h1>
<hr>
<p class="margin-bottom-double light-grey ">{{#defineZone "deviceTypeHeading"}}Connect your {{deviceType.displayName}} device
<p class="margin-bottom-double light-grey ">{{#defineZone "deviceTypeHeading"}}Connect your {{type.displayName}} device
to the WSO2 device cloud. {{/defineZone}}</p>
</div>
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-4 padding-top">
<img src="{{@app.context}}{{deviceType.image}}" class="img-responsive">
<img src="{{@app.context}}{{type.image}}" class="img-responsive">
</div>
<div class="col-xs-12 col-sm-6 col-md-8 col-lg-8 padding-top">
{{#if deviceType.ingredients}}
{{#if type.ingredients}}
<h3 class="uppercase">Ingredients</h3>
<hr>
<p class="grey margin-top">Hardware Requirements </p>
<br>
<ul>
{{#itr deviceType.ingredients}}
{{#itr type.ingredients}}
<span class="fw-stack fw-lg margin-right">
<i class="fw fw-circle-outline fw-stack-2x"> </i>
<i class="fw fw-right-arrow fw-stack-1x"></i>
@ -89,22 +89,22 @@
<br>
{{/if}}
{{#if deviceType.downloadBtnText}}
<a href="#" class="download-link btn-operations" data-devicetype="{{@uriParams.deviceType}}" data-sketchtype="{{@uriParams.deviceType}}"><i class="fw fw-download"></i> {{{deviceType.downloadBtnText}}}</a>
{{#if type.downloadBtnText}}
<a href="#" class="download-link btn-operations" data-devicetype="{{@uriParams.type}}" data-sketchtype="{{@uriParams.type}}"><i class="fw fw-download"></i> {{{type.downloadBtnText}}}</a>
{{else}}
<a href="#" class="download-link btn-operations" data-devicetype="{{@uriParams.deviceType}}" data-sketchtype="{{@uriParams.deviceType}}"><i class="fw fw-download"></i> Download</a>
<a href="#" class="download-link btn-operations" data-devicetype="{{@uriParams.type}}" data-sketchtype="{{@uriParams.type}}"><i class="fw fw-download"></i> Download</a>
{{/if}}
<br/><br/>
</div>
{{#if deviceType.prepareSteps}}
{{#if type.prepareSteps}}
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-12 padding-double grey-bg ">
<h3 class="uppercase">Prepare</h3><hr>
<p class="grey margin-top">Get your device ready</p>
<br/>
<ul>
{{#itr deviceType.prepareSteps}}
{{#itr type.prepareSteps}}
<p class="padding-top-double"><span class="circle">0{{key}}</span> {{{value}}}</p>
{{/itr}}
</ul>
@ -112,26 +112,26 @@
</div>
{{/if}}
{{#if deviceType.schematicDiagram}}
{{#if type.schematicDiagram}}
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-12 padding-double">
<h3 class="uppercase">Schematic Diagram</h3><hr>
<p class="grey margin-top">Click on the image to zoom</p>
<center>
<a href="{{@app.context}}{{deviceType.schematicDiagram}}" target="_blank">
<img src="{{@app.context}}{{deviceType.schematicDiagram}}" class="img-responsive" style="max-width: 500px; max-height: 500px">
<a href="{{@app.context}}{{type.schematicDiagram}}" target="_blank">
<img src="{{@app.context}}{{type.schematicDiagram}}" class="img-responsive" style="max-width: 500px; max-height: 500px">
</a>
</center>
<br/>
</div>
{{/if}}
{{#if deviceType.quickStartup}}
{{#if type.quickStartup}}
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-12 padding-double">
<h3 class="uppercase">Connect (Quick Start)</h3><hr>
<p class="grey margin-top">Internet of Things Foundation Quickstart connection</p>
<br/>
<ul>
{{#itr deviceType.quickStartup}}
{{#itr type.quickStartup}}
<p class="padding-top-double"><span class="circle">0{{key}}</span> {{{value}}}</p>
{{/itr}}
</ul>
@ -139,17 +139,17 @@
</div>
{{/if}}
{{#if deviceType.additionalHtml}}
{{{deviceType.additionalHtml}}}
{{#if type.additionalHtml}}
{{{type.additionalHtml}}}
{{/if}}
</div>
{{#if deviceType.showQRCode}}
{{#if type.showQRCode}}
<div id="qr-code-modal" data-enrollment-url="{{deviceType.enrollmentURL}}" class="hidden">
<div id="qr-code-modal" data-enrollment-url="{{type.enrollmentURL}}" class="hidden">
<div class="content">
<div class="row">

@ -7,7 +7,7 @@
</span>
<span class="wr-list-desc">
<h3 class="wr-list-name">{{policy.policyName}}</h3>
<span class="wr-list-username">{{deviceType}}</span>
<span class="wr-list-username">{{type}}</span>
</span>
</div>
<div class="col-lg-6">
@ -37,7 +37,7 @@
</div>
<div class="col-lg-3">
<span class="list-group-item-actions">
<a href="{{appContext}}/policy/effective-policy?type={{deviceType}}&id={{deviceId}}"
<a href="{{appContext}}/policy/effective-policy?type={{type}}&id={{deviceId}}"
class="cu-btn-inner policy-view-link" data-id="{{id}}">
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>

@ -19,7 +19,7 @@
<tr data-type="selectable" data-id="{{id}}">
<td data-display="{{description}}" data-grid-label="Description">{{description}}</td>
<td style="text-align: center;">
<a href="device/{{deviceType}}?id={{deviceIdentifier}}" data-id="{{id}}" data-url="device/{{deviceType}}?id={{deviceIdentifier}}" class="new-notification" data-click-event="remove-form">
<a href="device/{{type}}?id={{deviceIdentifier}}" data-id="{{id}}" data-url="device/{{type}}?id={{deviceIdentifier}}" class="new-notification" data-click-event="remove-form">
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i class="fw fw-view fw-stack-1x"></i>
@ -57,7 +57,7 @@
<tr data-type="selectable" data-id="{{id}}">
<td data-display="{{description}}" data-grid-label="Description">{{description}}</td>
<td style="text-align: center;">
<a href="device/{{deviceType}}?id={{deviceIdentifier}}" data-click-event="remove-form">
<a href="device/{{type}}?id={{deviceIdentifier}}" data-click-event="remove-form">
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i class="fw fw-view fw-stack-1x"></i>

@ -2,11 +2,11 @@
<li class="message message-info" data-type="selectable" >
<h4>
<i class="icon fw fw-info"></i>
<a href="{{../context}}/device/{{deviceType}}?id={{deviceIdentifier}}"
<a href="{{../context}}/device/{{type}}?id={{deviceIdentifier}}"
data-id="{{id}}"
data-url="device?type={{deviceType}}&id={{deviceIdentifier}}"
data-url="device?type={{type}}&id={{deviceIdentifier}}"
class="new-notification" data-click-event="remove-form">
{{deviceType}} : {{deviceName}}
{{type}} : {{deviceName}}
</a>
</h4>
<p>{{description}}</p>

@ -23,7 +23,7 @@
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>carbon-devicemgt</artifactId>
<packaging>pom</packaging>
<version>3.0.172-SNAPSHOT</version>
<version>3.0.46-SNAPSHOT</version>
<name>WSO2 Carbon - Device Management - Parent</name>
<url>http://wso2.org</url>
<description>WSO2 Connected Device Manager Components</description>
@ -54,7 +54,6 @@
<module>features/email-sender</module>
<module>features/jwt-client</module>
<module>features/device-mgt-extensions</module>
<module>components/test-coverage</module>
</modules>
<dependencyManagement>
@ -268,6 +267,11 @@
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<version>${carbon.device.mgt.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics.dashboard</artifactId>
<version>${carbon.device.mgt.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.server.feature</artifactId>
@ -460,18 +464,6 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.securevault</artifactId>
<version>${carbon.kernel.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.testing.osgi-mock</artifactId>
<version>${apache.osgi.mock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.governance</groupId>
<artifactId>org.wso2.carbon.governance.api</artifactId>
@ -1226,12 +1218,7 @@
<artifactId>commons-codec</artifactId>
<version>${version.commons.codec}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>${apache.http.compnents.core}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-lang.wso2</groupId>
<artifactId>commons-lang</artifactId>
@ -1601,42 +1588,6 @@
<artifactId>org.wso2.carbon.registry.resource</artifactId>
<version>${carbon.registry.resource.version}</version>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>${power.mock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-testng</artifactId>
<version>${power.mock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-dbcp.wso2</groupId>
<artifactId>commons-dbcp</artifactId>
<version>${commons.dbcp.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.governance</groupId>
<artifactId>org.wso2.carbon.governance.registry.extensions</artifactId>
<version>${carbon.governance.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<scope>test</scope>
<version>${slf4j.nop.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
@ -1887,7 +1838,7 @@
<properties>
<servelet.jsp.version>2.2.1</servelet.jsp.version>
<testng.version>6.1.1</testng.version>
<carbon.kernel.version>4.4.17</carbon.kernel.version>
<carbon.kernel.version>4.4.11</carbon.kernel.version>
<carbon.kernel.449.version>4.4.9</carbon.kernel.449.version>
<carbon.kernel.version.range>[4.4.0, 5.0.0)</carbon.kernel.version.range>
<carbon.p2.plugin.version>1.5.4</carbon.p2.plugin.version>
@ -1954,7 +1905,7 @@
<axiom.wso2.version>1.2.11.wso2v10</axiom.wso2.version>
<!-- Carbon Device Management -->
<carbon.device.mgt.version>3.0.172-SNAPSHOT</carbon.device.mgt.version>
<carbon.device.mgt.version>3.0.46-SNAPSHOT</carbon.device.mgt.version>
<!-- Carbon Commons -->
<carbon.commons.version>4.4.8</carbon.commons.version>
@ -1965,7 +1916,7 @@
<commons-lang.wso2.osgi.version.range>[2.6.0,3.0.0)</commons-lang.wso2.osgi.version.range>
<!-- Carbon API Management -->
<carbon.api.mgt.version>6.1.109</carbon.api.mgt.version>
<carbon.api.mgt.version>6.1.64</carbon.api.mgt.version>
<carbon.api.mgt.version.range>(6.0.0,7.0.0]</carbon.api.mgt.version.range>
<!-- Carbon Analytics -->
@ -1981,7 +1932,7 @@
<carbon.registry.imp.pkg.version.range>[4.4.8, 5.0.0)</carbon.registry.imp.pkg.version.range>
<!--CXF properties-->
<cxf.version>3.2.0</cxf.version>
<cxf.version>2.7.16</cxf.version>
<cxf.bindings.version>2.5.11</cxf.bindings.version>
<json-simple.version>1.1.wso2v1</json-simple.version>
<jackson.version>1.9.0</jackson.version>
@ -2065,12 +2016,6 @@
<!-- apache pdfbox version -->
<slf4j.simple.version>1.6.1</slf4j.simple.version>
<!--apache osgi mock version-->
<apache.osgi.mock.version>2.3.2</apache.osgi.mock.version>
<!-- apache http components core -->
<apache.http.compnents.core>4.4.3</apache.http.compnents.core>
<!-- api-mgt handler version properties -->
<org.apache.synapse.version>2.1.7-wso2v7</org.apache.synapse.version>
<org.apache.ws.security.wso2.version>1.5.11.wso2v15</org.apache.ws.security.wso2.version>
@ -2088,8 +2033,9 @@
<commons.codec.verision.range>(1.9,2.0]</commons.codec.verision.range>
<javassist.version>3.12.1.GA</javassist.version>
<maven.javadoc.skip>true</maven.javadoc.skip>
<!-- maven check style version -->
<maven.checkstyle.plugin.version>2.17</maven.checkstyle.plugin.version>
</properties>
</project>
</project>
Loading…
Cancel
Save