Merge branch 'application-mgt-new' into 'application-mgt-new'

Merge with upstream

See merge request entgra/carbon-device-mgt!74
This commit is contained in:
Inosh Perara 2019-04-24 09:54:18 +00:00
commit 40eecf75ea
992 changed files with 8503 additions and 198859 deletions

6
.gitignore vendored
View File

@ -29,7 +29,7 @@ components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/r
components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/package-lock.json components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/package-lock.json
components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/npm-debug.log components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/npm-debug.log
components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/dist/ components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/dist/
components/application-mgt/org.wso2.carbon.device.application.mgt.store.ui/src/main/resources/store/node_modules/ components/application-mgt/org.wso2.carbon.device.application.mgt.store.ui/react-app/node_modules/
components/application-mgt/org.wso2.carbon.device.application.mgt.store.ui/src/main/resources/store/public/dist/ components/application-mgt/org.wso2.carbon.device.application.mgt.store.ui/react-app/dist/
components/application-mgt/org.wso2.carbon.device.application.mgt.store.ui/src/main/resources/store/package-lock.json components/application-mgt/org.wso2.carbon.device.application.mgt.store.ui/react-app/package-lock.json

View File

@ -0,0 +1,95 @@
/* Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.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 org.wso2.carbon.device.application.mgt.common.ApplicationList;
import org.wso2.carbon.device.application.mgt.common.ErrorResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* APIs to handle application management related tasks.
*/
@SwaggerDefinition(
info = @Info(
version = "1.0.0",
title = "ApplicationDTO Management Common Service",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = "name", value = "ApplicationManagementArtifactDownloadService"),
@ExtensionProperty(name = "context", value = "/api/application-mgt/v1.0/artifact"),
})
}
)
)
@Path("/artifact")
@Api(value = "ApplicationDTO Management Artifact Downloading Service")
@Produces(MediaType.APPLICATION_JSON)
public interface ArtifactDownloadAPI {
@GET
@Path("/{uuid}/{fileName}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@ApiOperation(
produces = MediaType.APPLICATION_OCTET_STREAM,
httpMethod = "GET",
value = "get application management UI configuration",
notes = "This will get all UI configuration of application management"
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully got UI config.",
response = ApplicationList.class),
@ApiResponse(
code = 404,
message = "Not Found. There doesn't have an defined UI config." +
"query."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting the UI config.",
response = ErrorResponse.class)
})
Response getArtifact(
@ApiParam(
name = "uuid",
value = "UUID of the application release.",
required = true)
@PathParam("uuid") String uuid,
@ApiParam(
name = "fileName",
value = "Name of the artifact",
required = true)
@PathParam("fileName") String fileName);
}

View File

@ -40,19 +40,19 @@ import javax.ws.rs.core.Response;
@SwaggerDefinition( @SwaggerDefinition(
info = @Info( info = @Info(
version = "1.0.0", version = "1.0.0",
title = "Application Management Common Service", title = "ApplicationDTO Management Common Service",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = "name", value = "ApplicationManagementCommonService"), @ExtensionProperty(name = "name", value = "ApplicationManagementCommonService"),
@ExtensionProperty(name = "context", value = "/api/application-mgt/v1.0/app-mgt"), @ExtensionProperty(name = "context", value = "/api/application-mgt/v1.0/configt"),
}) })
} }
) )
) )
@Path("/app-mgt") @Path("/config")
@Api(value = "Application Management Common Service", description = "This API carries all application management common services") @Api(value = "ApplicationDTO Management Common Service", description = "This API carries all application management common services")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public interface AppMgtAPI { public interface ConfigRetrieveAPI {
@GET @GET
@Path("/ui-config") @Path("/ui-config")

View File

@ -0,0 +1,76 @@
/* Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.application.mgt.api.services.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.api.services.ArtifactDownloadAPI;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.services.AppmDataHandler;
import org.wso2.carbon.device.application.mgt.core.exception.BadRequestException;
import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException;
import org.wso2.carbon.device.application.mgt.core.util.APIUtil;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.InputStream;
/**
* Implementation of ApplicationDTO Management related APIs.
*/
@Produces({"application/json"})
@Path("/artifact")
public class ArtifactDownloadAPIImpl implements ArtifactDownloadAPI {
private static Log log = LogFactory.getLog(ArtifactDownloadAPIImpl.class);
@GET
@Override
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Path("/{uuid}/{fileName}")
public Response getArtifact(@PathParam("uuid") String uuid,
@PathParam("fileName") String fileName) {
AppmDataHandler dataHandler = APIUtil.getDataHandler();
try {
InputStream fileInputStream = dataHandler.getArtifactStream(uuid, fileName);
Response.ResponseBuilder response = Response
.ok(fileInputStream, MediaType.APPLICATION_OCTET_STREAM);
response.status(Response.Status.OK);
// response.type("application/html");
response.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
return response.build();
} catch (NotFoundException e) {
String msg = "Couldn't find an application release for UUID: " + uuid + " and file name: " + fileName;
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
String msg = "Invalid data is used with the request to get input stream of the application release. UUID: "
+ uuid + " and file name: " + fileName;
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
String msg = "Error occurred while getting the application release artifact file. ";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
}

View File

@ -19,11 +19,10 @@ package org.wso2.carbon.device.application.mgt.api.services.impl;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.api.services.AppMgtAPI; import org.wso2.carbon.device.application.mgt.api.services.ConfigRetrieveAPI;
import org.wso2.carbon.device.application.mgt.common.config.UIConfiguration; import org.wso2.carbon.device.application.mgt.common.config.UIConfiguration;
import org.wso2.carbon.device.application.mgt.common.services.ConfigManager; import org.wso2.carbon.device.application.mgt.common.services.AppmDataHandler;
import org.wso2.carbon.device.application.mgt.core.util.APIUtil; import org.wso2.carbon.device.application.mgt.core.util.APIUtil;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.GET; import javax.ws.rs.GET;
@ -32,29 +31,22 @@ import javax.ws.rs.Produces;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
/** /**
* Implementation of Application Management related APIs. * Implementation of ApplicationDTO Management related APIs.
*/ */
@Produces({"application/json"}) @Produces({"application/json"})
@Path("/app-mgt") @Path("/config")
public class AppMgtAPIImpl implements AppMgtAPI { public class ConfigRetrieveAPIImpl implements ConfigRetrieveAPI {
private static Log log = LogFactory.getLog(AppMgtAPIImpl.class); private static Log log = LogFactory.getLog(ConfigRetrieveAPIImpl.class);
@GET @GET
@Override @Override
@Consumes("application/json") @Consumes("application/json")
@Path("/ui-config") @Path("/ui-config")
public Response getUiConfig() { public Response getUiConfig() {
ConfigManager configManager = APIUtil.getConfigManager(); AppmDataHandler dataHandler = APIUtil.getDataHandler();
try { UIConfiguration uiConfiguration = dataHandler.getUIConfiguration();
UIConfiguration uiConfiguration = configManager.getUIConfiguration();
return Response.status(Response.Status.OK).entity(uiConfiguration).build(); return Response.status(Response.Status.OK).entity(uiConfiguration).build();
}catch (ApplicationManagementException e) {
String msg = "Error occurred while getting the application list for publisher ";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
} }
} }

View File

@ -25,7 +25,8 @@
<jaxrs:server id="applicationMgtCommonService" address="/"> <jaxrs:server id="applicationMgtCommonService" address="/">
<jaxrs:serviceBeans> <jaxrs:serviceBeans>
<ref bean="applicationMgtCommonServiceBean"/> <ref bean="applicationMgtConfigService"/>
<ref bean="applicationMgtArtifactService"/>
<ref bean="swaggerResource"/> <ref bean="swaggerResource"/>
</jaxrs:serviceBeans> </jaxrs:serviceBeans>
<jaxrs:providers> <jaxrs:providers>
@ -52,7 +53,8 @@
<bean id="swaggerWriter" class="io.swagger.jaxrs.listing.SwaggerSerializers" /> <bean id="swaggerWriter" class="io.swagger.jaxrs.listing.SwaggerSerializers" />
<bean id="swaggerResource" class="io.swagger.jaxrs.listing.ApiListingResource" /> <bean id="swaggerResource" class="io.swagger.jaxrs.listing.ApiListingResource" />
<bean id="applicationMgtCommonServiceBean" class="org.wso2.carbon.device.application.mgt.api.services.impl.AppMgtAPIImpl"/> <bean id="applicationMgtConfigService" class="org.wso2.carbon.device.application.mgt.api.services.impl.ConfigRetrieveAPIImpl"/>
<bean id="applicationMgtArtifactService" class="org.wso2.carbon.device.application.mgt.api.services.impl.ArtifactDownloadAPIImpl"/>
<bean id="jsonProvider" class="org.wso2.carbon.device.application.mgt.addons.JSONMessageHandler"/> <bean id="jsonProvider" class="org.wso2.carbon.device.application.mgt.addons.JSONMessageHandler"/>
<bean id="multipartProvider" class="org.wso2.carbon.device.application.mgt.addons.MultipartCustomProvider"/> <bean id="multipartProvider" class="org.wso2.carbon.device.application.mgt.addons.MultipartCustomProvider"/>

View File

@ -42,7 +42,6 @@
<plugin> <plugin>
<groupId>org.apache.felix</groupId> <groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId> <artifactId>maven-bundle-plugin</artifactId>
<version>1.4.0</version>
<extensions>true</extensions> <extensions>true</extensions>
<configuration> <configuration>
<instructions> <instructions>
@ -52,11 +51,12 @@
<Bundle-Description>Application Management Common Bundle</Bundle-Description> <Bundle-Description>Application Management Common Bundle</Bundle-Description>
<Import-Package> <Import-Package>
org.wso2.carbon.device.mgt.common.*;version="${carbon.device.mgt.version}", org.wso2.carbon.device.mgt.common.*;version="${carbon.device.mgt.version}",
org.wso2.carbon.device.mgt.core.dto;version="${carbon.device.mgt.version}",
com.google.gson, com.google.gson,
io.swagger.annotations.*;resolution:=optional, io.swagger.annotations.*;resolution:=optional,
com.fasterxml.jackson.annotation, com.fasterxml.jackson.annotation,
javax.validation.constraints, javax.validation.constraints,
javax.xml.bind.annotation.* javax.xml.bind.annotation.*,
</Import-Package> </Import-Package>
<Export-Package> <Export-Package>
org.wso2.carbon.device.application.mgt.common.* org.wso2.carbon.device.application.mgt.common.*
@ -113,6 +113,17 @@
<groupId>org.hibernate</groupId> <groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId> <artifactId>hibernate-validator</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -18,11 +18,13 @@
*/ */
package org.wso2.carbon.device.application.mgt.common; package org.wso2.carbon.device.application.mgt.common;
import org.wso2.carbon.device.application.mgt.common.dto.ApplicationDTO;
public class AppOperation { public class AppOperation {
private static final long serialVersionUID = 7603215716452548282L; private static final long serialVersionUID = 7603215716452548282L;
private Application application; private ApplicationDTO application;
private int tenantId; private int tenantId;
private String activityId; private String activityId;
private String scheduledDateTime; private String scheduledDateTime;
@ -71,11 +73,11 @@ public class AppOperation {
this.type = type; this.type = type;
} }
public Application getApplication() { public ApplicationDTO getApplication() {
return application; return application;
} }
public void setApplication(Application application) { public void setApplication(ApplicationDTO application) {
this.application = application; this.application = application;
} }

View File

@ -0,0 +1,92 @@
package org.wso2.carbon.device.application.mgt.common;/* Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.InputStream;
import java.util.Map;
public class ApplicationArtifact {
private String installerName;
private InputStream installerStream;
private String bannerName;
private InputStream bannerStream;
private String iconName;
private InputStream iconStream;
private Map<String , InputStream> screenshots;
public String getInstallerName() {
return installerName;
}
public void setInstallerName(String installerName) {
this.installerName = installerName;
}
public InputStream getInstallerStream() {
return installerStream;
}
public void setInstallerStream(InputStream installerStream) {
this.installerStream = installerStream;
}
public String getBannerName() {
return bannerName;
}
public void setBannerName(String bannerName) {
this.bannerName = bannerName;
}
public InputStream getBannerStream() {
return bannerStream;
}
public void setBannerStream(InputStream bannerStream) {
this.bannerStream = bannerStream;
}
public String getIconName() {
return iconName;
}
public void setIconName(String iconName) {
this.iconName = iconName;
}
public InputStream getIconStream() {
return iconStream;
}
public void setIconStream(InputStream iconStream) {
this.iconStream = iconStream;
}
public Map<String, InputStream> getScreenshots() {
return screenshots;
}
public void setScreenshots(Map<String, InputStream> screenshots) {
this.screenshots = screenshots;
}
}

View File

@ -0,0 +1,45 @@
package org.wso2.carbon.device.application.mgt.common;/* Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
public class ApplicationInstaller {
/***
* Package name of the Installer
*/
private String packageName;
/***
* Version of the Installer.
*/
private String version;
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}

View File

@ -18,10 +18,13 @@
*/ */
package org.wso2.carbon.device.application.mgt.common; package org.wso2.carbon.device.application.mgt.common;
import org.wso2.carbon.device.application.mgt.common.dto.ApplicationDTO;
import org.wso2.carbon.device.application.mgt.common.response.Application;
import java.util.List; import java.util.List;
/** /**
* Represents a list of {@link Application}. * Represents a list of {@link ApplicationDTO}.
*/ */
public class ApplicationList { public class ApplicationList {

View File

@ -0,0 +1,42 @@
package org.wso2.carbon.device.application.mgt.common;/* Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.List;
public class ApplicationReleaseArtifactPaths {
private String installerPath;
private String iconPath;
private String bannerPath;
private List<String> screenshotPaths;
public String getInstallerPath() { return installerPath; }
public void setInstallerPath(String installerPath) { this.installerPath = installerPath; }
public String getIconPath() { return iconPath; }
public void setIconPath(String iconPath) { this.iconPath = iconPath; }
public String getBannerPath() { return bannerPath; }
public void setBannerPath(String bannerPath) { this.bannerPath = bannerPath; }
public List<String> getScreenshotPaths() { return screenshotPaths; }
public void setScreenshotPaths(List<String> screenshotPaths) { this.screenshotPaths = screenshotPaths; }
}

View File

@ -1,5 +1,5 @@
package org.wso2.carbon.device.application.mgt.common; package org.wso2.carbon.device.application.mgt.common;
public enum DeviceType { public enum DeviceTypes {
ANDROID, IOS ANDROID, IOS
} }

View File

@ -21,7 +21,7 @@ package org.wso2.carbon.device.application.mgt.common;
import java.io.Serializable; import java.io.Serializable;
/** /**
* This class represents the Enterprise Application information. * This class represents the Enterprise ApplicationDTO information.
*/ */
public class EnterpriseApplication extends AndroidApplication implements Serializable { public class EnterpriseApplication extends AndroidApplication implements Serializable {

View File

@ -37,7 +37,7 @@ public class EnterpriseInstallationDetails {
@ApiModelProperty( @ApiModelProperty(
name = "applicationUUID", name = "applicationUUID",
value = "Application ID", value = "ApplicationDTO ID",
required = true, required = true,
example = "4354c752-109f-11e8-b642-0ed5f89f718b" example = "4354c752-109f-11e8-b642-0ed5f89f718b"
) )

View File

@ -18,25 +18,68 @@
*/ */
package org.wso2.carbon.device.application.mgt.common; package org.wso2.carbon.device.application.mgt.common;
import java.util.List;
/** /**
* Filter represents a criteria that can be used for searching applications. * Filter represents a criteria that can be used for searching applications.
*/ */
public class Filter { public class Filter {
/** /***
* Name of the application * Supported device type for the application.
* e.g :- Android, iOS, Windows
*/
private String deviceType;
/***
* Name of the application.
*/ */
private String appName; private String appName;
/** /***
* Type of the application * Type of the application.
* e.g :- ENTERPRISE, PUBLIC
*/ */
private String appType; private String appType;
/** /***
* Category of the application * Subscription type of the application.
* e.g :- FREE, PAID etc
*/ */
private String appCategory; private String subscriptionType;
/***
* Minimum rating of the application.
* e.g :- 4,5
*/
private int minimumRating;
/***
* Application release version.
*/
private String version;
/***
* Release type of the application release.
* e.g :- Alpha, Beta
*/
private String appReleaseType;
/**
* Category list of the application
*/
private List<String> appCategories;
/**
* Tag list of the application
*/
private List<String> tags;
/***
* Unrestricted role list. Visibility of the application can restricted through user roles and users can view the
* application who has at least one role in unrestricted role list
*/
private List<String> unrestrictedRoles;
/** /**
* Checking the application name matches fully with given name * Checking the application name matches fully with given name
@ -59,9 +102,10 @@ public class Filter {
private String sortBy; private String sortBy;
/** /**
* Set as True if required to have only published application release, otherwise set to False * Current application release state.
* e.g :- CREATED. IN_REVIEW, PUBLISHED etc
*/ */
private String currentAppReleaseState; private String appReleaseState;
public int getLimit() { public int getLimit() {
return limit; return limit;
@ -111,19 +155,43 @@ public class Filter {
this.appType = appType; this.appType = appType;
} }
public String getAppCategory() { public List<String> getAppCategories() {
return appCategory; return appCategories;
} }
public void setAppCategory(String appCategory) { public void setAppCategories(List<String> appCategories) {
this.appCategory = appCategory; this.appCategories = appCategories;
} }
public String getCurrentAppReleaseState() { public List<String> getTags() { return tags; }
return currentAppReleaseState;
}
public void setCurrentAppReleaseState(String currentAppReleaseState) { public void setTags(List<String> tags) { this.tags = tags; }
this.currentAppReleaseState = currentAppReleaseState;
} public List<String> getUnrestrictedRoles() { return unrestrictedRoles; }
public void setUnrestrictedRoles(List<String> unrestrictedRoles) { this.unrestrictedRoles = unrestrictedRoles; }
public String getAppReleaseState() { return appReleaseState; }
public void setAppReleaseState(String appReleaseState) { this.appReleaseState = appReleaseState; }
public String getDeviceType() { return deviceType; }
public void setDeviceType(String deviceType) { this.deviceType = deviceType; }
public String getSubscriptionType() { return subscriptionType; }
public void setSubscriptionType(String subscriptionType) { this.subscriptionType = subscriptionType; }
public int getMinimumRating() { return minimumRating; }
public void setMinimumRating(int minimumRating) { this.minimumRating = minimumRating; }
public String getVersion() { return version; }
public void setVersion(String version) { this.version = version; }
public String getAppReleaseType() { return appReleaseType; }
public void setAppReleaseType(String appReleaseType) { this.appReleaseType = appReleaseType; }
} }

View File

@ -0,0 +1,42 @@
package org.wso2.carbon.device.application.mgt.common;
/* Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
public class ProxyResponse {
private int code;
private String url;
private String data;
private String executorResponse;
public int getCode() { return code; }
public void setCode(int code) { this.code = code; }
public String getUrl() { return url; }
public void setUrl(String url) { this.url = url; }
public String getData() { return data; }
public void setData(String data) { this.data = data; }
public String getExecutorResponse() { return executorResponse; }
public void setExecutorResponse(String executorResponse) { this.executorResponse = executorResponse; }
}

View File

@ -19,7 +19,7 @@
package org.wso2.carbon.device.application.mgt.common; package org.wso2.carbon.device.application.mgt.common;
/** /**
* Represents an user of {@link Application}. * Represents an user.
*/ */
public class User { public class User {

View File

@ -0,0 +1,42 @@
package org.wso2.carbon.device.application.mgt.common.config;/* Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import javax.xml.bind.annotation.XmlElement;
public class RatingConfiguration {
private int minRatingValue;
private int maxRatingValue;
@XmlElement(name = "MinRatingValue")
public int getMinRatingValue() {
return minRatingValue;
}
public void setMinRatingValue(int minRatingValue) {
this.minRatingValue = minRatingValue;
}
@XmlElement(name = "MaxRatingValue")
public int getMaxRatingValue() {
return maxRatingValue;
}
public void setMaxRatingValue(int maxRatingValue) {
this.maxRatingValue = maxRatingValue;
}
}

View File

@ -16,7 +16,7 @@
* under the License. * under the License.
* *
*/ */
package org.wso2.carbon.device.application.mgt.common; package org.wso2.carbon.device.application.mgt.common.dto;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
@ -24,8 +24,8 @@ import io.swagger.annotations.ApiModelProperty;
import java.util.List; import java.util.List;
@ApiModel(value = "Application", description = "Application represents the an Application in Application Store") @ApiModel(value = "ApplicationDTO", description = "ApplicationDTO represents an Application details.")
public class Application { public class ApplicationDTO {
@ApiModelProperty(name = "id", @ApiModelProperty(name = "id",
value = "The ID given to the application when it is stored in the APPM database") value = "The ID given to the application when it is stored in the APPM database")
@ -36,6 +36,11 @@ public class Application {
required = true) required = true)
private String name; private String name;
@ApiModelProperty(name = "description",
value = "Description of the application",
required = true)
private String description;
@ApiModelProperty(name = "appCategory", @ApiModelProperty(name = "appCategory",
value = "Category of the application", value = "Category of the application",
required = true, required = true,
@ -64,32 +69,36 @@ public class Application {
value = "List of application tags") value = "List of application tags")
private List<String> tags; private List<String> tags;
@ApiModelProperty(name = "user",
value = "Application creating user")
private User user;
@ApiModelProperty(name = "unrestrictedRoles", @ApiModelProperty(name = "unrestrictedRoles",
value = "List of roles that users should have to access the application") value = "List of roles that users should have to access the application")
private List<String> unrestrictedRoles; private List<String> unrestrictedRoles;
@ApiModelProperty(name = "isRestricted",
value = "If unrestricted roles are defined then isRestricted value is true otherwise it is false")
private boolean isRestricted;
@ApiModelProperty(name = "deviceTypeId", @ApiModelProperty(name = "deviceTypeId",
value = "Id of the Related device type of the application", value = "Id of the Related device type of the application",
example = "1, 2, 3") example = "1, 2, 3")
private int deviceTypeId; private int deviceTypeId;
@ApiModelProperty(name = "deviceType",
@ApiModelProperty(name = "deviceTypeName",
value = "Related device type of the application", value = "Related device type of the application",
required = true, required = true,
example = "IoS, Android, Arduino, RaspberryPi etc") example = "IoS, Android, Arduino, RaspberryPi etc")
private String deviceType; private String deviceTypeName;
@ApiModelProperty(name = "applicationReleases", @ApiModelProperty(name = "appRating",
value = "Rating of the aplication")
private int appRating;
@ApiModelProperty(name = "status",
value = "Application status",
required = true,
example = "REMOVED, ACTIVE")
private String status;
@ApiModelProperty(name = "applicationReleaseDTOs",
value = "List of application releases", value = "List of application releases",
required = true) required = true)
private List<ApplicationRelease> applicationReleases; private List<ApplicationReleaseDTO> applicationReleaseDTOs;
public int getId() { public int getId() {
return id; return id;
@ -119,14 +128,6 @@ public class Application {
this.tags = tags; this.tags = tags;
} }
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getType() { public String getType() {
return type; return type;
} }
@ -151,20 +152,12 @@ public class Application {
this.paymentCurrency = paymentCurrency; this.paymentCurrency = paymentCurrency;
} }
public boolean getIsRestricted() { public List<ApplicationReleaseDTO> getApplicationReleaseDTOs() {
return isRestricted; return applicationReleaseDTOs;
} }
public void setIsRestricted(boolean isRestricted) { public void setApplicationReleaseDTOs(List<ApplicationReleaseDTO> applicationReleaseDTOs) {
this.isRestricted = isRestricted; this.applicationReleaseDTOs = applicationReleaseDTOs;
}
public List<ApplicationRelease> getApplicationReleases() {
return applicationReleases;
}
public void setApplicationReleases(List<ApplicationRelease> applicationReleases) {
this.applicationReleases = applicationReleases;
} }
public List<String> getUnrestrictedRoles() { public List<String> getUnrestrictedRoles() {
@ -175,13 +168,11 @@ public class Application {
this.unrestrictedRoles = unrestrictedRoles; this.unrestrictedRoles = unrestrictedRoles;
} }
public String getDeviceType() { public String getDeviceTypeName() {
return deviceType; return deviceTypeName;
} }
public void setDeviceType(String deviceType) { public void setDeviceTypeName(String deviceTypeName) { this.deviceTypeName = deviceTypeName; }
this.deviceType = deviceType;
}
public int getDeviceTypeId() { public int getDeviceTypeId() {
return deviceTypeId; return deviceTypeId;
@ -190,4 +181,16 @@ public class Application {
public void setDeviceTypeId(int deviceTypeId) { public void setDeviceTypeId(int deviceTypeId) {
this.deviceTypeId = deviceTypeId; this.deviceTypeId = deviceTypeId;
} }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public int getAppRating() { return appRating; }
public void setAppRating(int appRating) { this.appRating = appRating; }
} }

View File

@ -16,18 +16,24 @@
* under the License. * under the License.
* *
*/ */
package org.wso2.carbon.device.application.mgt.common; package org.wso2.carbon.device.application.mgt.common.dto;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
@ApiModel(value = "ApplicationRelease", description = "This class holds the details when releasing an Application to application store") @ApiModel(value = "ApplicationReleaseDTO", description = "This class holds the details when releasing an ApplicationDTO to application store")
public class ApplicationRelease { @JsonIgnoreProperties({"appHashValue"})
public class ApplicationReleaseDTO {
@ApiModelProperty(name = "id", @ApiModelProperty(name = "id",
value = "ID of the application release") value = "ID of the application release")
private int id; private int id;
@ApiModelProperty(name = "description",
value = "Description of the application release")
private String description;
@ApiModelProperty(name = "version", @ApiModelProperty(name = "version",
value = "Version of the application release") value = "Version of the application release")
private String version; private String version;
@ -36,29 +42,29 @@ public class ApplicationRelease {
value = "UUID of the application release") value = "UUID of the application release")
private String uuid; private String uuid;
@ApiModelProperty(name = "appStoredLoc", @ApiModelProperty(name = "installerName",
value = "Application storing location") value = "ApplicationDTO storing location")
private String appStoredLoc; private String installerName;
@ApiModelProperty(name = "bannerLoc", @ApiModelProperty(name = "bannerName",
value = "Banner file storing location") value = "Banner file storing location")
private String bannerLoc; private String bannerName;
@ApiModelProperty(name = "screenshotLoc1", @ApiModelProperty(name = "iconName",
value = "Screenshot storing location")
private String screenshotLoc1;
@ApiModelProperty(name = "screenshotLoc2",
value = "Screenshot storing location")
private String screenshotLoc2;
@ApiModelProperty(name = "screenshotLoc3",
value = "Screenshot storing location")
private String screenshotLoc3;
@ApiModelProperty(name = "iconLoc",
value = "icon file storing location") value = "icon file storing location")
private String iconLoc; private String iconName;
@ApiModelProperty(name = "screenshotName1",
value = "Screenshot storing location")
private String screenshotName1;
@ApiModelProperty(name = "screenshotName2",
value = "Screenshot storing location")
private String screenshotName2;
@ApiModelProperty(name = "screenshotName3",
value = "Screenshot storing location")
private String screenshotName3;
@ApiModelProperty(name = "releaseType", @ApiModelProperty(name = "releaseType",
value = "Release type of the application release", value = "Release type of the application release",
@ -78,7 +84,7 @@ public class ApplicationRelease {
@ApiModelProperty(name = "isSharedWithAllTenants", @ApiModelProperty(name = "isSharedWithAllTenants",
value = "If application release is shared with all tenants it is eqal to 1 otherwise 0", value = "If application release is shared with all tenants it is eqal to 1 otherwise 0",
required = true) required = true)
private int isSharedWithAllTenants; private boolean isSharedWithAllTenants;
@ApiModelProperty(name = "metaData", @ApiModelProperty(name = "metaData",
value = "Meta data of the application release", value = "Meta data of the application release",
@ -97,14 +103,21 @@ public class ApplicationRelease {
value = "URL which is used for WEB-CLIP") value = "URL which is used for WEB-CLIP")
private String url; private String url;
@ApiModelProperty(name = "lifecycleState", @ApiModelProperty(name = "supportedOsVersions",
value = "Latest Lifecycle state of the application release") value = "ApplicationDTO release supported OS versions")
private LifecycleState lifecycleState; private String supportedOsVersions;
@ApiModelProperty(name = "currentState",
value = "Current state of the application release")
private String currentState;
@ApiModelProperty(name = "packageName", @ApiModelProperty(name = "packageName",
value = "Application bundle identifier") value = "ApplicationDTO bundle identifier")
private String packageName; private String packageName;
public ApplicationReleaseDTO() {
}
public int getRatedUsers() { public int getRatedUsers() {
return ratedUsers; return ratedUsers;
} }
@ -149,7 +162,7 @@ public class ApplicationRelease {
this.appHashValue = appHashValue; this.appHashValue = appHashValue;
} }
public void setIsSharedWithAllTenants(int isSharedWithAllTenants) { public void setIsSharedWithAllTenants(boolean isSharedWithAllTenants) {
this.isSharedWithAllTenants = isSharedWithAllTenants; this.isSharedWithAllTenants = isSharedWithAllTenants;
} }
@ -177,60 +190,58 @@ public class ApplicationRelease {
return appHashValue; return appHashValue;
} }
public int getIsSharedWithAllTenants() { public boolean getIsSharedWithAllTenants() { return isSharedWithAllTenants; }
return isSharedWithAllTenants;
}
public String getMetaData() { public String getMetaData() {
return metaData; return metaData;
} }
public String getAppStoredLoc() { public String getInstallerName() {
return appStoredLoc; return installerName;
} }
public void setAppStoredLoc(String appStoredLoc) { public void setInstallerName(String installerName) {
this.appStoredLoc = appStoredLoc; this.installerName = installerName;
} }
public String getBannerLoc() { public String getBannerName() {
return bannerLoc; return bannerName;
} }
public void setBannerLoc(String bannerLoc) { public void setBannerName(String bannerName) {
this.bannerLoc = bannerLoc; this.bannerName = bannerName;
} }
public String getScreenshotLoc1() { public String getScreenshotName1() {
return screenshotLoc1; return screenshotName1;
} }
public void setScreenshotLoc1(String screenshotLoc1) { public void setScreenshotName1(String screenshotName1) {
this.screenshotLoc1 = screenshotLoc1; this.screenshotName1 = screenshotName1;
} }
public String getScreenshotLoc2() { public String getScreenshotName2() {
return screenshotLoc2; return screenshotName2;
} }
public void setScreenshotLoc2(String screenshotLoc2) { public void setScreenshotName2(String screenshotName2) {
this.screenshotLoc2 = screenshotLoc2; this.screenshotName2 = screenshotName2;
} }
public String getScreenshotLoc3() { public String getScreenshotName3() {
return screenshotLoc3; return screenshotName3;
} }
public void setScreenshotLoc3(String screenshotLoc3) { public void setScreenshotName3(String screenshotName3) {
this.screenshotLoc3 = screenshotLoc3; this.screenshotName3 = screenshotName3;
} }
public String getIconLoc() { public String getIconName() {
return iconLoc; return iconName;
} }
public void setIconLoc(String iconLoc) { public void setIconName(String iconName) {
this.iconLoc = iconLoc; this.iconName = iconName;
} }
public String getUrl() { public String getUrl() {
@ -241,14 +252,6 @@ public class ApplicationRelease {
this.url = url; this.url = url;
} }
public LifecycleState getLifecycleState() {
return lifecycleState;
}
public void setLifecycleState(LifecycleState lifecycleState) {
this.lifecycleState = lifecycleState;
}
public void setPackageName(String packageName) { public void setPackageName(String packageName) {
this.packageName = packageName; this.packageName = packageName;
} }
@ -256,4 +259,16 @@ public class ApplicationRelease {
public String getPackageName() { public String getPackageName() {
return packageName; return packageName;
} }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public String getSupportedOsVersions() { return supportedOsVersions; }
public void setSupportedOsVersions(String supportedOsVersions) { this.supportedOsVersions = supportedOsVersions; }
public String getCurrentState() { return currentState; }
public void setCurrentState(String currentState) { this.currentState = currentState; }
} }

View File

@ -0,0 +1,38 @@
package org.wso2.carbon.device.application.mgt.common.dto;/* Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
public class CategoryDTO {
int id;
String categoryName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
}

View File

@ -16,7 +16,7 @@
* under the License. * under the License.
* *
*/ */
package org.wso2.carbon.device.application.mgt.common; package org.wso2.carbon.device.application.mgt.common.dto;
import java.sql.Timestamp; import java.sql.Timestamp;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
@ -24,8 +24,8 @@ import io.swagger.annotations.ApiModelProperty;
import java.util.List; import java.util.List;
@ApiModel(value = "LifecycleState", description = "LifecycleState represents the Lifecycle state for an application release") @ApiModel(value = "LifecycleStateDTO", description = "LifecycleStateDTO represents the Lifecycle state for an application release")
public class LifecycleState { public class LifecycleStateDTO {
@ApiModelProperty(name = "id", @ApiModelProperty(name = "id",
value = "ID of the application release lifecycle", value = "ID of the application release lifecycle",

View File

@ -0,0 +1,39 @@
package org.wso2.carbon.device.application.mgt.common.dto;/* Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
public class TagDTO {
int id;
String tagName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTagName() {
return tagName;
}
public void setTagName(String tagName) {
this.tagName = tagName;
}
}

View File

@ -0,0 +1,131 @@
package org.wso2.carbon.device.application.mgt.common.response;/* Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import io.swagger.annotations.ApiModelProperty;
import java.util.List;
public class Application {
@ApiModelProperty(name = "id",
value = "ID of the application",
required = true)
private int id;
@ApiModelProperty(name = "name",
value = "Name of the application",
required = true)
private String name;
@ApiModelProperty(name = "description",
value = "Description of the application",
required = true)
private String description;
@ApiModelProperty(name = "appCategory",
value = "CategoryDTO of the application",
required = true,
example = "Educational, Gaming, Travel, Entertainment etc")
private String appCategory;
@ApiModelProperty(name = "type",
value = "Type of the application",
required = true,
example = "ENTERPRISE, PUBLIC, WEB, WEB_CLIP etc")
private String type;
@ApiModelProperty(name = "subType",
value = "Subscription type of the application",
required = true,
example = "PAID, FREE")
private String subType;
@ApiModelProperty(name = "paymentCurrency",
value = "Payment currency of the application",
required = true,
example = "$")
private String paymentCurrency;
@ApiModelProperty(name = "tags",
value = "List of application tags")
private List<String> tags;
@ApiModelProperty(name = "unrestrictedRoles",
value = "List of roles that users should have to access the application")
private List<String> unrestrictedRoles;
@ApiModelProperty(name = "deviceType",
value = "Related device type of the application",
required = true,
example = "IoS, Android, Arduino, RaspberryPi etc")
private String deviceType;
@ApiModelProperty(name = "applicationReleases",
value = "List of application releases",
required = true)
private List<ApplicationRelease> applicationReleases;
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 getAppCategory() {
return appCategory;
}
public void setAppCategory(String appCategory) {
this.appCategory = appCategory;
}
public List<String> getTags() { return tags; }
public void setTags(List<String> tags) { this.tags = tags; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
public String getSubType() { return subType; }
public void setSubType(String subType) { this.subType = subType; }
public String getPaymentCurrency() { return paymentCurrency; }
public void setPaymentCurrency(String paymentCurrency) { this.paymentCurrency = paymentCurrency; }
public List<ApplicationRelease> getApplicationReleases() { return applicationReleases; }
public void setApplicationReleases(List<ApplicationRelease> applicationReleases) {
this.applicationReleases = applicationReleases; }
public List<String> getUnrestrictedRoles() { return unrestrictedRoles; }
public void setUnrestrictedRoles(List<String> unrestrictedRoles) { this.unrestrictedRoles = unrestrictedRoles; }
public String getDeviceType() { return deviceType; }
public void setDeviceType(String deviceType) { this.deviceType = deviceType; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
}

View File

@ -0,0 +1,175 @@
/*
* 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.response;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "ApplicationReleaseDTO", description = "This class holds the details when releasing an ApplicationDTO to application store")
public class ApplicationRelease {
@ApiModelProperty(name = "description",
value = "Description of the application release")
private String description;
@ApiModelProperty(name = "version",
value = "Version of the application release")
private String version;
@ApiModelProperty(name = "uuid",
value = "UUID of the application release")
private String uuid;
@ApiModelProperty(name = "installerPath",
value = "ApplicationDTO storing location")
private String installerPath;
@ApiModelProperty(name = "bannerPath",
value = "Banner file storing location")
private String bannerPath;
@ApiModelProperty(name = "iconPath",
value = "icon file storing location")
private String iconPath;
@ApiModelProperty(name = "screenshotPath1",
value = "Screenshot storing location")
private String screenshotPath1;
@ApiModelProperty(name = "screenshotPath2",
value = "Screenshot storing location")
private String screenshotPath2;
@ApiModelProperty(name = "screenshotPath3",
value = "Screenshot storing location")
private String screenshotPath3;
@ApiModelProperty(name = "releaseType",
value = "Release type of the application release",
required = true,
example = "alpha, beta etc")
private String releaseType;
@ApiModelProperty(name = "price",
value = "Price of the application release",
required = true)
private Double price;
@ApiModelProperty(name = "isSharedWithAllTenants",
value = "If application release is shared with all tenants it is eqal to 1 otherwise 0",
required = true)
private boolean isSharedWithAllTenants;
@ApiModelProperty(name = "metaData",
value = "Meta data of the application release",
required = true)
private String metaData;
@ApiModelProperty(name = "url",
value = "URL which is used for WEB-CLIP")
private String url;
@ApiModelProperty(name = "supportedOsVersions",
value = "ApplicationDTO release supported OS versions")
private String supportedOsVersions;
public String getReleaseType() {
return releaseType;
}
public void setReleaseType(String releaseType) {
this.releaseType = releaseType;
}
public void setIsSharedWithAllTenants(boolean isSharedWithAllTenants) {
this.isSharedWithAllTenants = isSharedWithAllTenants;
}
public void setMetaData(String metaData) {
this.metaData = metaData;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public boolean getIsSharedWithAllTenants() {
return isSharedWithAllTenants;
}
public String getMetaData() {
return metaData;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public String getVersion() { return version; }
public void setVersion(String version) { this.version = version; }
public String getUuid() { return uuid; }
public void setUuid(String uuid) { this.uuid = uuid; }
public String getInstallerPath() { return installerPath; }
public void setInstallerPath(String installerPath) { this.installerPath = installerPath; }
public String getBannerPath() { return bannerPath; }
public void setBannerPath(String bannerPath) { this.bannerPath = bannerPath; }
public String getIconPath() { return iconPath; }
public void setIconPath(String iconPath) { this.iconPath = iconPath; }
public String getScreenshotPath1() { return screenshotPath1; }
public void setScreenshotPath1(String screenshotPath1) { this.screenshotPath1 = screenshotPath1; }
public String getScreenshotPath2() { return screenshotPath2; }
public void setScreenshotPath2(String screenshotPath2) { this.screenshotPath2 = screenshotPath2; }
public String getScreenshotPath3() { return screenshotPath3; }
public void setScreenshotPath3(String screenshotPath3) { this.screenshotPath3 = screenshotPath3; }
public boolean isSharedWithAllTenants() { return isSharedWithAllTenants; }
public void setSharedWithAllTenants(boolean sharedWithAllTenants) { isSharedWithAllTenants = sharedWithAllTenants; }
public String getSupportedOsVersions() { return supportedOsVersions; }
public void setSupportedOsVersions(String supportedOsVersions) { this.supportedOsVersions = supportedOsVersions; }
}

View File

@ -18,15 +18,19 @@
*/ */
package org.wso2.carbon.device.application.mgt.common.services; package org.wso2.carbon.device.application.mgt.common.services;
import org.wso2.carbon.device.application.mgt.common.Application; import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.wso2.carbon.device.application.mgt.common.ApplicationArtifact;
import org.wso2.carbon.device.application.mgt.common.dto.ApplicationDTO;
import org.wso2.carbon.device.application.mgt.common.ApplicationList; 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.dto.ApplicationReleaseDTO;
import org.wso2.carbon.device.application.mgt.common.Filter; import org.wso2.carbon.device.application.mgt.common.Filter;
import org.wso2.carbon.device.application.mgt.common.LifecycleState; import org.wso2.carbon.device.application.mgt.common.dto.LifecycleStateDTO;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.RequestValidatingException; import org.wso2.carbon.device.application.mgt.common.exception.RequestValidatingException;
import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException; import org.wso2.carbon.device.application.mgt.common.response.Application;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.application.mgt.common.response.ApplicationRelease;
import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationReleaseWrapper;
import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationWrapper;
import java.io.InputStream; import java.io.InputStream;
import java.util.List; import java.util.List;
@ -39,27 +43,28 @@ public interface ApplicationManager {
/** /**
* Creates an application. * Creates an application.
* *
* @param application Application that need to be created. * @param applicationWrapper Application that need to be created.
* @return Created application * @return Created application
* @throws ApplicationManagementException Application Management Exception * @throws ApplicationManagementException ApplicationDTO Management Exception
*/ */
Application createApplication(Application application) Application createApplication(ApplicationWrapper applicationWrapper, ApplicationArtifact applicationArtifact)
throws ApplicationManagementException, RequestValidatingException; throws ApplicationManagementException, RequestValidatingException;
/** /**
* Updates an already existing application. * Updates an already existing application.
* *
* @param application Application that need to be updated. * @param applicationWrapper Application that need to be updated.
* @param applicationId ID of the application
* @return Updated Application * @return Updated Application
* @throws ApplicationManagementException Application Management Exception * @throws ApplicationManagementException ApplicationDTO Management Exception
*/ */
Application updateApplication(Application application) throws ApplicationManagementException; void updateApplication(int applicationId, ApplicationWrapper applicationWrapper) throws ApplicationManagementException;
/** /**
* Delete an application identified by the unique ID. * Delete an application identified by the unique ID.
* *
* @param applicationId ID for tha application * @param applicationId ID for tha application
* @throws ApplicationManagementException Application Management Exception * @throws ApplicationManagementException ApplicationDTO Management Exception
*/ */
List<String> deleteApplication(int applicationId) throws ApplicationManagementException; List<String> deleteApplication(int applicationId) throws ApplicationManagementException;
@ -68,154 +73,147 @@ public interface ApplicationManager {
* *
* @param applicationId ID of tha application * @param applicationId ID of tha application
* @param releaseUuid UUID of tha application release * @param releaseUuid UUID of tha application release
* @param handleConnections Whether it is necessary handle DB connections. * @throws ApplicationManagementException ApplicationDTO Management Exception
* @throws ApplicationManagementException Application Management Exception
*/ */
String deleteApplicationRelease(int applicationId, String releaseUuid, boolean handleConnections) throws String deleteApplicationRelease(int applicationId, String releaseUuid) throws ApplicationManagementException;
ApplicationManagementException;
/** /**
* To get the applications based on the search filter. * To get the applications based on the search filter.
* *
* @param filter Search filter * @param filter Search filter
* @return Applications that matches the given filter criteria. * @return Applications that matches the given filter criteria.
* @throws ApplicationManagementException Application Management Exception * @throws ApplicationManagementException ApplicationDTO Management Exception
*/ */
ApplicationList getApplications(Filter filter) throws ApplicationManagementException; ApplicationList getApplications(Filter filter) throws ApplicationManagementException;
/** /**
* To get the applications based on the search filter. * To get the ApplicationDTO for given Id.
* *
* @param appId id of the application * @param id id of the ApplicationDTO
* @return Application release which is published and release of the Application(appId). * @param state state of the ApplicationDTO
* @throws ApplicationManagementException Application Management Exception * @return the ApplicationDTO identified by the ID
*/ * @throws ApplicationManagementException ApplicationDTO Management Exception.
String getUuidOfLatestRelease(int appId) throws ApplicationManagementException;
/**
* To get the Application for given Id.
*
* @param id id of the Application
* @param state state of the Application
* @return the Application identified by the ID
* @throws ApplicationManagementException Application Management Exception.
*/ */
Application getApplicationById(int id, String state) throws ApplicationManagementException; Application getApplicationById(int id, String state) throws ApplicationManagementException;
/** /**
* To get the Application for given application relase UUID. * To get the ApplicationDTO for given application relase UUID.
* *
* @param uuid UUID of the Application * @param uuid UUID of the ApplicationDTO
* @param state state of the Application * @param state state of the ApplicationDTO
* @return the Application identified by the ID * @return the ApplicationDTO identified by the ID
* @throws ApplicationManagementException Application Management Exception. * @throws ApplicationManagementException ApplicationDTO Management Exception.
*/ */
Application getApplicationByUuid(String uuid, String state) throws ApplicationManagementException; ApplicationDTO getApplicationByUuid(String uuid, String state) throws ApplicationManagementException;
/** /**
* To get an application associated with the release. * To get an application associated with the release.
* *
* @param appReleaseUUID UUID of the app release * @param appReleaseUUID UUID of the app release
* @return {@link Application} associated with the release * @return {@link ApplicationDTO} associated with the release
* @throws ApplicationManagementException If unable to retrieve {@link Application} associated with the given UUID * @throws ApplicationManagementException If unable to retrieve {@link ApplicationDTO} associated with the given UUID
*/ */
Application getApplicationByRelease(String appReleaseUUID) throws ApplicationManagementException; ApplicationDTO getApplicationByRelease(String appReleaseUUID) throws ApplicationManagementException;
/** /**
* To get Application with the given UUID. * To get all the releases of a particular ApplicationDTO.
* *
* @param appId ID of the Application * @param applicationId ID of the ApplicationDTO .
* @return the boolean value, whether application exist or not * @param releaseUuid UUID of the ApplicationDTO Release.
* @throws ApplicationManagementException Application Management Exception. * @return the LifecycleStateDTO of the ApplicationDTO releases related with the particular ApplicationDTO.
* @throws ApplicationManagementException ApplicationDTO Management Exception.
*/ */
boolean verifyApplicationExistenceById(int appId) throws ApplicationManagementException; LifecycleStateDTO getLifecycleState(int applicationId, String releaseUuid) throws ApplicationManagementException;
/** /**
* To get Application with the given UUID. * To get all the releases of a particular ApplicationDTO.
* *
* @return the boolean value, whether user has assigned unrestricted roles to access the application * @param applicationId ID of the ApplicationDTO.
* * @throws ApplicationManagementException Application Management Exception. * @param releaseUuid UUID of the ApplicationDTO Release.
*/
Boolean isUserAllowable(List<String> unrestrictedRoles, String userName) throws ApplicationManagementException;
/**
* To get all the releases of a particular Application.
*
* @param applicationId ID of the Application .
* @param releaseUuid UUID of the Application Release.
* @return the LifecycleState of the Application releases related with the particular Application.
* @throws ApplicationManagementException Application Management Exception.
*/
LifecycleState getLifecycleState(int applicationId, String releaseUuid) throws ApplicationManagementException;
/**
* To get all the releases of a particular Application.
*
* @param applicationId ID of the Application.
* @param releaseUuid UUID of the Application Release.
* @param state Lifecycle state to change the app * @param state Lifecycle state to change the app
* @throws ApplicationManagementException Application Management Exception. * @throws ApplicationManagementException ApplicationDTO Management Exception.
*/ */
void changeLifecycleState(int applicationId, String releaseUuid, LifecycleState state) void changeLifecycleState(int applicationId, String releaseUuid, LifecycleStateDTO state)
throws ApplicationManagementException; throws ApplicationManagementException;
/**
* Get the application if application is an accessible one.
*
* @param applicationId ID of the Application.
* @throws ApplicationManagementException Application Management Exception.
*/
Application getApplicationIfAccessible(int applicationId) throws ApplicationManagementException;
/** /**
* To update release images such as icons, banner and screenshots. * To update release images such as icons, banner and screenshots.
* *
* @param appId ID of the Application * @param uuid uuid of the ApplicationDTO
* @param uuid uuid of the Application * @param applicationArtifact Application artifact that contains names and input streams of the application artifacts.
* @param iconFileStream icon file of the release * @throws ApplicationManagementException ApplicationDTO Management Exception.
* @param bannerFileStream bannerFileStream of the release.
* @param attachments screenshot attachments of the release
* @return Updated Application Release.
* @throws ApplicationManagementException Application Management Exception.
*/ */
ApplicationRelease updateApplicationImageArtifact(int appId, String uuid, InputStream iconFileStream, InputStream void updateApplicationImageArtifact(String uuid, ApplicationArtifact applicationArtifact) throws ApplicationManagementException;
bannerFileStream, List<InputStream> attachments)
throws ApplicationManagementException, ResourceManagementException;
/** /**
* To update release images. * To update release images.
* *
* @param appId ID of the Application * @param deviceType Application artifact compatible device type name.
* @param uuid uuid of the Application * @param appType Type of the application.
* @param binaryFile binaryFile of the release. * @param uuid uuid of the ApplicationDTO
* @return Updated Application Release. * @param applicationArtifact Application artifact that contains names and input streams of the application artifacts.
* @throws ApplicationManagementException Application Management Exception. * @throws ApplicationManagementException ApplicationDTO Management Exception.
*/ */
ApplicationRelease updateApplicationArtifact(int appId, String uuid, InputStream binaryFile) void updateApplicationArtifact(String deviceType, String appType, String uuid,
throws ApplicationManagementException, ResourceManagementException, RequestValidatingException, DeviceManagementException; ApplicationArtifact applicationArtifact) throws ApplicationManagementException;
/** /**
* To verify whether application release is acceptable to update or not. * To create an application release for an ApplicationDTO.
* *
* @param appId ID of the Application * @param applicationId ID of the ApplicationDTO
* @param appReleaseUuid UUID of the ApplicationRelease * @param applicationReleaseWrapper ApplicatonRelease that need to be be created.
* @return Updated Application Release.
* @throws ApplicationManagementException Application Management Exception.
*/
boolean isAcceptableAppReleaseUpdate(int appId, String appReleaseUuid)
throws ApplicationManagementException;
/**
* To create an application release for an Application.
*
* @param applicationId ID of the Application
* @param applicationRelease ApplicatonRelease that need to be be created.
* @return the unique id of the application release, if the application release succeeded else -1 * @return the unique id of the application release, if the application release succeeded else -1
*/ */
ApplicationRelease createRelease(int applicationId, ApplicationRelease applicationRelease) ApplicationRelease createRelease(int applicationId, ApplicationReleaseWrapper applicationReleaseWrapper,
throws ApplicationManagementException; ApplicationArtifact applicationArtifact) throws ApplicationManagementException;
/***
*
* @param applicationId ID of the application
* @param releaseUuid UUID of the application release
* @param deviceType Supported device type of the application
* @param applicationRelease {@link ApplicationReleaseDTO}
* @param binaryFileStram {@link InputStream} of the binary file
* @param iconFileStream {@link InputStream} of the icon
* @param bannerFileStream {@link InputStream} of the banner
* @param attachments {@link List} of {@link InputStream} of attachments
* @return If the application release is updated correctly True returns, otherwise retuen False
*/
boolean updateRelease(int applicationId, String releaseUuid, String deviceType, ApplicationReleaseDTO applicationRelease,
InputStream binaryFileStram, InputStream iconFileStream, InputStream bannerFileStream,
List<InputStream> attachments) throws ApplicationManagementException;
/***
* To validate the application creating request
*
* @param applicationWrapper {@link ApplicationDTO}
* @throws RequestValidatingException if the payload contains invalid inputs.
*/
void validateAppCreatingRequest(ApplicationWrapper applicationWrapper) throws RequestValidatingException;
/***
*
* @param applicationReleaseWrapper {@link ApplicationReleaseDTO}
* @param applicationType Type of the application
* @throws RequestValidatingException throws if payload does not satisfy requrements.
*/
void validateReleaseCreatingRequest(ApplicationReleaseWrapper applicationReleaseWrapper, String applicationType)
throws RequestValidatingException;
/***
*
* @param iconFile Icon file for the application.
* @param bannerFile Banner file for the application.
* @param attachmentList Screenshot list.
* @throws RequestValidatingException If request doesn't contains required attachments.
*/
void validateImageArtifacts(Attachment iconFile, Attachment bannerFile, List<Attachment> attachmentList)
throws RequestValidatingException;
void validateBinaryArtifact(Attachment binaryFile, String applicationType) throws RequestValidatingException;
void addAplicationCategories(List<String> categories) throws ApplicationManagementException;
} }

View File

@ -19,8 +19,8 @@
package org.wso2.carbon.device.application.mgt.common.services; package org.wso2.carbon.device.application.mgt.common.services;
import org.wso2.carbon.device.application.mgt.common.ApplicationRelease; import org.wso2.carbon.device.application.mgt.common.ApplicationInstaller;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationStorageManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationStorageManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.RequestValidatingException; import org.wso2.carbon.device.application.mgt.common.exception.RequestValidatingException;
import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException;
@ -29,59 +29,56 @@ import java.io.InputStream;
import java.util.List; import java.util.List;
/** /**
* This manages all the storage related requirements of Application. * This manages all the storage related requirements of ApplicationDTO.
*/ */
public interface ApplicationStorageManager { public interface ApplicationStorageManager {
/** /**
* To upload image artifacts related with an Application. * To upload image artifacts related with an ApplicationDTO.
* *
* @param applicationRelease ApplicationRelease Object * @param applicationRelease ApplicationReleaseDTO Object
* @param iconFile Icon File input stream * @param iconFile Icon File input stream
* @param bannerFile Banner File input stream * @param bannerFile Banner File input stream
* @throws ResourceManagementException Resource Management Exception. * @throws ResourceManagementException Resource Management Exception.
*/ */
ApplicationRelease uploadImageArtifacts(ApplicationRelease applicationRelease, ApplicationReleaseDTO uploadImageArtifacts(ApplicationReleaseDTO applicationRelease,
InputStream iconFile, InputStream bannerFile, List<InputStream> screenshots) throws ResourceManagementException; InputStream iconFile, InputStream bannerFile, List<InputStream> screenshots) throws ResourceManagementException;
/** /**
* To upload image artifacts related with an Application. * To upload image artifacts related with an ApplicationDTO.
* *
* @param applicationRelease Release of the application * @param applicationRelease Release of the application
* @param iconFile Icon File input stream
* @param bannerFile Banner File input stream
* @param screenshots Input Streams of screenshots
* @throws ResourceManagementException Resource Management Exception. * @throws ResourceManagementException Resource Management Exception.
*/ */
ApplicationRelease updateImageArtifacts(ApplicationRelease applicationRelease, InputStream iconFile, void deleteImageArtifacts(ApplicationReleaseDTO applicationRelease) throws ResourceManagementException;
InputStream bannerFile, List<InputStream> screenshots)
throws ResourceManagementException, ApplicationManagementException; ApplicationInstaller getAppInstallerData(InputStream binaryFile, String deviceType)
throws ApplicationStorageManagementException;
/** /**
* To upload release artifacts for an Application. * To upload release artifacts for an ApplicationDTO.
* *
* @param applicationRelease Application Release Object. * @param applicationRelease ApplicationDTO Release Object.
* @param appType Application Type. * @param appType ApplicationDTO Type.
* @param deviceType Compatible device tipe of the application. * @param deviceType Compatible device tipe of the application.
* @param binaryFile Binary File for the release. * @param binaryFile Binary File for the release.
* @throws ResourceManagementException Resource Management Exception. * @throws ResourceManagementException Resource Management Exception.
*/ */
ApplicationRelease uploadReleaseArtifact(ApplicationRelease applicationRelease, String appType, String deviceType, ApplicationReleaseDTO uploadReleaseArtifact(ApplicationReleaseDTO applicationRelease, String appType, String deviceType,
InputStream binaryFile) throws ResourceManagementException, RequestValidatingException; InputStream binaryFile) throws ResourceManagementException;
/** /**
* To upload release artifacts for an Application. * To upload release artifacts for an ApplicationDTO.
* *
* @param applicationRelease applicationRelease Application release of a particular application. * @param applicationReleaseDTO applicationRelease ApplicationDTO release of a particular application.
* @param appType Type of the application. * @param deletingAppHashValue Hash value of the deleting application release.
* @param deviceType Compatible device tipe of the application.
* @param binaryFile Binary File for the release.
* @throws ApplicationStorageManagementException Resource Management Exception. * @throws ApplicationStorageManagementException Resource Management Exception.
*/ */
ApplicationRelease updateReleaseArtifacts(ApplicationRelease applicationRelease, String appType, String deviceType, void copyImageArtifactsAndDeleteInstaller(String deletingAppHashValue,
InputStream binaryFile) throws ApplicationStorageManagementException, RequestValidatingException; ApplicationReleaseDTO applicationReleaseDTO) throws ApplicationStorageManagementException;
/** /**
* To delete the artifacts related with particular Application Release. * To delete the artifacts related with particular ApplicationDTO Release.
* *
* @param directoryPath Hash value of the application artifact. * @param directoryPath Hash value of the application artifact.
* @throws ApplicationStorageManagementException Not Found Exception. * @throws ApplicationStorageManagementException Not Found Exception.
@ -89,11 +86,18 @@ public interface ApplicationStorageManager {
void deleteApplicationReleaseArtifacts(String directoryPath) throws ApplicationStorageManagementException; void deleteApplicationReleaseArtifacts(String directoryPath) throws ApplicationStorageManagementException;
/** /**
* To delete all release artifacts related with particular Application Release. * To delete all release artifacts related with particular ApplicationDTO Release.
* *
* @param directoryPaths Hash values of the Application. * @param directoryPaths Hash values of the ApplicationDTO.
* @throws ApplicationStorageManagementException Application Storage Management Exception * @throws ApplicationStorageManagementException ApplicationDTO Storage Management Exception
*/ */
void deleteAllApplicationReleaseArtifacts(List<String> directoryPaths) throws ApplicationStorageManagementException; void deleteAllApplicationReleaseArtifacts(List<String> directoryPaths) throws ApplicationStorageManagementException;
/***
* Get the InputStream of the file which is located in filePath
* @param path file path
* @return {@link InputStream}
* @throws ApplicationStorageManagementException throws if an error occurs when accessing the file.
*/
InputStream getFileSttream(String path) throws ApplicationStorageManagementException;
} }

View File

@ -20,12 +20,15 @@ package org.wso2.carbon.device.application.mgt.common.services;
import org.wso2.carbon.device.application.mgt.common.config.UIConfiguration; import org.wso2.carbon.device.application.mgt.common.config.UIConfiguration;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
public interface ConfigManager { import java.io.InputStream;
public interface AppmDataHandler {
/** /**
* Get all review with pagination * Get UI configuration which is defined in the app-manager.xml
* *
* @return {@link UIConfiguration} UI configuration * @return {@link UIConfiguration} UI configuration
* @throws ApplicationManagementException Exceptions of the Application managementt.
*/ */
UIConfiguration getUIConfiguration() throws ApplicationManagementException; UIConfiguration getUIConfiguration();
InputStream getArtifactStream(String uuid, String artifactName) throws ApplicationManagementException;
} }

View File

@ -25,7 +25,7 @@ import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import java.util.List; import java.util.List;
/** /**
* This interface manages all the operations related with Application Subscription. * This interface manages all the operations related with ApplicationDTO Subscription.
*/ */
public interface SubscriptionManager { public interface SubscriptionManager {
/** /**
@ -70,10 +70,10 @@ public interface SubscriptionManager {
/** /**
* To uninstall an application from a given list of devices. * To uninstall an application from a given list of devices.
* @param applicationUUID Application ID * @param applicationUUID ApplicationDTO ID
* @param deviceList Device list * @param deviceList Device list
* @return Failed Device List which the application was unable to uninstall * @return Failed Device List which the application was unable to uninstall
* @throws ApplicationManagementException Application Management Exception * @throws ApplicationManagementException ApplicationDTO Management Exception
*/ */
List<DeviceIdentifier> uninstallApplication(String applicationUUID, List<DeviceIdentifier> deviceList) List<DeviceIdentifier> uninstallApplication(String applicationUUID, List<DeviceIdentifier> deviceList)
throws ApplicationManagementException; throws ApplicationManagementException;

View File

@ -0,0 +1,107 @@
/*
* 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.wrapper;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "ApplicationReleaseDTO", description = "This class holds the details when releasing an ApplicationDTO to application store")
public class ApplicationReleaseWrapper {
@ApiModelProperty(name = "description",
value = "Description of the application release")
private String description;
@ApiModelProperty(name = "releaseType",
value = "Release type of the application release",
required = true,
example = "alpha, beta etc")
private String releaseType;
@ApiModelProperty(name = "price",
value = "Price of the application release",
required = true)
private Double price;
@ApiModelProperty(name = "isSharedWithAllTenants",
value = "If application release is shared with all tenants it is eqal to 1 otherwise 0",
required = true)
private boolean isSharedWithAllTenants;
@ApiModelProperty(name = "metaData",
value = "Meta data of the application release",
required = true)
private String metaData;
@ApiModelProperty(name = "url",
value = "URL which is used for WEB-CLIP")
private String url;
@ApiModelProperty(name = "supportedOsVersions",
value = "ApplicationDTO release supported OS versions")
private String supportedOsVersions;
public String getReleaseType() {
return releaseType;
}
public void setReleaseType(String releaseType) {
this.releaseType = releaseType;
}
public void setIsSharedWithAllTenants(boolean isSharedWithAllTenants) {
this.isSharedWithAllTenants = isSharedWithAllTenants;
}
public void setMetaData(String metaData) {
this.metaData = metaData;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public boolean getIsSharedWithAllTenants() {
return isSharedWithAllTenants;
}
public String getMetaData() {
return metaData;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public String getSupportedOsVersions() { return supportedOsVersions; }
public void setSupportedOsVersions(String supportedOsVersions) { this.supportedOsVersions = supportedOsVersions; }
}

View File

@ -0,0 +1,130 @@
/*
* 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.wrapper;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.List;
@ApiModel(value = "ApplicationWrapper", description = "ApplicationWrapper represents the an ApplicationDTO in ApplicationDTO Store")
public class ApplicationWrapper {
@ApiModelProperty(name = "name",
value = "Name of the application",
required = true)
private String name;
@ApiModelProperty(name = "description",
value = "Description of the application",
required = true)
private String description;
@ApiModelProperty(name = "appCategory",
value = "CategoryDTO of the application",
required = true,
example = "Educational, Gaming, Travel, Entertainment etc")
private String appCategory;
@ApiModelProperty(name = "type",
value = "Type of the application",
required = true,
example = "ENTERPRISE, PUBLIC, WEB, WEB_CLIP etc")
private String type;
@ApiModelProperty(name = "subType",
value = "Subscription type of the application",
required = true,
example = "PAID, FREE")
private String subType;
@ApiModelProperty(name = "paymentCurrency",
value = "Payment currency of the application",
required = true,
example = "$")
private String paymentCurrency;
@ApiModelProperty(name = "tags",
value = "List of application tags")
private List<String> tags;
@ApiModelProperty(name = "unrestrictedRoles",
value = "List of roles that users should have to access the application")
private List<String> unrestrictedRoles;
@ApiModelProperty(name = "deviceType",
value = "Related device type of the application",
required = true,
example = "IoS, Android, Arduino, RaspberryPi etc")
private String deviceType;
@ApiModelProperty(name = "applicationReleaseWrappers",
value = "List of application releases",
required = true)
private List<ApplicationReleaseWrapper> applicationReleaseWrappers;
public String getName() {
return name;
}
public void setName(String name) { this.name = name; }
public String getAppCategory() {
return appCategory;
}
public void setAppCategory(String appCategory) {
this.appCategory = appCategory;
}
public List<String> getTags() { return tags; }
public void setTags(List<String> tags) { this.tags = tags; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
public String getSubType() { return subType; }
public void setSubType(String subType) { this.subType = subType; }
public String getPaymentCurrency() { return paymentCurrency; }
public void setPaymentCurrency(String paymentCurrency) { this.paymentCurrency = paymentCurrency; }
public List<ApplicationReleaseWrapper> getApplicationReleaseWrappers() { return applicationReleaseWrappers; }
public void setApplicationReleaseWrappers(List<ApplicationReleaseWrapper> applicationReleaseWrappers) {
this.applicationReleaseWrappers = applicationReleaseWrappers; }
public List<String> getUnrestrictedRoles() { return unrestrictedRoles; }
public void setUnrestrictedRoles(List<String> unrestrictedRoles) { this.unrestrictedRoles = unrestrictedRoles; }
public String getDeviceType() { return deviceType; }
public void setDeviceType(String deviceType) { this.deviceType = deviceType; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
}

View File

@ -71,7 +71,6 @@
org.wso2.carbon.user.api.*, org.wso2.carbon.user.api.*,
org.wso2.carbon.ndatasource.core, org.wso2.carbon.ndatasource.core,
org.wso2.carbon, org.wso2.carbon,
javax.annotation,
org.xml.sax, org.xml.sax,
org.xml.sax.helpers, org.xml.sax.helpers,
org.apache.commons.io, org.apache.commons.io,
@ -197,6 +196,17 @@
<artifactId>commons-validator</artifactId> <artifactId>commons-validator</artifactId>
<version>1.6</version> <version>1.6</version>
</dependency> </dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>3.2.7</version>
<scope>compile</scope>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -18,6 +18,7 @@
*/ */
package org.wso2.carbon.device.application.mgt.core.config; package org.wso2.carbon.device.application.mgt.core.config;
import org.wso2.carbon.device.application.mgt.common.config.RatingConfiguration;
import org.wso2.carbon.device.application.mgt.common.config.UIConfiguration; import org.wso2.carbon.device.application.mgt.common.config.UIConfiguration;
import org.wso2.carbon.device.application.mgt.core.lifecycle.config.LifecycleState; import org.wso2.carbon.device.application.mgt.core.lifecycle.config.LifecycleState;
@ -44,6 +45,12 @@ public class Configuration {
private UIConfiguration uiConfiguration; private UIConfiguration uiConfiguration;
private List<String> appCategories;
private String artifactDownloadEndpoint;
private RatingConfiguration ratingConfiguration;
@XmlElement(name = "DatasourceName", required = true) @XmlElement(name = "DatasourceName", required = true)
public String getDatasourceName() { public String getDatasourceName() {
return datasourceName; return datasourceName;
@ -74,18 +81,42 @@ public class Configuration {
return lifecycleStates; return lifecycleStates;
} }
public void setLifecycleStates( public void setLifecycleStates(List<LifecycleState> lifecycleStates) {
List<LifecycleState> lifecycleStates) {
this.lifecycleStates = lifecycleStates; this.lifecycleStates = lifecycleStates;
} }
@XmlElement(name = "UIConfigs")
public UIConfiguration getUiConfiguration() { public UIConfiguration getUiConfiguration() {
return uiConfiguration; return uiConfiguration;
} }
@XmlElement(name = "UIConfigs")
public void setUiConfiguration(UIConfiguration uiConfiguration) { public void setUiConfiguration(UIConfiguration uiConfiguration) {
this.uiConfiguration = uiConfiguration; this.uiConfiguration = uiConfiguration;
} }
@XmlElement(name = "RatingConfig")
public RatingConfiguration getRatingConfiguration() { return ratingConfiguration; }
public void setRatingConfiguration(
RatingConfiguration ratingConfiguration) { this.ratingConfiguration = ratingConfiguration; }
@XmlElement(name = "ArtifactDownloadEndpoint", required = true)
public String getArtifactDownloadEndpoint() {
return artifactDownloadEndpoint;
}
public void setArtifactDownloadEndpoint(String artifactDownloadEndpoint) {
this.artifactDownloadEndpoint = artifactDownloadEndpoint;
}
@XmlElementWrapper(name = "AppCategories")
@XmlElement(name = "Category")
public List<String> getAppCategories() {
return appCategories;
}
public void setAppCategories(List<String> appCategories) {
this.appCategories = appCategories;
}
} }

View File

@ -19,31 +19,54 @@
package org.wso2.carbon.device.application.mgt.core.dao; package org.wso2.carbon.device.application.mgt.core.dao;
import org.wso2.carbon.device.application.mgt.common.*; 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.dto.ApplicationDTO;
import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO;
import org.wso2.carbon.device.application.mgt.common.dto.CategoryDTO;
import org.wso2.carbon.device.application.mgt.common.dto.TagDTO;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import java.util.List; import java.util.List;
/** /**
* ApplicationDAO is responsible for handling all the Database related operations related with Application Management. * ApplicationDAO is responsible for handling all the Database related operations related with ApplicationDTO Management.
*/ */
public interface ApplicationDAO { public interface ApplicationDAO {
/** /**
* To create an application. * To create an application.
* *
* @param application Application that need to be created. * @param application ApplicationDTO that need to be created.
* @return Created Application. * @return Created Application.
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
int createApplication(Application application, int deviceId) throws ApplicationManagementDAOException; int createApplication(ApplicationDTO application, int tenantId) throws ApplicationManagementDAOException;
/** /**
* To add tags for a particular application. * To add tags for a particular application.
* *
* @param tags tags that need to be added for a application. * @param tags tags that need to be added for a application.
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
void addTags(List<String> tags, int applicationId, int tenantId) throws ApplicationManagementDAOException; void addTags(List<String> tags, int tenantId) throws ApplicationManagementDAOException;
List<TagDTO> getAllTags(int tenantId) throws ApplicationManagementDAOException;
List<Integer> getTagIdsForTagNames (List<String> tagNames, int tenantId) throws ApplicationManagementDAOException;
void addTagMapping (List<Integer> tagIds, int applicationId, int tenantId) throws ApplicationManagementDAOException;
List<String> getAppTags(int appId, int tenantId) throws ApplicationManagementDAOException;
List<String> getAppCategories (int appId, int tenantId) throws ApplicationManagementDAOException;
List<CategoryDTO> getAllCategories(int tenantId) throws ApplicationManagementDAOException;
void addCategories(List<String> categories, int tenantId) throws ApplicationManagementDAOException;
void addCategoryMapping (List<Integer> categoryIds, int applicationId, int tenantId) throws ApplicationManagementDAOException;
/** /**
* To check application existence. * To check application existence.
@ -51,7 +74,7 @@ public interface ApplicationDAO {
* @param appName appName that need to identify application. * @param appName appName that need to identify application.
* @param type type that need to identify application. * @param type type that need to identify application.
* @param tenantId tenantId that need to identify application. * @param tenantId tenantId that need to identify application.
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
boolean isExistApplication(String appName, String type, int tenantId) throws ApplicationManagementDAOException; boolean isExistApplication(String appName, String type, int tenantId) throws ApplicationManagementDAOException;
@ -59,17 +82,18 @@ public interface ApplicationDAO {
* To get the applications that satisfy the given criteria. * To get the applications that satisfy the given criteria.
* *
* @param filter Filter criteria. * @param filter Filter criteria.
* @param deviceTypeId ID of the device type
* @param tenantId Id of the tenant. * @param tenantId Id of the tenant.
* @return Application list * @return ApplicationDTO list
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
ApplicationList getApplications(Filter filter, int tenantId) throws ApplicationManagementDAOException; List<ApplicationDTO> getApplications(Filter filter, int deviceTypeId, int tenantId) throws ApplicationManagementDAOException;
/** /**
* To get the UUID of latest app release that satisfy the given criteria. * To get the UUID of latest app release that satisfy the given criteria.
* *
* @param appId application id * @param appId application id
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
String getUuidOfLatestRelease(int appId) throws ApplicationManagementDAOException; String getUuidOfLatestRelease(int appId) throws ApplicationManagementDAOException;
@ -80,9 +104,9 @@ public interface ApplicationDAO {
* @param tenantId ID of the tenant. * @param tenantId ID of the tenant.
* @param appType Type of the application. * @param appType Type of the application.
* @return the application * @return the application
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
Application getApplication(String appName, String appType, int tenantId) throws ApplicationManagementDAOException; ApplicationDTO getApplication(String appName, String appType, int tenantId) throws ApplicationManagementDAOException;
/** /**
* To get the application with the given id * To get the application with the given id
@ -90,10 +114,9 @@ public interface ApplicationDAO {
* @param id ID of the application. * @param id ID of the application.
* @param tenantId ID of the tenant. * @param tenantId ID of the tenant.
* @return the application * @return the application
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
Application getApplicationById(String id, int tenantId) throws ApplicationDTO getApplicationById(String id, int tenantId) throws ApplicationManagementDAOException;
ApplicationManagementDAOException;
/** /**
* To get the application with the given id * To get the application with the given id
@ -101,9 +124,9 @@ public interface ApplicationDAO {
* @param applicationId Id of the application to be retrieved. * @param applicationId Id of the application to be retrieved.
* @param tenantId ID of the tenant. * @param tenantId ID of the tenant.
* @return the application * @return the application
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
Application getApplicationById(int applicationId, int tenantId) throws ApplicationManagementDAOException; ApplicationDTO getApplicationById(int applicationId, int tenantId) throws ApplicationManagementDAOException;
/** /**
* To get the application with the given uuid * To get the application with the given uuid
@ -111,9 +134,9 @@ public interface ApplicationDAO {
* @param releaseUuid UUID of the application release. * @param releaseUuid UUID of the application release.
* @param tenantId ID of the tenant. * @param tenantId ID of the tenant.
* @return the application * @return the application
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
Application getApplicationByUUID(String releaseUuid, int tenantId) throws ApplicationManagementDAOException; ApplicationDTO getApplicationByUUID(String releaseUuid, int tenantId) throws ApplicationManagementDAOException;
/** /**
* To get the application with the given uuid * To get the application with the given uuid
@ -121,47 +144,47 @@ public interface ApplicationDAO {
* @param appId ID of the application * @param appId ID of the application
* @param tenantId Tenant Id * @param tenantId Tenant Id
* @return the boolean value * @return the boolean value
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
boolean verifyApplicationExistenceById(int appId, int tenantId) throws ApplicationManagementDAOException; boolean verifyApplicationExistenceById(int appId, int tenantId) throws ApplicationManagementDAOException;
/** /**
* To get the application id of the application specified by the UUID * Verify whether application exist for given application name and device type. Because a name and device type is
* unique for an application.
* *
* @param appName name of the application. * @param appName name of the application.
* @param appType type of the application. * @param deviceTypeId ID of the device type.
* @param tenantId ID of the tenant. * @param tenantId ID of the tenant.
* @return ID of the Application. * @return ID of the ApplicationDTO.
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException Application Management DAO Exception.
*/ */
int getApplicationId(String appName, String appType, int tenantId) throws ApplicationManagementDAOException; boolean isValidAppName(String appName, int deviceTypeId, int tenantId) throws ApplicationManagementDAOException;
/** /**
* To edit the given application. * To edit the given application.
* *
* @param application Application that need to be edited. * @param application ApplicationDTO that need to be edited.
* @param tenantId Tenant ID of the Application. * @param tenantId Tenant ID of the ApplicationDTO.
* @return Updated Application. * @return Updated ApplicationDTO.
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
Application editApplication(Application application, int tenantId) throws ApplicationManagementDAOException, ApplicationDTO editApplication(ApplicationDTO application, int tenantId) throws ApplicationManagementDAOException;
ApplicationManagementException;
/** /**
* To delete the application * To delete the application
* *
* @param appId ID of the application. * @param appId ID of the application.
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
void deleteApplication(int appId) throws ApplicationManagementDAOException; void deleteApplication(int appId) throws ApplicationManagementDAOException;
/** /**
* To get the application count that satisfies gives search query. * To get the application count that satisfies gives search query.
* *
* @param filter Application Filter. * @param filter ApplicationDTO Filter.
* @param tenantId Id of the tenant * @param tenantId Id of the tenant
* @return count of the applications * @return count of the applications
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
int getApplicationCount(Filter filter, int tenantId) throws ApplicationManagementDAOException; int getApplicationCount(Filter filter, int tenantId) throws ApplicationManagementDAOException;
@ -171,18 +194,18 @@ public interface ApplicationDAO {
* @param tags Tags which are going to delete. * @param tags Tags which are going to delete.
* @param applicationId ID of the application to delete the tags. * @param applicationId ID of the application to delete the tags.
* @param tenantId Tenant Id * @param tenantId Tenant Id
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
void deleteTags(List<String> tags, int applicationId, int tenantId) throws ApplicationManagementDAOException; void deleteTags(List<String> tags, int applicationId, int tenantId) throws ApplicationManagementDAOException;
/** /**
* To get an {@link Application} associated with the given release * To get an {@link ApplicationDTO} associated with the given release
* *
* @param appReleaseUUID UUID of the {@link ApplicationRelease} * @param appReleaseUUID UUID of the {@link ApplicationReleaseDTO}
* @param tenantId ID of the tenant * @param tenantId ID of the tenant
* @return {@link Application} associated with the given release UUID * @return {@link ApplicationDTO} associated with the given release UUID
* @throws ApplicationManagementDAOException if unable to fetch the Application from the data store. * @throws ApplicationManagementDAOException if unable to fetch the ApplicationDTO from the data store.
*/ */
Application getApplicationByRelease(String appReleaseUUID, int tenantId) throws ApplicationManagementDAOException; ApplicationDTO getApplicationByRelease(String appReleaseUUID, int tenantId) throws ApplicationManagementDAOException;
} }

View File

@ -18,25 +18,26 @@
*/ */
package org.wso2.carbon.device.application.mgt.core.dao; package org.wso2.carbon.device.application.mgt.core.dao;
import org.wso2.carbon.device.application.mgt.common.ApplicationRelease; import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO;
import org.wso2.carbon.device.application.mgt.common.ApplicationReleaseArtifactPaths;
import org.wso2.carbon.device.application.mgt.common.Rating; import org.wso2.carbon.device.application.mgt.common.Rating;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import java.util.List; import java.util.List;
/** /**
* This is responsible for Application Release related DAO operations. * This is responsible for ApplicationDTO Release related DAO operations.
*/ */
public interface ApplicationReleaseDAO { public interface ApplicationReleaseDAO {
/** /**
* To create an Application release. * To create an ApplicationDTO release.
* *
* @param applicationRelease Application Release that need to be created. * @param applicationRelease ApplicationDTO Release that need to be created.
* @return Unique ID of the relevant release. * @return Unique ID of the relevant release.
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
ApplicationRelease createRelease(ApplicationRelease applicationRelease, int appId, int tenantId) throws ApplicationReleaseDTO createRelease(ApplicationReleaseDTO applicationRelease, int appId, int tenantId) throws
ApplicationManagementDAOException; ApplicationManagementDAOException;
/** /**
@ -47,54 +48,53 @@ public interface ApplicationReleaseDAO {
* @param releaseType type of the release * @param releaseType type of the release
* @param tenantId tenantId of the application * @param tenantId tenantId of the application
* @return ApplicationRelease for the particular version of the given application * @return ApplicationReleaseDTO for the particular version of the given application
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
ApplicationRelease getRelease(String applicationName,String applicationType, String versionName, ApplicationReleaseDTO getRelease(String applicationName,String applicationType, String versionName,
String releaseType, int tenantId) throws String releaseType, int tenantId) throws
ApplicationManagementDAOException; ApplicationManagementDAOException;
/** /**
* To get all the releases of a particular application. * To get all the releases of a particular application.
* *
* @param applicationId Id of the Application * @param applicationId Id of the application
* @param tenantId tenant id of the application * @param tenantId tenant id of the application
* @return list of the application releases * @return list of the application releases
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
List<ApplicationRelease> getReleases(int applicationId, int tenantId) throws List<ApplicationReleaseDTO> getReleases(int applicationId, int tenantId) throws
ApplicationManagementDAOException; ApplicationManagementDAOException;
/** /**
* To get the release by state. * To get the release by state.
* *
* @param appId Id of the Application * @param appId Id of the ApplicationDTO
* @param tenantId tenant id of the application * @param tenantId tenant id of the application
* @param state state of the application * @param state state of the application
* @return list of the application releases * @return list of the application releases
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
List<ApplicationRelease> getReleaseByState(int appId, int tenantId, String state) List<ApplicationReleaseDTO> getReleaseByState(int appId, int tenantId, String state)
throws ApplicationManagementDAOException; throws ApplicationManagementDAOException;
/** /**
* To update an Application release. * To update an ApplicationDTO release.
* *
* @param applicationRelease ApplicationRelease that need to be updated. * @param applicationRelease ApplicationReleaseDTO that need to be updated.
* @param applicationId Id of the application.
* @param tenantId Id of the tenant * @param tenantId Id of the tenant
* @return the updated Application Release * @return the updated ApplicationDTO Release
* @throws ApplicationManagementDAOException Application Management DAO Exception * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception
*/ */
ApplicationRelease updateRelease(int applicationId, ApplicationRelease applicationRelease, int tenantId) throws ApplicationReleaseDTO updateRelease(ApplicationReleaseDTO applicationRelease, int tenantId)
ApplicationManagementDAOException; throws ApplicationManagementDAOException;
/** /**
* To update an Application release. * To update an ApplicationDTO release.
* @param uuid UUID of the ApplicationRelease that need to be updated. * @param uuid UUID of the ApplicationReleaseDTO that need to be updated.
* @param rating given stars for the application. * @param rating given stars for the application.
* @param ratedUsers number of users who has rated for the application release. * @param ratedUsers number of users who has rated for the application release.
* @throws ApplicationManagementDAOException Application Management DAO Exception * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception
*/ */
void updateRatingValue(String uuid, double rating, int ratedUsers) throws ApplicationManagementDAOException; void updateRatingValue(String uuid, double rating, int ratedUsers) throws ApplicationManagementDAOException;
@ -103,7 +103,7 @@ public interface ApplicationReleaseDAO {
* *
* @param uuid UUID of the application Release. * @param uuid UUID of the application Release.
* @param tenantId Tenant Id * @param tenantId Tenant Id
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
Rating getRating(String uuid, int tenantId) throws ApplicationManagementDAOException; Rating getRating(String uuid, int tenantId) throws ApplicationManagementDAOException;
@ -111,9 +111,9 @@ public interface ApplicationReleaseDAO {
/** /**
* To delete a particular release. * To delete a particular release.
* *
* @param id ID of the Application which the release need to be deleted. * @param id ID of the ApplicationDTO which the release need to be deleted.
* @param version Version of the Application Release * @param version Version of the ApplicationDTO Release
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
void deleteRelease(int id, String version) throws ApplicationManagementDAOException; void deleteRelease(int id, String version) throws ApplicationManagementDAOException;
@ -123,30 +123,31 @@ public interface ApplicationReleaseDAO {
* @param applicationId ID of the application. * @param applicationId ID of the application.
* @param releaseUuid UUID of the application release. * @param releaseUuid UUID of the application release.
* @param tenantId Tenant Id * @param tenantId Tenant Id
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
ApplicationRelease getReleaseByIds(int applicationId, String releaseUuid, int tenantId) throws ApplicationReleaseDTO getReleaseByIds(int applicationId, String releaseUuid, int tenantId) throws
ApplicationManagementDAOException; ApplicationManagementDAOException;
ApplicationReleaseDTO getReleaseByUUID(String uuid, int tenantId) throws ApplicationManagementDAOException;
/** /**
* To verify whether application release exist or not. * To verify whether application release exist or not.
* *
* @param appId ID of the application. * @param appId ID of the application.
* @param uuid UUID of the application release. * @param uuid UUID of the application release.
* @param tenantId Tenant Id * @param tenantId Tenant Id
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
boolean verifyReleaseExistence(int appId, String uuid, int tenantId) throws ApplicationManagementDAOException; boolean verifyReleaseExistence(int appId, String uuid, int tenantId) throws ApplicationManagementDAOException;
/** /**
* To verify whether application release exist or not for the given app release version. * To verify whether application release exist or not for the given app release version.
* *
* @param appId ID of the application.
* @param hashVal Hash value of the application release. * @param hashVal Hash value of the application release.
* @param tenantId Tenant Id * @param tenantId Tenant Id
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
boolean verifyReleaseExistenceByHash(int appId, String hashVal, int tenantId) boolean verifyReleaseExistenceByHash(String hashVal, int tenantId)
throws ApplicationManagementDAOException; throws ApplicationManagementDAOException;
/** /**
@ -167,4 +168,15 @@ public interface ApplicationReleaseDAO {
*/ */
boolean verifyReleaseExistenceByUuid(String uuid, int tenantId) throws ApplicationManagementDAOException; boolean verifyReleaseExistenceByUuid(String uuid, int tenantId) throws ApplicationManagementDAOException;
String getReleaseHashValue(String uuid, int tenantId) throws ApplicationManagementDAOException;
/***
*
* @param packageName Application release package name
* @param tenantId Tenant ID
* @return True if application release package name already exist in the IoT server, Otherwise returns False.
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
boolean isActiveReleaseExisitForPackageName(String packageName, int tenantId, String inactiveState) throws ApplicationManagementDAOException;
} }

View File

@ -18,7 +18,7 @@
*/ */
package org.wso2.carbon.device.application.mgt.core.dao; 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.common.dto.LifecycleStateDTO;
import org.wso2.carbon.device.application.mgt.core.exception.LifeCycleManagementDAOException; import org.wso2.carbon.device.application.mgt.core.exception.LifeCycleManagementDAOException;
import java.util.List; import java.util.List;
@ -35,7 +35,7 @@ public interface LifecycleStateDAO {
* @return Latest Lifecycle State for the given application release * @return Latest Lifecycle State for the given application release
* @throws LifeCycleManagementDAOException Lifecycle Management DAO Exception. * @throws LifeCycleManagementDAOException Lifecycle Management DAO Exception.
*/ */
LifecycleState getLatestLifeCycleStateByReleaseID(int applicationReleaseId) throws LifeCycleManagementDAOException; LifecycleStateDTO getLatestLifeCycleStateByReleaseID(int applicationReleaseId) throws LifeCycleManagementDAOException;
/** /**
* To get the latest lifecycle state for the given application id and the application release UUID. * To get the latest lifecycle state for the given application id and the application release UUID.
@ -45,7 +45,7 @@ public interface LifecycleStateDAO {
* @return Latest Lifecycle State for the given application release * @return Latest Lifecycle State for the given application release
* @throws LifeCycleManagementDAOException Lifecycle Management DAO Exception. * @throws LifeCycleManagementDAOException Lifecycle Management DAO Exception.
*/ */
LifecycleState getLatestLifeCycleState(int appId, String uuid) throws LifeCycleManagementDAOException; LifecycleStateDTO getLatestLifeCycleState(int appId, String uuid) throws LifeCycleManagementDAOException;
/** /**
* To get all changed lifecycle states for the given application release id. * To get all changed lifecycle states for the given application release id.
@ -54,25 +54,35 @@ public interface LifecycleStateDAO {
* @return Lifecycle States for the given application release * @return Lifecycle States for the given application release
* @throws LifeCycleManagementDAOException Lifecycle Management DAO Exception. * @throws LifeCycleManagementDAOException Lifecycle Management DAO Exception.
*/ */
List<LifecycleState> getLifecycleStates(int appReleaseId) throws LifeCycleManagementDAOException; List<LifecycleStateDTO> getLifecycleStates(int appReleaseId) throws LifeCycleManagementDAOException;
/** /**
* To add new lifecycle states for the given application release. * To add new lifecycle states for the given application release.
* @param uuid Id of the application release. * @param uuid Id of the application release.
* @param appId Id of the application. * @param appId Id of the application.
* @param state LifecycleState. * @param state LifecycleStateDTO.
* @param tenantId Tenant id * @param tenantId Tenant id
* *
* @throws LifeCycleManagementDAOException Lifecycle Management DAO Exception. * @throws LifeCycleManagementDAOException Lifecycle Management DAO Exception.
*/ */
void addLifecycleState(LifecycleState state, int appId, String uuid, int tenantId) void addLifecycleState(LifecycleStateDTO state, int appId, String uuid, int tenantId)
throws LifeCycleManagementDAOException; throws LifeCycleManagementDAOException;
/** /**
* To delete a specific lifecycle state for application release. * To delete a specific lifecycle state for application release.
* @param identifier Id of the LifecycleState. * @param identifier Id of the LifecycleStateDTO.
* *
* @throws LifeCycleManagementDAOException Lifecycle Management DAO Exception. * @throws LifeCycleManagementDAOException Lifecycle Management DAO Exception.
*/ */
void deleteLifecycleState(int identifier) throws LifeCycleManagementDAOException; void deleteLifecycleState(int identifier) throws LifeCycleManagementDAOException;
/***
*
* @param appId ID of the application
* @param uuid UUID of the application release
* @return Username of the application release creator
* @throws LifeCycleManagementDAOException {@link LifeCycleManagementDAOException}
*/
String getAppReleaseCreatedUsername(int appId, String uuid, int tenantId) throws LifeCycleManagementDAOException;
} }

View File

@ -18,7 +18,8 @@
*/ */
package org.wso2.carbon.device.application.mgt.core.dao; 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.dto.ApplicationDTO;
import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
@ -37,8 +38,8 @@ public interface SubscriptionDAO {
* @param tenantId id of the tenant * @param tenantId id of the tenant
* @param subscribedBy username of the user who subscribe the application * @param subscribedBy username of the user who subscribe the application
* @param deviceList List of {@link Device} which the application is installed on * @param deviceList List of {@link Device} which the application is installed on
* @param appId id of the {@link Application} which installs * @param appId id of the {@link ApplicationDTO} which installs
* @param releaseId id of the {@link org.wso2.carbon.device.application.mgt.common.ApplicationRelease} * @param releaseId id of the {@link ApplicationReleaseDTO}
* @throws ApplicationManagementDAOException If unable to add a mapping between device and application * @throws ApplicationManagementDAOException If unable to add a mapping between device and application
*/ */
void subscribeDeviceToApplication(int tenantId, String subscribedBy, List<Device> deviceList, int appId, void subscribeDeviceToApplication(int tenantId, String subscribedBy, List<Device> deviceList, int appId,
@ -51,8 +52,8 @@ public interface SubscriptionDAO {
* @param tenantId id of the tenant * @param tenantId id of the tenant
* @param subscribedBy username of the user who subscribe the application * @param subscribedBy username of the user who subscribe the application
* @param userList list of user names of the users whose devices are subscribed to the application * @param userList list of user names of the users whose devices are subscribed to the application
* @param appId id of the {@link Application} which installs * @param appId id of the {@link ApplicationDTO} which installs
* @param releaseId id of the {@link org.wso2.carbon.device.application.mgt.common.ApplicationRelease} * @param releaseId id of the {@link ApplicationReleaseDTO}
* @throws ApplicationManagementDAOException If unable to add a mapping between device and application * @throws ApplicationManagementDAOException If unable to add a mapping between device and application
*/ */
void subscribeUserToApplication(int tenantId, String subscribedBy, List<String> userList, int appId, int releaseId) void subscribeUserToApplication(int tenantId, String subscribedBy, List<String> userList, int appId, int releaseId)
@ -65,8 +66,8 @@ public interface SubscriptionDAO {
* @param tenantId id of the tenant * @param tenantId id of the tenant
* @param subscribedBy username of the user who subscribe the application * @param subscribedBy username of the user who subscribe the application
* @param roleList list of roles which belongs devices are subscribed to the application * @param roleList list of roles which belongs devices are subscribed to the application
* @param appId id of the {@link Application} which installs * @param appId id of the {@link ApplicationDTO} which installs
* @param releaseId id of the {@link org.wso2.carbon.device.application.mgt.common.ApplicationRelease} * @param releaseId id of the {@link ApplicationReleaseDTO}
* @throws ApplicationManagementDAOException If unable to add a mapping between device and application * @throws ApplicationManagementDAOException If unable to add a mapping between device and application
*/ */
void subscribeRoleToApplication(int tenantId, String subscribedBy, List<String> roleList, int appId, int releaseId) void subscribeRoleToApplication(int tenantId, String subscribedBy, List<String> roleList, int appId, int releaseId)
@ -79,8 +80,8 @@ public interface SubscriptionDAO {
* @param tenantId id of the tenant * @param tenantId id of the tenant
* @param subscribedBy username of the user who subscribe the application * @param subscribedBy username of the user who subscribe the application
* @param groupList list of {@link DeviceGroup} which belongs the devices that are subscribed to the application * @param groupList list of {@link DeviceGroup} which belongs the devices that are subscribed to the application
* @param appId id of the {@link Application} which installs * @param appId id of the {@link ApplicationDTO} which installs
* @param releaseId id of the {@link org.wso2.carbon.device.application.mgt.common.ApplicationRelease} * @param releaseId id of the {@link ApplicationReleaseDTO}
* @throws ApplicationManagementDAOException If unable to add a mapping between device and application * @throws ApplicationManagementDAOException If unable to add a mapping between device and application
*/ */
void subscribeGroupToApplication(int tenantId, String subscribedBy, List<DeviceGroup> groupList, int appId, void subscribeGroupToApplication(int tenantId, String subscribedBy, List<DeviceGroup> groupList, int appId,

View File

@ -22,16 +22,17 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.json.JSONException; import org.json.JSONException;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.common.*; import org.wso2.carbon.device.application.mgt.common.dto.ApplicationDTO;
import org.wso2.carbon.device.application.mgt.common.Application;
import org.wso2.carbon.device.application.mgt.common.PaginationRequest; import org.wso2.carbon.device.application.mgt.common.PaginationRequest;
import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO;
import org.wso2.carbon.device.application.mgt.common.exception.ReviewManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ReviewManagementException;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager;
import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager; import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager;
import org.wso2.carbon.device.application.mgt.core.config.Configuration; import org.wso2.carbon.device.application.mgt.core.config.Configuration;
import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager; import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager;
import org.wso2.carbon.device.application.mgt.core.exception.UnexpectedServerErrorException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -55,10 +56,10 @@ public class Util {
* @throws SQLException SQL Exception * @throws SQLException SQL Exception
* @throws JSONException JSONException. * @throws JSONException JSONException.
*/ */
public static List<Application> loadApplications(ResultSet rs) throws SQLException, JSONException { public static List<ApplicationDTO> loadApplications(ResultSet rs) throws SQLException, JSONException {
List<Application> applications = new ArrayList<>(); List<ApplicationDTO> applications = new ArrayList<>();
Application application = null; ApplicationDTO application = null;
int applicationId = -1; int applicationId = -1;
boolean hasNext = rs.next(); boolean hasNext = rs.next();
@ -67,35 +68,22 @@ public class Util {
if (application != null) { if (application != null) {
applications.add(application); applications.add(application);
} }
application = new ApplicationDTO();
application.setApplicationReleaseDTOs(new ArrayList<>());
applicationId = rs.getInt("APP_ID"); applicationId = rs.getInt("APP_ID");
application = new Application();
application.setTags(new ArrayList<>());
application.setUnrestrictedRoles(new ArrayList<>());
application.setId(applicationId); application.setId(applicationId);
application.setName(rs.getString("APP_NAME")); application.setName(rs.getString("APP_NAME"));
application.setDescription(rs.getString("APP_DESCRIPTION"));
application.setType(rs.getString("APP_TYPE")); application.setType(rs.getString("APP_TYPE"));
application.setAppCategory(rs.getString("APP_CATEGORY")); application.setSubType(rs.getString("APP_SUB_TYPE"));
application.setSubType(rs.getString("SUB_TYPE")); application.setPaymentCurrency(rs.getString("APP_CURRENCY"));
application.setPaymentCurrency(rs.getString("CURRENCY")); application.setStatus(rs.getString("APP_STATUS"));
application.setIsRestricted(rs.getBoolean("RESTRICTED")); application.setAppRating(rs.getInt("APP_RATING"));
String tag = rs.getString("APP_TAG"); application.setDeviceTypeId(rs.getInt("APP_DEVICE_TYPE_ID"));
String unrestrictedRole = rs.getString("ROLE"); application.getApplicationReleaseDTOs().add(loadAppRelease(rs));
if (tag != null) {
application.getTags().add(tag);
}
if (unrestrictedRole != null) {
application.getUnrestrictedRoles().add(unrestrictedRole);
}
} else { } else {
String tag = rs.getString("APP_TAG"); if (application != null && application.getApplicationReleaseDTOs() != null) {
String unrestrictedRole = rs.getString("ROLE"); application.getApplicationReleaseDTOs().add(loadAppRelease(rs));
if (application != null) {
if (tag != null && !application.getTags().contains(tag)) {
application.getTags().add(tag);
}
if (unrestrictedRole != null && !application.getUnrestrictedRoles().contains(unrestrictedRole)) {
application.getUnrestrictedRoles().add(unrestrictedRole);
}
} }
} }
hasNext = rs.next(); hasNext = rs.next();
@ -106,75 +94,81 @@ public class Util {
return applications; return applications;
} }
/**
* Populates {@link ApplicationReleaseDTO} object with the result obtained from the database.
*
* @param rs {@link ResultSet} from obtained from the database
* @return {@link ApplicationReleaseDTO} object populated with the data
* @throws SQLException If unable to populate {@link ApplicationReleaseDTO} object with the data
*/
public static ApplicationReleaseDTO loadAppRelease(ResultSet rs) throws SQLException {
ApplicationReleaseDTO appRelease = new ApplicationReleaseDTO();
appRelease.setDescription(rs.getString("RELEASE_DESCRIPTION"));
appRelease.setUuid(rs.getString("RELEASE_UUID"));
appRelease.setReleaseType(rs.getString("RELEASE_TYPE"));
appRelease.setVersion(rs.getString("RELEASE_VERSION"));
appRelease.setInstallerName(rs.getString("AP_RELEASE_STORED_LOC"));
appRelease.setIconName(rs.getString("AP_RELEASE_ICON_LOC"));
appRelease.setBannerName(rs.getString("AP_RELEASE_BANNER_LOC"));
appRelease.setScreenshotName1(rs.getString("AP_RELEASE_SC1"));
appRelease.setScreenshotName2(rs.getString("AP_RELEASE_SC2"));
appRelease.setScreenshotName3(rs.getString("AP_RELEASE_SC3"));
appRelease.setAppHashValue(rs.getString("RELEASE_HASH_VALUE"));
appRelease.setPrice(rs.getDouble("RELEASE_PRICE"));
appRelease.setMetaData(rs.getString("RELEASE_META_INFO"));
appRelease.setSupportedOsVersions(rs.getString("RELEASE_SUP_OS_VERSIONS"));
appRelease.setRating(rs.getDouble("RELEASE_RATING"));
appRelease.setCurrentState(rs.getString("RELEASE_CURRENT_STATE"));
appRelease.setRatedUsers(rs.getInt("RATED_USER_COUNT"));
return appRelease;
}
/** /**
* To create application object from the result set retrieved from the Database. * To create application object from the result set retrieved from the Database.
* *
* @param rs ResultSet * @param rs ResultSet
* @return Application that is retrieved from the Database. * @return ApplicationDTO that is retrieved from the Database.
* @throws SQLException SQL Exception * @throws SQLException SQL Exception
* @throws JSONException JSONException. * @throws JSONException JSONException.
*/ */
public static Application loadApplication(ResultSet rs) throws SQLException, JSONException { public static ApplicationDTO loadApplication(ResultSet rs)
throws SQLException, JSONException, UnexpectedServerErrorException {
Application application = null; List<ApplicationDTO> applicationDTOs = loadApplications(rs);
int applicatioId; if (applicationDTOs.isEmpty()) {
int iteration = 0; return null;
if (rs != null) {
while (rs.next()) {
if (iteration == 0) {
application = new Application();
application.setTags(new ArrayList<>());
application.setUnrestrictedRoles(new ArrayList<>());
applicatioId = rs.getInt("APP_ID");
application.setId(applicatioId);
application.setName(rs.getString("APP_NAME"));
application.setType(rs.getString("APP_TYPE"));
application.setAppCategory(rs.getString("APP_CATEGORY"));
application.setSubType(rs.getString("SUB_TYPE"));
application.setPaymentCurrency(rs.getString("CURRENCY"));
application.setIsRestricted(rs.getBoolean("RESTRICTED"));
application.setDeviceTypeId(rs.getInt("DEVICE_TYPE_ID"));
} }
if (applicationDTOs.size() > 1) {
String tag = rs.getString("APP_TAG"); String msg = "Internal server error. Found more than one application for requested application ID";
String unrestrictedRole = rs.getString("ROLE"); log.error(msg);
if (tag != null && !application.getTags().contains(tag)) { throw new UnexpectedServerErrorException(msg);
application.getTags().add(tag);
} }
if (unrestrictedRole != null && !application.getUnrestrictedRoles().contains(unrestrictedRole)) { return applicationDTOs.get(0);
application.getUnrestrictedRoles().add(unrestrictedRole);
}
iteration++;
}
}
return application;
} }
/** /**
* Populates {@link ApplicationRelease} object with the result obtained from the database. * Populates {@link ApplicationReleaseDTO} object with the result obtained from the database.
* *
* @param resultSet {@link ResultSet} from obtained from the database * @param resultSet {@link ResultSet} from obtained from the database
* @return {@link ApplicationRelease} object populated with the data * @return {@link ApplicationReleaseDTO} object populated with the data
* @throws SQLException If unable to populate {@link ApplicationRelease} object with the data * @throws SQLException If unable to populate {@link ApplicationReleaseDTO} object with the data
*/ */
public static ApplicationRelease loadApplicationRelease(ResultSet resultSet) throws SQLException { public static ApplicationReleaseDTO loadApplicationRelease(ResultSet resultSet) throws SQLException {
ApplicationRelease applicationRelease = new ApplicationRelease(); ApplicationReleaseDTO applicationRelease = new ApplicationReleaseDTO();
applicationRelease.setId(resultSet.getInt("RELEASE_ID")); applicationRelease.setId(resultSet.getInt("RELEASE_ID"));
applicationRelease.setVersion(resultSet.getString("RELEASE_VERSION")); applicationRelease.setVersion(resultSet.getString("RELEASE_VERSION"));
applicationRelease.setUuid(resultSet.getString("UUID")); applicationRelease.setUuid(resultSet.getString("UUID"));
applicationRelease.setReleaseType(resultSet.getString("RELEASE_TYPE")); applicationRelease.setReleaseType(resultSet.getString("RELEASE_TYPE"));
applicationRelease.setPackageName(resultSet.getString("PACKAGE_NAME")); applicationRelease.setPackageName(resultSet.getString("PACKAGE_NAME"));
applicationRelease.setPrice(resultSet.getDouble("APP_PRICE")); applicationRelease.setPrice(resultSet.getDouble("APP_PRICE"));
applicationRelease.setAppStoredLoc(resultSet.getString("STORED_LOCATION")); applicationRelease.setInstallerName(resultSet.getString("STORED_LOCATION"));
applicationRelease.setBannerLoc(resultSet.getString("BANNER_LOCATION")); applicationRelease.setBannerName(resultSet.getString("BANNER_LOCATION"));
applicationRelease.setIconLoc(resultSet.getString("ICON_LOCATION")); applicationRelease.setIconName(resultSet.getString("ICON_LOCATION"));
applicationRelease.setScreenshotLoc1(resultSet.getString("SCREEN_SHOT_1")); applicationRelease.setScreenshotName1(resultSet.getString("SCREEN_SHOT_1"));
applicationRelease.setScreenshotLoc2(resultSet.getString("SCREEN_SHOT_2")); applicationRelease.setScreenshotName2(resultSet.getString("SCREEN_SHOT_2"));
applicationRelease.setScreenshotLoc3(resultSet.getString("SCREEN_SHOT_3")); applicationRelease.setScreenshotName3(resultSet.getString("SCREEN_SHOT_3"));
applicationRelease.setAppHashValue(resultSet.getString("HASH_VALUE")); applicationRelease.setAppHashValue(resultSet.getString("HASH_VALUE"));
applicationRelease.setIsSharedWithAllTenants(resultSet.getInt("SHARED")); applicationRelease.setIsSharedWithAllTenants(resultSet.getBoolean("SHARED"));
applicationRelease.setMetaData(resultSet.getString("APP_META_INFO")); applicationRelease.setMetaData(resultSet.getString("APP_META_INFO"));
applicationRelease.setRating(resultSet.getDouble("RATING")); applicationRelease.setRating(resultSet.getDouble("RATING"));
return applicationRelease; return applicationRelease;
@ -212,7 +206,7 @@ public class Util {
commentManagementConfig.getPaginationConfiguration().getCommentListPageSize()); commentManagementConfig.getPaginationConfiguration().getCommentListPageSize());
} else { } else {
throw new ReviewManagementException( throw new ReviewManagementException(
"Application Management configuration has not initialized. Please check the application-mgt.xml file."); "ApplicationDTO Management configuration has not initialized. Please check the application-mgt.xml file.");
} }
} }
return paginationRequest; return paginationRequest;
@ -230,7 +224,7 @@ public class Util {
applicationManager = applicationManager =
(ApplicationManager) ctx.getOSGiService(ApplicationManager.class, null); (ApplicationManager) ctx.getOSGiService(ApplicationManager.class, null);
if (applicationManager == null) { if (applicationManager == null) {
String msg = "Application Manager service has not initialized."; String msg = "ApplicationDTO Manager service has not initialized.";
log.error(msg); log.error(msg);
throw new IllegalStateException(msg); throw new IllegalStateException(msg);
} }
@ -241,7 +235,7 @@ public class Util {
} }
/** /**
* To get the Application Storage Manager from the osgi context. * To get the ApplicationDTO Storage Manager from the osgi context.
* @return ApplicationStoreManager instance in the current osgi context. * @return ApplicationStoreManager instance in the current osgi context.
*/ */
public static ApplicationStorageManager getApplicationStorageManager() { public static ApplicationStorageManager getApplicationStorageManager() {
@ -252,7 +246,7 @@ public class Util {
applicationStorageManager = (ApplicationStorageManager) ctx applicationStorageManager = (ApplicationStorageManager) ctx
.getOSGiService(ApplicationStorageManager.class, null); .getOSGiService(ApplicationStorageManager.class, null);
if (applicationStorageManager == null) { if (applicationStorageManager == null) {
String msg = "Application Storage Manager service has not initialized."; String msg = "ApplicationDTO Storage Manager service has not initialized.";
log.error(msg); log.error(msg);
throw new IllegalStateException(msg); throw new IllegalStateException(msg);
} }

View File

@ -51,7 +51,7 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
@Override @Override
public boolean addReview(Review review, String uuid, int tenantId) throws ReviewManagementDAOException { public boolean addReview(Review review, String uuid, int tenantId) throws ReviewManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to add review for application release. Application UUID: " + uuid); log.debug("Request received in DAO Layer to add review for application release. ApplicationDTO UUID: " + uuid);
} }
PreparedStatement statement = null; PreparedStatement statement = null;
ResultSet rs = null; ResultSet rs = null;
@ -93,7 +93,7 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug( log.debug(
"Request received in DAO Layer to check whether user have already commented or not for the " "Request received in DAO Layer to check whether user have already commented or not for the "
+ "application release. Application UUID: " + uuid + " comment owner: " + username + + "application release. ApplicationDTO UUID: " + uuid + " comment owner: " + username +
" tenant-id " + tenantId); " tenant-id " + tenantId);
} }
Connection conn; Connection conn;

View File

@ -18,21 +18,22 @@
*/ */
package org.wso2.carbon.device.application.mgt.core.dao.impl.application; package org.wso2.carbon.device.application.mgt.core.dao.impl.application;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.json.JSONException; import org.json.JSONException;
import org.wso2.carbon.device.application.mgt.common.AppLifecycleState; import org.wso2.carbon.device.application.mgt.common.AppLifecycleState;
import org.wso2.carbon.device.application.mgt.common.Application; import org.wso2.carbon.device.application.mgt.common.dto.ApplicationDTO;
import org.wso2.carbon.device.application.mgt.common.ApplicationList; import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO;
import org.wso2.carbon.device.application.mgt.common.ApplicationRelease; import org.wso2.carbon.device.application.mgt.common.dto.CategoryDTO;
import org.wso2.carbon.device.application.mgt.common.Filter; import org.wso2.carbon.device.application.mgt.common.Filter;
import org.wso2.carbon.device.application.mgt.common.Pagination; import org.wso2.carbon.device.application.mgt.common.dto.TagDTO;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; 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.ApplicationDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.Util; 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.dao.impl.AbstractDAOImpl;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.exception.UnexpectedServerErrorException;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -41,6 +42,7 @@ import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.StringJoiner;
/** /**
* This handles ApplicationDAO related operations. * This handles ApplicationDAO related operations.
@ -50,12 +52,11 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
private static final Log log = LogFactory.getLog(GenericApplicationDAOImpl.class); private static final Log log = LogFactory.getLog(GenericApplicationDAOImpl.class);
@Override @Override
public int createApplication(Application application, int deviceId) throws ApplicationManagementDAOException { public int createApplication(ApplicationDTO application, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to create an application"); log.debug("Request received in DAO Layer to create an application");
log.debug("Application Details : "); log.debug("ApplicationDTO Details : ");
log.debug("App Name : " + application.getName() + " App Type : " log.debug("App Name : " + application.getName() + " App Type : " + application.getType());
+ application.getType() + " User Name : " + application.getUser().getUserName());
} }
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
@ -63,16 +64,19 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
int applicationId = -1; int applicationId = -1;
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
stmt = conn.prepareStatement("INSERT INTO AP_APP (NAME, TYPE, APP_CATEGORY, SUB_TYPE, RESTRICTED, " stmt = conn.prepareStatement("INSERT INTO AP_APP "
+ "TENANT_ID, DEVICE_TYPE_ID) VALUES (?, ?, ?, ?, ?, ?, ?)", + "(NAME, "
Statement.RETURN_GENERATED_KEYS); + "DESCRIPTION, "
+ "TYPE, "
+ "SUB_TYPE, "
+ "TENANT_ID, "
+ "DEVICE_TYPE_ID) VALUES (?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, application.getName()); stmt.setString(1, application.getName());
stmt.setString(2, application.getType()); stmt.setString(2, application.getDescription());
stmt.setString(3, application.getAppCategory()); stmt.setString(3, application.getType());
stmt.setString(4, application.getSubType()); stmt.setString(4, application.getSubType());
stmt.setBoolean(5, application.getIsRestricted()); stmt.setInt(5, tenantId);
stmt.setInt(6, application.getUser().getTenantId()); stmt.setInt(6, application.getDeviceTypeId());
stmt.setInt(7, deviceId);
stmt.executeUpdate(); stmt.executeUpdate();
rs = stmt.getGeneratedKeys(); rs = stmt.getGeneratedKeys();
@ -80,7 +84,6 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
applicationId = rs.getInt(1); applicationId = rs.getInt(1);
} }
return applicationId; return applicationId;
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException( throw new ApplicationManagementDAOException(
"Error occurred while obtaining the DB connection when application creation", e); "Error occurred while obtaining the DB connection when application creation", e);
@ -122,7 +125,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
@Override @Override
public ApplicationList getApplications(Filter filter, int tenantId) throws ApplicationManagementDAOException { public List<ApplicationDTO> getApplications(Filter filter,int deviceTypeId, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting application data from the database"); log.debug("Getting application data from the database");
log.debug(String.format("Filter: limit=%s, offset=%s", filter.getLimit(), filter.getOffset())); log.debug(String.format("Filter: limit=%s, offset=%s", filter.getLimit(), filter.getOffset()));
@ -131,31 +134,47 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
ApplicationList applicationList = new ApplicationList(); String sql = "SELECT "
Pagination pagination = new Pagination(); + "AP_APP.ID AS APP_ID, "
String sql = "SELECT AP_APP.ID AS APP_ID, AP_APP.NAME AS APP_NAME, AP_APP.TYPE AS APP_TYPE, AP_APP.APP_CATEGORY" + "AP_APP.NAME AS APP_NAME, "
+ " AS APP_CATEGORY, AP_APP.SUB_TYPE AS SUB_TYPE, AP_APP.CURRENCY AS CURRENCY, " + "AP_APP.DESCRIPTION AS APP_DESCRIPTION, "
+ "AP_APP.RESTRICTED AS RESTRICTED, AP_APP_TAG.TAG AS APP_TAG, AP_UNRESTRICTED_ROLE.ROLE " + "AP_APP.TYPE AS APP_TYPE, "
+ "AS ROLE FROM ((AP_APP LEFT JOIN AP_APP_TAG ON AP_APP.ID = AP_APP_TAG.AP_APP_ID) " + "AP_APP.STATUS AS APP_STATUS, "
+ "LEFT JOIN AP_UNRESTRICTED_ROLE ON AP_APP.ID = AP_UNRESTRICTED_ROLE.AP_APP_ID) " + "AP_APP.SUB_TYPE AS APP_SUB_TYPE, "
+ "WHERE AP_APP.TENANT_ID = ? AND AP_APP.STATUS != ?"; + "AP_APP.CURRENCY AS APP_CURRENCY, "
+ "AP_APP.RATING AS APP_RATING, "
+ "AP_APP.DEVICE_TYPE_ID AS APP_DEVICE_TYPE_ID, "
+ "AP_APP_RELEASE.DESCRIPTION AS RELEASE_DESCRIPTION, "
+ "AP_APP_RELEASE.VERSION AS RELEASE_VERSION, "
+ "AP_APP_RELEASE.UUID AS RELEASE_UUID, "
+ "AP_APP_RELEASE.RELEASE_TYPE AS RELEASE_TYPE, "
+ "AP_APP_RELEASE.INSTALLER_LOCATION AS AP_RELEASE_STORED_LOC, "
+ "AP_APP_RELEASE.ICON_LOCATION AS AP_RELEASE_ICON_LOC, "
+ "AP_APP_RELEASE.BANNER_LOCATION AS AP_RELEASE_BANNER_LOC, "
+ "AP_APP_RELEASE.SC_1_LOCATION AS AP_RELEASE_SC1, "
+ "AP_APP_RELEASE.SC_2_LOCATION AS AP_RELEASE_SC2, "
+ "AP_APP_RELEASE.SC_3_LOCATION AS AP_RELEASE_SC3, "
+ "AP_APP_RELEASE.APP_HASH_VALUE AS RELEASE_HASH_VALUE, "
+ "AP_APP_RELEASE.APP_PRICE AS RELEASE_PRICE, "
+ "AP_APP_RELEASE.APP_META_INFO AS RELEASE_META_INFO, "
+ "AP_APP_RELEASE.SUPPORTED_OS_VERSIONS AS RELEASE_SUP_OS_VERSIONS, "
+ "AP_APP_RELEASE.RATING AS RELEASE_RATING, "
+ "AP_APP_RELEASE.CURRENT_STATE AS RELEASE_CURRENT_STATE, "
+ "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT "
+ "FROM AP_APP "
+ "INNER JOIN AP_APP_RELEASE ON "
+ "AP_APP.ID = AP_APP_RELEASE.AP_APP_ID AND "
+ "AP_APP.TENANT_ID = AP_APP_RELEASE.TENANT_ID "
+ "WHERE AP_APP.TENANT_ID = ?";
if (filter == null) { if (filter == null) {
throw new ApplicationManagementDAOException("Filter need to be instantiated"); throw new ApplicationManagementDAOException("Filter need to be instantiated");
} }
if (filter.getAppType() != null && !filter.getAppType().isEmpty()) { if (!StringUtils.isEmpty(filter.getAppType())) {
sql += " AND AP_APP.TYPE "; sql += " AND AP_APP.TYPE = ?";
sql += "= ?";
} }
if (!StringUtils.isEmpty(filter.getAppName())) {
if (filter.getAppCategory() != null && !filter.getAppCategory().isEmpty()) {
sql += " AND AP_APP.APP_CATEGORY ";
sql += "= ?";
}
if (filter.getAppName() != null && !filter.getAppName().isEmpty()) {
sql += " AND LOWER (AP_APP.NAME) "; sql += " AND LOWER (AP_APP.NAME) ";
if (filter.isFullMatch()) { if (filter.isFullMatch()) {
sql += "= ?"; sql += "= ?";
@ -163,28 +182,39 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
sql += "LIKE ?"; sql += "LIKE ?";
} }
} }
if (!StringUtils.isEmpty(filter.getSubscriptionType())) {
String defaultSortOrder = "ASC"; sql += " AND AP_APP.SUB_TYPE = ?";
if (filter.getSortBy() != null && !filter.getSortBy().isEmpty()) { }
defaultSortOrder = filter.getSortBy(); if (filter.getMinimumRating() > 0) {
sql += " AND AP_APP.RATING >= ?";
}
if (!StringUtils.isEmpty(filter.getVersion())) {
sql += " AND AP_APP_RELEASE.VERSION = ?";
}
if (!StringUtils.isEmpty(filter.getAppReleaseType())) {
sql += " AND AP_APP_RELEASE.RELEASE_TYPE = ?";
}
if (!StringUtils.isEmpty(filter.getAppReleaseState())) {
sql += " AND AP_APP_RELEASE.CURRENT_STATE = ?";
}
if (deviceTypeId > 0) {
sql += " AND AP_APP.DEVICE_TYPE_ID = ?";
} }
sql += " ORDER BY APP_ID " + defaultSortOrder +" LIMIT ? OFFSET ? ";
pagination.setLimit(filter.getLimit()); String sortingOrder = "ASC";
pagination.setOffset(filter.getOffset()); if (!StringUtils.isEmpty(filter.getSortBy() )) {
sortingOrder = filter.getSortBy();
}
sql += " ORDER BY APP_ID " + sortingOrder +" LIMIT ? OFFSET ? ";
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(paramIndex++, tenantId); stmt.setInt(paramIndex++, tenantId);
stmt.setString(paramIndex++, AppLifecycleState.REMOVED.toString());
if (filter.getAppType() != null && !filter.getAppType().isEmpty()) { if (filter.getAppType() != null && !filter.getAppType().isEmpty()) {
stmt.setString(paramIndex++, filter.getAppType()); stmt.setString(paramIndex++, filter.getAppType());
} }
if (filter.getAppCategory() != null && !filter.getAppCategory().isEmpty()) {
stmt.setString(paramIndex++, filter.getAppCategory());
}
if (filter.getAppName() != null && !filter.getAppName().isEmpty()) { if (filter.getAppName() != null && !filter.getAppName().isEmpty()) {
if (filter.isFullMatch()) { if (filter.isFullMatch()) {
stmt.setString(paramIndex++, filter.getAppName().toLowerCase()); stmt.setString(paramIndex++, filter.getAppName().toLowerCase());
@ -192,7 +222,24 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
stmt.setString(paramIndex++, "%" + filter.getAppName().toLowerCase() + "%"); stmt.setString(paramIndex++, "%" + filter.getAppName().toLowerCase() + "%");
} }
} }
if (!StringUtils.isEmpty(filter.getSubscriptionType())) {
stmt.setString(paramIndex++, filter.getSubscriptionType());
}
if (filter.getMinimumRating() > 0) {
stmt.setInt(paramIndex++, filter.getMinimumRating());
}
if (!StringUtils.isEmpty(filter.getVersion())) {
stmt.setString(paramIndex++, filter.getVersion());
}
if (!StringUtils.isEmpty(filter.getAppReleaseType())) {
stmt.setString(paramIndex++, filter.getAppReleaseType());
}
if (!StringUtils.isEmpty(filter.getAppReleaseState())) {
stmt.setString(paramIndex++, filter.getAppReleaseState());
}
if (deviceTypeId > 0 ) {
stmt.setInt(paramIndex++, deviceTypeId);
}
if (filter.getLimit() == 0) { if (filter.getLimit() == 0) {
stmt.setInt(paramIndex++, 100); stmt.setInt(paramIndex++, 100);
} else { } else {
@ -200,11 +247,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
stmt.setInt(paramIndex, filter.getOffset()); stmt.setInt(paramIndex, filter.getOffset());
rs = stmt.executeQuery(); rs = stmt.executeQuery();
applicationList.setApplications(Util.loadApplications(rs)); return Util.loadApplications(rs);
applicationList.setPagination(pagination);
applicationList.getPagination().setSize(filter.getOffset());
applicationList.getPagination().setCount(applicationList.getApplications().size());
} catch (SQLException e) { } catch (SQLException e) {
throw new ApplicationManagementDAOException("Error occurred while getting application list for the tenant" throw new ApplicationManagementDAOException("Error occurred while getting application list for the tenant"
+ " " + tenantId + ". While executing " + sql, e); + " " + tenantId + ". While executing " + sql, e);
@ -217,7 +260,6 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} finally { } finally {
Util.cleanupResources(stmt, rs); Util.cleanupResources(stmt, rs);
} }
return applicationList;
} }
@Override @Override
@ -301,7 +343,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
@Override @Override
public Application getApplication(String appName, String appType, int tenantId) throws public ApplicationDTO getApplication(String appName, String appType, int tenantId) throws
ApplicationManagementDAOException { ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting application with the type(" + appType + " and Name " + appName + log.debug("Getting application with the type(" + appType + " and Name " + appName +
@ -340,14 +382,15 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e); throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e);
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
} catch (UnexpectedServerErrorException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
} finally { } finally {
Util.cleanupResources(stmt, rs); Util.cleanupResources(stmt, rs);
} }
} }
@Override @Override
public Application getApplicationById(String id, int tenantId) throws public ApplicationDTO getApplicationById(String id, int tenantId) throws ApplicationManagementDAOException {
ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting application with the id:" + id); log.debug("Getting application with the id:" + id);
} }
@ -382,14 +425,16 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e); throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e);
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
} catch (UnexpectedServerErrorException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
} finally { } finally {
Util.cleanupResources(stmt, rs); Util.cleanupResources(stmt, rs);
} }
} }
@Override @Override
public Application getApplicationByUUID(String releaseUuid, int tenantId) throws public ApplicationDTO getApplicationByUUID(String releaseUuid, int tenantId)
ApplicationManagementDAOException { throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting application with the release UUID: " + releaseUuid + " from the database"); log.debug("Getting application with the release UUID: " + releaseUuid + " from the database");
} }
@ -429,14 +474,16 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e); throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e);
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
} catch (UnexpectedServerErrorException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
} finally { } finally {
Util.cleanupResources(stmt, rs); Util.cleanupResources(stmt, rs);
} }
} }
@Override @Override
public Application getApplicationById(int applicationId, int tenantId) throws public ApplicationDTO getApplicationById(int applicationId, int tenantId)
ApplicationManagementDAOException { throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting application with the id (" + applicationId + ") from the database"); log.debug("Getting application with the id (" + applicationId + ") from the database");
} }
@ -445,28 +492,48 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
ResultSet rs = null; ResultSet rs = null;
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
String sql = String sql = "SELECT "
"SELECT AP_APP.ID AS APP_ID, AP_APP.NAME AS APP_NAME, AP_APP.TYPE AS APP_TYPE, AP_APP.APP_CATEGORY " + "AP_APP.ID AS APP_ID, "
+ "AS APP_CATEGORY, AP_APP.SUB_TYPE AS SUB_TYPE, AP_APP.CURRENCY AS CURRENCY, " + "AP_APP.NAME AS APP_NAME, "
+ "AP_APP.RESTRICTED AS RESTRICTED, AP_APP.DEVICE_TYPE_ID AS DEVICE_TYPE_ID, " + "AP_APP.DESCRIPTION AS APP_DESCRIPTION, "
+ "AP_APP_TAG.TAG AS APP_TAG, AP_UNRESTRICTED_ROLE.ROLE AS ROLE FROM " + "AP_APP.TYPE AS APP_TYPE, "
+ "((AP_APP LEFT JOIN AP_APP_TAG ON AP_APP.ID = AP_APP_TAG.AP_APP_ID) " + "AP_APP.STATUS AS APP_STATUS, "
+ "LEFT JOIN AP_UNRESTRICTED_ROLE ON AP_APP.ID = AP_UNRESTRICTED_ROLE.AP_APP_ID) WHERE " + "AP_APP.SUB_TYPE AS APP_SUB_TYPE, "
+ "AP_APP.ID = ? AND AP_APP.TENANT_ID = ? AND AP_APP.STATUS != ?"; + "AP_APP.CURRENCY AS APP_CURRENCY, "
+ "AP_APP.RATING AS APP_RATING, "
+ "AP_APP.DEVICE_TYPE_ID AS APP_DEVICE_TYPE_ID, "
+ "AP_APP_RELEASE.DESCRIPTION AS RELEASE_DESCRIPTION, "
+ "AP_APP_RELEASE.VERSION AS RELEASE_VERSION, "
+ "AP_APP_RELEASE.UUID AS RELEASE_UUID, "
+ "AP_APP_RELEASE.RELEASE_TYPE AS RELEASE_TYPE, "
+ "AP_APP_RELEASE.INSTALLER_LOCATION AS AP_RELEASE_STORED_LOC, "
+ "AP_APP_RELEASE.BANNER_LOCATION AS AP_RELEASE_BANNER_LOC, "
+ "AP_APP_RELEASE.SC_1_LOCATION AS AP_RELEASE_SC1, "
+ "AP_APP_RELEASE.SC_2_LOCATION AS AP_RELEASE_SC2, "
+ "AP_APP_RELEASE.SC_3_LOCATION AS AP_RELEASE_SC3, "
+ "AP_APP_RELEASE.APP_PRICE AS RELEASE_PRICE, "
+ "AP_APP_RELEASE.APP_META_INFO AS RELEASE_META_INFO, "
+ "AP_APP_RELEASE.SUPPORTED_OS_VERSIONS AS RELEASE_SUP_OS_VERSIONS, "
+ "AP_APP_RELEASE.RATING AS RELEASE_RATING, "
+ "AP_APP_RELEASE.CURRENT_STATE AS RELEASE_CURRENT_STATE, "
+ "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT "
+ "FROM AP_APP "
+ "INNER JOIN AP_APP_RELEASE ON "
+ "AP_APP.ID = AP_APP_RELEASE.AP_APP_ID AND "
+ "AP_APP.TENANT_ID = AP_APP_RELEASE.TENANT_ID "
+ "WHERE "
+ "AP_APP.ID =? AND "
+ "AP_APP.TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, applicationId); stmt.setInt(1, applicationId);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
stmt.setString(3, AppLifecycleState.REMOVED.toString());
rs = stmt.executeQuery(); rs = stmt.executeQuery();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Successfully retrieved basic details of the application with the id " log.debug("Successfully retrieved basic details of the application with the id "
+ applicationId); + applicationId);
} }
return Util.loadApplication(rs); return Util.loadApplication(rs);
} catch (SQLException e) { } catch (SQLException e) {
throw new ApplicationManagementDAOException( throw new ApplicationManagementDAOException(
"Error occurred while getting application details with app id " + applicationId + "Error occurred while getting application details with app id " + applicationId +
@ -475,6 +542,8 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e); throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e);
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
} catch (UnexpectedServerErrorException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
} finally { } finally {
Util.cleanupResources(stmt, rs); Util.cleanupResources(stmt, rs);
} }
@ -514,14 +583,16 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
@Override @Override
public Application editApplication(Application application, int tenantId) throws ApplicationManagementException { public ApplicationDTO editApplication(ApplicationDTO application, int tenantId)
throws ApplicationManagementDAOException {
int paramIndex = 1; int paramIndex = 1;
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
Application existingApplication = this.getApplicationById(application.getId(), tenantId); //todo this is wrong
ApplicationDTO existingApplication = this.getApplicationById(application.getId(), tenantId);
if (existingApplication == null) { if (existingApplication == null) {
throw new ApplicationManagementException("There doesn't have an application for updating"); throw new ApplicationManagementDAOException("There doesn't have an application for updating");
} }
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
@ -537,9 +608,9 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
existingApplication.getAppCategory())) { existingApplication.getAppCategory())) {
sql += "APP_CATEGORY = ?, "; sql += "APP_CATEGORY = ?, ";
} }
if (application.getIsRestricted() != existingApplication.getIsRestricted()) { // if (application.getIsRestricted() != existingApplication.getIsRestricted()) {
sql += "RESTRICTED = ? "; // sql += "RESTRICTED = ? ";
} // }
if (!application.getSubType().equals(existingApplication.getSubType())) { if (!application.getSubType().equals(existingApplication.getSubType())) {
sql += "SUB_TYPE = ? "; sql += "SUB_TYPE = ? ";
} }
@ -557,9 +628,9 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
existingApplication.getAppCategory())) { existingApplication.getAppCategory())) {
stmt.setString(paramIndex++, application.getAppCategory()); stmt.setString(paramIndex++, application.getAppCategory());
} }
if (application.getIsRestricted() != existingApplication.getIsRestricted()) { // if (application.getIsRestricted() != existingApplication.getIsRestricted()) {
stmt.setBoolean(paramIndex++, application.getIsRestricted()); // stmt.setBoolean(paramIndex++, application.getIsRestricted());
} // }
if (!application.getSubType().equals(existingApplication.getSubType())) { if (!application.getSubType().equals(existingApplication.getSubType())) {
stmt.setString(paramIndex++, application.getSubType()); stmt.setString(paramIndex++, application.getSubType());
} }
@ -597,21 +668,22 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
@Override @Override
public void addTags(List<String> tags, int applicationId, int tenantId) throws ApplicationManagementDAOException { public void addTags(List<String> tags, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to add tags"); log.debug("Request received in DAO Layer to add tags");
} }
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
String sql = "INSERT INTO AP_APP_TAG (TAG, TENANT_ID, AP_APP_ID) VALUES (?, ?, ?)"; String sql = "INSERT INTO AP_APP_TAG "
+ "(TAG,"
+ " TENANT_ID) "
+ "VALUES (?, ?)";
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
conn.setAutoCommit(false);
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
for (String tag : tags) { for (String tag : tags) {
stmt.setString(1, tag); stmt.setString(1, tag);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
stmt.setInt(3, applicationId);
stmt.addBatch(); stmt.addBatch();
} }
stmt.executeBatch(); stmt.executeBatch();
@ -626,6 +698,275 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
} }
@Override
public List<TagDTO> getAllTags(int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get all tags");
}
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
List<TagDTO> tagEntities = new ArrayList<>();
String sql = "SELECT "
+ "AP_APP_TAG.ID AS ID, "
+ "AP_APP_TAG.TAG AS TAG "
+ "FROM AP_APP_TAG "
+ "WHERE TENANT_ID = ?";
conn = this.getDBConnection();
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
rs = stmt.executeQuery();
while(rs.next()){
TagDTO tagDTO = new TagDTO();
tagDTO.setId(rs.getInt("ID"));
tagDTO.setTagName(rs.getString("TAG"));
tagEntities.add(tagDTO);
}
return tagEntities;
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
"Error occurred while obtaining the DB connection when adding tags", e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException("Error occurred while adding tags", e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
@Override
public List<CategoryDTO> getAllCategories(int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get all tags");
}
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
List<CategoryDTO> categories = new ArrayList<>();
String sql = "SELECT "
+ "AP_APP_CATEGORY.ID AS ID, "
+ "AP_APP_CATEGORY.CATEGORY AS CATEGORY "
+ "FROM AP_APP_CATEGORY "
+ "WHERE TENANT_ID = ?";
conn = this.getDBConnection();
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
rs = stmt.executeQuery();
while(rs.next()){
CategoryDTO category = new CategoryDTO();
category.setId(rs.getInt("ID"));
category.setCategoryName(rs.getString("CATEGORY"));
categories.add(category);
}
return categories;
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
"Error occurred while obtaining the DB connection when getting categories", e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException("Error occurred while getting categories", e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
@Override
public void addCategories(List<String> categories, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to add tags");
}
Connection conn;
PreparedStatement stmt = null;
String sql = "INSERT INTO AP_APP_CATEGORY "
+ "(CATEGORY,"
+ " TENANT_ID) "
+ "VALUES (?, ?)";
try {
conn = this.getDBConnection();
stmt = conn.prepareStatement(sql);
for (String category : categories) {
stmt.setString(1, category);
stmt.setInt(2, tenantId);
stmt.addBatch();
}
stmt.executeBatch();
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
"Error occurred while obtaining the DB connection when adding categories.", e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException("Error occurred while adding categories.", e);
} finally {
Util.cleanupResources(stmt, null);
}
}
@Override
public void addCategoryMapping (List<Integer> categoryIds, int applicationId, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to add categories");
}
Connection conn;
PreparedStatement stmt = null;
String sql = "INSERT INTO AP_APP_CATEGORY_MAPPING "
+ "(AP_APP_CATEGORY_ID, "
+ "AP_APP_ID, "
+ " TENANT_ID) "
+ "VALUES (?, ?, ?)";
try {
conn = this.getDBConnection();
stmt = conn.prepareStatement(sql);
for (Integer categoryId : categoryIds) {
stmt.setInt(1, categoryId);
stmt.setInt(2, applicationId);
stmt.setInt(3, tenantId);
stmt.addBatch();
}
stmt.executeBatch();
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
"Error occurred while obtaining the DB connection when adding data into category mapping.", e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException("Error occurred while adding data into category mapping.", e);
} finally {
Util.cleanupResources(stmt, null);
}
}
@Override
public List<Integer> getTagIdsForTagNames(List<String> tagNames, int tenantId)
throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get tag ids for given tag names");
}
try {
Connection conn = this.getDBConnection();
int index = 1;
List<Integer> tagIds = new ArrayList<>();
StringJoiner joiner = new StringJoiner(",",
"SELECT AP_APP_TAG.ID AS ID FROM AP_APP_TAG WHERE AP_APP_TAG.TAG IN (", ") AND TENANT_ID = ?");
tagNames.stream().map(ignored -> "?").forEach(joiner::add);
String query = joiner.toString();
try (PreparedStatement ps = conn.prepareStatement(query)) {
for (String tagName : tagNames) {
ps.setObject(index++, tagName);
}
ps.setInt(index, tenantId);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
tagIds.add(rs.getInt("ID"));
}
}
}
return tagIds;
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
"Error occurred while obtaining the DB connection when adding tags", e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException("Error occurred while adding tags", e);
}
}
public void addTagMapping (List<Integer> tagIds, int applicationId, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to add tags");
}
Connection conn;
PreparedStatement stmt = null;
String sql = "INSERT INTO AP_APP_TAG_MAPPING "
+ "(AP_APP_TAG_ID, "
+ "AP_APP_ID, "
+ " TENANT_ID) "
+ "VALUES (?, ?, ?)";
try {
conn = this.getDBConnection();
stmt = conn.prepareStatement(sql);
for (Integer tagId : tagIds) {
stmt.setInt(1, tagId);
stmt.setInt(2, applicationId);
stmt.setInt(3, tenantId);
stmt.addBatch();
}
stmt.executeBatch();
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
"Error occurred while obtaining the DB connection when adding tags", e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException("Error occurred while adding tags", e);
} finally {
Util.cleanupResources(stmt, null);
}
}
@Override
public List<String> getAppTags(int appId, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get tags for given application.");
}
Connection conn;
List<String> tags = new ArrayList<>();
String sql = "SELECT tag.TAG AS TAG "
+ "FROM "
+ "AP_APP_TAG tag INNER JOIN AP_APP_TAG_MAPPING tag_map ON tag.ID = tag_map.AP_APP_TAG_ID "
+ "INNER JOIN AP_APP app ON tag_map.AP_APP_ID = app.ID "
+ "WHERE app.ID = ? AND app.TENANT_ID = ?";
try {
conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)){
stmt.setInt(1, appId);
stmt.setInt(2, tenantId);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
tags.add(rs.getString("TAG"));
}
}
}
return tags;
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
"Error occurred while obtaining the DB connection when adding tags", e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException("Error occurred while adding tags", e);
}
}
@Override
public List<String> getAppCategories(int appId, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get categories for given application.");
}
Connection conn;
List<String> categories = new ArrayList<>();
String sql = "SELECT CATEGORY "
+ "FROM "
+ "AP_APP_CATEGORY cat INNER JOIN AP_APP_CATEGORY_MAPPING cat_map ON cat.ID = cat_map.AP_APP_CATEGORY_ID "
+ "INNER JOIN AP_APP app ON cat_map.AP_APP_ID = app.ID "
+ "WHERE app.ID = ? AND app.TENANT_ID = ?";
try {
conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)){
stmt.setInt(1, appId);
stmt.setInt(2, tenantId);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
categories.add(rs.getString("CATEGORY"));
}
}
}
return categories;
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
"Error occurred while obtaining the DB connection when adding tags", e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException("Error occurred while adding tags", e);
}
}
@Override @Override
public void deleteTags(List<String> tags, int applicationId, int tenantId) throws ApplicationManagementDAOException { public void deleteTags(List<String> tags, int applicationId, int tenantId) throws ApplicationManagementDAOException {
Connection conn; Connection conn;
@ -644,9 +985,6 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
stmt.addBatch(); stmt.addBatch();
} }
stmt.executeBatch(); stmt.executeBatch();
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
} catch (SQLException e) { } catch (SQLException e) {
@ -658,7 +996,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
@Override @Override
public Application getApplicationByRelease(String appReleaseUUID, int tenantId) public ApplicationDTO getApplicationByRelease(String appReleaseUUID, int tenantId)
throws ApplicationManagementDAOException { throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting application with the UUID (" + appReleaseUUID + ") from the database"); log.debug("Getting application with the UUID (" + appReleaseUUID + ") from the database");
@ -689,10 +1027,10 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
log.debug("Successfully retrieved details of the application with the UUID " + appReleaseUUID); log.debug("Successfully retrieved details of the application with the UUID " + appReleaseUUID);
} }
Application application = null; ApplicationDTO application = null;
while (rs.next()) { while (rs.next()) {
ApplicationRelease appRelease = Util.loadApplicationRelease(rs); ApplicationReleaseDTO appRelease = Util.loadApplicationRelease(rs);
application = new Application(); application = new ApplicationDTO();
application.setId(rs.getInt("APP_ID")); application.setId(rs.getInt("APP_ID"));
application.setName(rs.getString("APP_NAME")); application.setName(rs.getString("APP_NAME"));
@ -700,7 +1038,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
application.setAppCategory(rs.getString("APP_CATEGORY")); application.setAppCategory(rs.getString("APP_CATEGORY"));
application.setSubType(rs.getString("SUB_TYPE")); application.setSubType(rs.getString("SUB_TYPE"));
application.setPaymentCurrency(rs.getString("CURRENCY")); application.setPaymentCurrency(rs.getString("CURRENCY"));
application.setIsRestricted(rs.getBoolean("RESTRICTED")); // application.setIsRestricted(rs.getBoolean("RESTRICTED"));
String unrestrictedRole = rs.getString("ROLE").toLowerCase(); String unrestrictedRole = rs.getString("ROLE").toLowerCase();
List<String> unrestrictedRoleList = new ArrayList<>(); List<String> unrestrictedRoleList = new ArrayList<>();
@ -708,10 +1046,10 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
application.setUnrestrictedRoles(unrestrictedRoleList); application.setUnrestrictedRoles(unrestrictedRoleList);
List<ApplicationRelease> applicationReleaseList = new ArrayList<>(); List<ApplicationReleaseDTO> applicationReleaseList = new ArrayList<>();
applicationReleaseList.add(appRelease); applicationReleaseList.add(appRelease);
application.setApplicationReleases(applicationReleaseList); application.setApplicationReleaseDTOs(applicationReleaseList);
} }
return application; return application;
} catch (SQLException e) { } catch (SQLException e) {
@ -727,23 +1065,25 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
@Override @Override
public int getApplicationId(String appName, String appType, int tenantId) throws ApplicationManagementDAOException { public boolean isValidAppName(String appName, int deviceTypeId, int tenantId) throws ApplicationManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
String sql; String sql;
int id = -1;
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
sql = "SELECT ID FROM AP_APP WHERE NAME = ? AND TYPE = ? AND TENANT_ID = ?"; sql = "SELECT AP_APP.ID AS ID "
+ "FROM AP_APP "
+ "WHERE "
+ "AP_APP.NAME = ? AND "
+ "AP_APP.DEVICE_TYPE_ID = ? AND "
+ "AP_APP.TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, appName); stmt.setString(1, appName);
stmt.setString(2, appType); stmt.setInt(2, deviceTypeId);
stmt.setInt(3, tenantId); stmt.setInt(3, tenantId);
rs = stmt.executeQuery(); rs = stmt.executeQuery();
if (rs.next()) { return rs.next();
id = rs.getInt(1);
}
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
} catch (SQLException e) { } catch (SQLException e) {
@ -751,6 +1091,5 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} finally { } finally {
Util.cleanupResources(stmt, rs); Util.cleanupResources(stmt, rs);
} }
return id;
} }
} }

View File

@ -21,7 +21,9 @@ package org.wso2.carbon.device.application.mgt.core.dao.impl.application.release
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.common.ApplicationRelease; import org.wso2.carbon.device.application.mgt.common.AppLifecycleState;
import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO;
import org.wso2.carbon.device.application.mgt.common.ApplicationReleaseArtifactPaths;
import org.wso2.carbon.device.application.mgt.common.Rating; import org.wso2.carbon.device.application.mgt.common.Rating;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.core.dao.ApplicationReleaseDAO; import org.wso2.carbon.device.application.mgt.core.dao.ApplicationReleaseDAO;
@ -37,52 +39,71 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
/** /**
* GenericApplicationReleaseDAOImpl holds the implementation of ApplicationRelease related DAO operations. * GenericApplicationReleaseDAOImpl holds the implementation of ApplicationReleaseDTO related DAO operations.
*/ */
public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements ApplicationReleaseDAO { public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements ApplicationReleaseDAO {
private static final Log log = LogFactory.getLog(GenericApplicationReleaseDAOImpl.class); private static final Log log = LogFactory.getLog(GenericApplicationReleaseDAOImpl.class);
/** /**
* To insert the Application Release Details. * To insert the ApplicationDTO Release Details.
* *
* @param appId Id of the application * @param appId Id of the application
* @param applicationRelease Application Release the properties of which that need to be inserted. * @param applicationRelease ApplicationDTO Release the properties of which that need to be inserted.
* @param tenantId Tenant Id * @param tenantId Tenant Id
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
@Override public ApplicationRelease createRelease(ApplicationRelease applicationRelease, int appId, int tenantId) @Override public ApplicationReleaseDTO createRelease(ApplicationReleaseDTO applicationRelease, int appId, int tenantId)
throws ApplicationManagementDAOException { throws ApplicationManagementDAOException {
Connection connection; Connection connection;
PreparedStatement statement = null; PreparedStatement statement = null;
ResultSet resultSet = null; ResultSet resultSet = null;
String sql = "INSERT INTO AP_APP_RELEASE (VERSION,TENANT_ID,UUID,RELEASE_TYPE, PACKAGE_NAME, APP_PRICE, " String sql = "INSERT INTO AP_APP_RELEASE "
+ "STORED_LOCATION, ICON_LOCATION, BANNER_LOCATION, SC_1_LOCATION,SC_2_LOCATION,SC_3_LOCATION," + "(DESCRIPTION,"
+ "APP_HASH_VALUE, SHARED_WITH_ALL_TENANTS, APP_META_INFO,AP_APP_ID) " + "VERSION,"
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);"; + "TENANT_ID,"
+ "UUID,"
+ "RELEASE_TYPE,"
+ "PACKAGE_NAME,"
+ "APP_PRICE, "
+ "INSTALLER_LOCATION,"
+ "ICON_LOCATION,"
+ "BANNER_LOCATION,"
+ "SC_1_LOCATION,"
+ "SC_2_LOCATION,"
+ "SC_3_LOCATION,"
+ "APP_HASH_VALUE,"
+ "SHARED_WITH_ALL_TENANTS,"
+ "APP_META_INFO,"
+ "SUPPORTED_OS_VERSIONS,"
+ "CURRENT_STATE,"
+ "AP_APP_ID) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
int index = 0;
String generatedColumns[] = { "ID" }; String generatedColumns[] = { "ID" };
try { try {
connection = this.getDBConnection(); connection = this.getDBConnection();
statement = connection.prepareStatement(sql, generatedColumns); statement = connection.prepareStatement(sql, generatedColumns);
statement.setString(++index, applicationRelease.getVersion()); statement.setString(1, applicationRelease.getDescription());
statement.setInt(++index, tenantId); statement.setString(2, applicationRelease.getVersion());
statement.setString(++index, applicationRelease.getUuid()); statement.setInt(3, tenantId);
statement.setString(++index, String.valueOf(applicationRelease.getReleaseType())); statement.setString(4, applicationRelease.getUuid());
statement.setString(++index, String.valueOf(applicationRelease.getPackageName())); statement.setString(5, String.valueOf(applicationRelease.getReleaseType()));
statement.setDouble(++index, applicationRelease.getPrice()); statement.setString(6, String.valueOf(applicationRelease.getPackageName()));
statement.setString(++index, applicationRelease.getAppStoredLoc()); statement.setDouble(7, applicationRelease.getPrice());
statement.setString(++index, applicationRelease.getIconLoc()); statement.setString(8, applicationRelease.getInstallerName());
statement.setString(++index, applicationRelease.getBannerLoc()); statement.setString(9, applicationRelease.getIconName());
statement.setString(++index, applicationRelease.getScreenshotLoc1()); statement.setString(10, applicationRelease.getBannerName());
statement.setString(++index, applicationRelease.getScreenshotLoc2()); statement.setString(11, applicationRelease.getScreenshotName1());
statement.setString(++index, applicationRelease.getScreenshotLoc3()); statement.setString(12, applicationRelease.getScreenshotName2());
statement.setString(++index, applicationRelease.getAppHashValue()); statement.setString(13, applicationRelease.getScreenshotName3());
statement.setInt(++index, applicationRelease.getIsSharedWithAllTenants()); statement.setString(14, applicationRelease.getAppHashValue());
statement.setString(++index, applicationRelease.getMetaData()); statement.setBoolean(15, applicationRelease.getIsSharedWithAllTenants());
statement.setInt(++index, appId); statement.setString(16, applicationRelease.getMetaData());
statement.setString(17, applicationRelease.getSupportedOsVersions());
statement.setString(18, applicationRelease.getCurrentState());
statement.setInt(19, appId);
statement.executeUpdate(); statement.executeUpdate();
resultSet = statement.getGeneratedKeys(); resultSet = statement.getGeneratedKeys();
if (resultSet.next()) { if (resultSet.next()) {
@ -108,9 +129,9 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
* @param versionName version name of the application. * @param versionName version name of the application.
* @param releaseType type of the application release. * @param releaseType type of the application release.
* @param tenantId Tenant Id * @param tenantId Tenant Id
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
@Override public ApplicationRelease getRelease(String applicationName, String applicationType, String versionName, @Override public ApplicationReleaseDTO getRelease(String applicationName, String applicationType, String versionName,
String releaseType, int tenantId) throws ApplicationManagementDAOException { String releaseType, int tenantId) throws ApplicationManagementDAOException {
//todo no usage //todo no usage
Connection connection; Connection connection;
@ -158,9 +179,9 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
* @param applicationId ID of the application. * @param applicationId ID of the application.
* @param releaseUuid UUID of the application release. * @param releaseUuid UUID of the application release.
* @param tenantId Tenant Id * @param tenantId Tenant Id
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
@Override public ApplicationRelease getReleaseByIds(int applicationId, String releaseUuid, int tenantId) @Override public ApplicationReleaseDTO getReleaseByIds(int applicationId, String releaseUuid, int tenantId)
throws ApplicationManagementDAOException { throws ApplicationManagementDAOException {
Connection connection; Connection connection;
@ -201,19 +222,65 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
} }
} }
@Override
public ApplicationReleaseDTO getReleaseByUUID( String uuid, int tenantId) throws ApplicationManagementDAOException {
Connection connection;
String sql =
"SELECT AR.DESCRIPTION AS RELEASE_DESCRIPTION, "
+ "AR.VERSION AS RELEASE_VERSION, "
+ "AR.UUID AS RELEASE_UUID, "
+ "AR.RELEASE_TYPE AS RELEASE_TYPE, "
+ "AR.INSTALLER_LOCATION AS AP_RELEASE_STORED_LOC, "
+ "AR.ICON_LOCATION AS AP_RELEASE_ICON_LOC, "
+ "AR.BANNER_LOCATION AS AP_RELEASE_BANNER_LOC, "
+ "AR.SC_1_LOCATION AS AP_RELEASE_SC1, "
+ "AR.SC_2_LOCATION AS AP_RELEASE_SC2, "
+ "AR.SC_3_LOCATION AS AP_RELEASE_SC3, "
+ "AR.APP_HASH_VALUE AS RELEASE_HASH_VALUE, "
+ "AR.APP_PRICE AS RELEASE_PRICE, "
+ "AR.APP_META_INFO AS RELEASE_META_INFO, "
+ "AR.SUPPORTED_OS_VERSIONS AS RELEASE_SUP_OS_VERSIONS, "
+ "AR.RATING AS RELEASE_RATING, "
+ "AR.CURRENT_STATE AS RELEASE_CURRENT_STATE, AR.RATED_USERS AS RATED_USER_COUNT "
+ "FROM AP_APP_RELEASE AS AR "
+ "WHERE AR.UUID = ? AND AR.TENAT_ID = ?";
try {
connection = this.getDBConnection();
try (PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, uuid);
statement.setInt(2, tenantId);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
return Util.loadAppRelease(resultSet);
}
return null;
}
}
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
"Database connection exception while trying to get the release details of the UUID of the application release: "
+ uuid, e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
"Error while getting release details of the UUID of the application " + "release: " + uuid
+ " , while executing the query " + sql, e);
}
}
/** /**
* To insert the application release properties. * To insert the application release properties.
* *
* @param applicationId Id of the application. * @param applicationId Id of the application.
* @param tenantId Tenant Id * @param tenantId Tenant Id
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
@Override public List<ApplicationRelease> getReleases(int applicationId, int tenantId) @Override public List<ApplicationReleaseDTO> getReleases(int applicationId, int tenantId)
throws ApplicationManagementDAOException { throws ApplicationManagementDAOException {
Connection connection; Connection connection;
PreparedStatement statement = null; PreparedStatement statement = null;
ResultSet resultSet = null; ResultSet resultSet = null;
List<ApplicationRelease> applicationReleases = new ArrayList<>(); List<ApplicationReleaseDTO> applicationReleases = new ArrayList<>();
String sql = "SELECT AR.ID AS RELEASE_ID, AR.VERSION AS RELEASE_VERSION, AR.UUID, AR.RELEASE_TYPE " String sql = "SELECT AR.ID AS RELEASE_ID, AR.VERSION AS RELEASE_VERSION, AR.UUID, AR.RELEASE_TYPE "
+ "AS RELEASE_TYPE, AR.PACKAGE_NAME AS PACKAGE_NAME, AR.APP_PRICE, AR.STORED_LOCATION, AR.ICON_LOCATION, " + "AS RELEASE_TYPE, AR.PACKAGE_NAME AS PACKAGE_NAME, AR.APP_PRICE, AR.STORED_LOCATION, AR.ICON_LOCATION, "
+ "AR.BANNER_LOCATION, AR.SC_1_LOCATION AS SCREEN_SHOT_1, AR.SC_2_LOCATION AS SCREEN_SHOT_2, " + "AR.BANNER_LOCATION, AR.SC_1_LOCATION AS SCREEN_SHOT_1, AR.SC_2_LOCATION AS SCREEN_SHOT_2, "
@ -229,7 +296,7 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
resultSet = statement.executeQuery(); resultSet = statement.executeQuery();
while (resultSet.next()) { while (resultSet.next()) {
ApplicationRelease applicationRelease = Util.loadApplicationRelease(resultSet); ApplicationReleaseDTO applicationRelease = Util.loadApplicationRelease(resultSet);
applicationReleases.add(applicationRelease); applicationReleases.add(applicationRelease);
} }
return applicationReleases; return applicationReleases;
@ -247,12 +314,12 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
//todo this has to be removed //todo this has to be removed
@Override @Override
public List<ApplicationRelease> getReleaseByState(int appId, int tenantId, String state) throws public List<ApplicationReleaseDTO> getReleaseByState(int appId, int tenantId, String state) throws
ApplicationManagementDAOException { ApplicationManagementDAOException {
Connection connection; Connection connection;
PreparedStatement statement = null; PreparedStatement statement = null;
ResultSet resultSet = null; ResultSet resultSet = null;
List<ApplicationRelease> applicationReleases = new ArrayList<>(); List<ApplicationReleaseDTO> applicationReleases = new ArrayList<>();
String sql = "SELECT AR.ID AS RELEASE_ID, AR.VERSION AS RELEASE_VERSION, AR.UUID AS UUID, AR.RELEASE_TYPE AS " String sql = "SELECT AR.ID AS RELEASE_ID, AR.VERSION AS RELEASE_VERSION, AR.UUID AS UUID, AR.RELEASE_TYPE AS "
+ "RELEASE_TYPE, AR.PACKAGE_NAME AS PACKAGE_NAME, AR.APP_PRICE AS APP_PRICE, AR.STORED_LOCATION AS " + "RELEASE_TYPE, AR.PACKAGE_NAME AS PACKAGE_NAME, AR.APP_PRICE AS APP_PRICE, AR.STORED_LOCATION AS "
+ "STORED_LOCATION, AR.BANNER_LOCATION AS BANNER_LOCATION, ICON_LOCATION, AR.SC_1_LOCATION AS " + "STORED_LOCATION, AR.BANNER_LOCATION AS BANNER_LOCATION, ICON_LOCATION, AR.SC_1_LOCATION AS "
@ -272,7 +339,7 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
resultSet = statement.executeQuery(); resultSet = statement.executeQuery();
while (resultSet.next()) { while (resultSet.next()) {
ApplicationRelease appRelease = Util.loadApplicationRelease(resultSet); ApplicationReleaseDTO appRelease = Util.loadApplicationRelease(resultSet);
applicationReleases.add(appRelease); applicationReleases.add(appRelease);
} }
return applicationReleases; return applicationReleases;
@ -293,7 +360,7 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
* *
* @param uuid UUID of the application Release. * @param uuid UUID of the application Release.
* @param rating given stars for the application release. * @param rating given stars for the application release.
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
@Override public void updateRatingValue(String uuid, double rating, int ratedUsers) @Override public void updateRatingValue(String uuid, double rating, int ratedUsers)
throws ApplicationManagementDAOException { throws ApplicationManagementDAOException {
@ -322,7 +389,7 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
* To retrieve rating of an application release. * To retrieve rating of an application release.
* *
* @param uuid UUID of the application Release. * @param uuid UUID of the application Release.
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
@Override public Rating getRating(String uuid, int tenantId) throws ApplicationManagementDAOException { @Override public Rating getRating(String uuid, int tenantId) throws ApplicationManagementDAOException {
Connection connection; Connection connection;
@ -357,39 +424,59 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
/** /**
* To insert the application release properties. * To insert the application release properties.
* *
* @param applicationRelease Application Release the properties of which that need to be inserted. * @param applicationReleaseDTO ApplicationDTO Release the properties of which that need to be inserted.
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
@Override public ApplicationRelease updateRelease(int applicationId, ApplicationRelease applicationRelease, int tenantId) @Override
public ApplicationReleaseDTO updateRelease(ApplicationReleaseDTO applicationReleaseDTO, int tenantId)
throws ApplicationManagementDAOException { throws ApplicationManagementDAOException {
Connection connection; Connection connection;
PreparedStatement statement = null; PreparedStatement statement = null;
String sql = "UPDATE AP_APP_RELEASE SET VERSION = ?, UUID = ?, RELEASE_TYPE = ?, PACKAGE_NAME = ?," String sql = "UPDATE AP_APP_RELEASE "
+ " APP_PRICE = ?, STORED_LOCATION = ?, BANNER_LOCATION = ?, ICON_LOCATION =?, SC_1_LOCATION = ?, " + + "SET "
"SC_2_LOCATION = ?," + "DESCRIPTION = ?, "
+ " SC_3_LOCATION = ?, APP_HASH_VALUE = ?, SHARED_WITH_ALL_TENANTS = ?, APP_META_INFO = ? " + "VERSION = ?, "
+ "WHERE AP_APP_ID = ? AND TENANT_ID = ? AND ID = ?;"; + "UUID = ?, "
+ "RELEASE_TYPE = ?, "
+ "PACKAGE_NAME = ?, "
+ "APP_PRICE = ?, "
+ "INSTALLER_LOCATION = ?, "
+ "BANNER_LOCATION = ?, "
+ "ICON_LOCATION = ?, "
+ "SC_1_LOCATION = ?, "
+ "SC_2_LOCATION = ?, "
+ "SC_3_LOCATION = ?, "
+ "APP_HASH_VALUE = ?, "
+ "SHARED_WITH_ALL_TENANTS = ?, "
+ "APP_META_INFO = ?, "
+ "SUPPORTED_OS_VERSIONS = ?, "
+ "CURRENT_STATE = ? "
+ "WHERE ID = ? AND TENANT_ID = ? ";
try { try {
connection = this.getDBConnection(); connection = this.getDBConnection();
statement = connection.prepareStatement(sql); statement = connection.prepareStatement(sql);
statement.setString(1, applicationRelease.getVersion()); statement.setString(1, applicationReleaseDTO.getDescription());
statement.setString(2, applicationRelease.getUuid()); statement.setString(2, applicationReleaseDTO.getVersion());
statement.setString(3, applicationRelease.getReleaseType()); statement.setString(3, applicationReleaseDTO.getUuid());
statement.setString(4, applicationRelease.getPackageName()); statement.setString(4, applicationReleaseDTO.getReleaseType());
statement.setDouble(5, applicationRelease.getPrice()); statement.setString(5, applicationReleaseDTO.getPackageName());
statement.setString(6, applicationRelease.getAppStoredLoc()); statement.setDouble(6, applicationReleaseDTO.getPrice());
statement.setString(7, applicationRelease.getBannerLoc()); statement.setString(7, applicationReleaseDTO.getInstallerName());
statement.setString(8, applicationRelease.getIconLoc()); statement.setString(8, applicationReleaseDTO.getBannerName());
statement.setString(9, applicationRelease.getScreenshotLoc1()); statement.setString(9, applicationReleaseDTO.getIconName());
statement.setString(10, applicationRelease.getScreenshotLoc2()); statement.setString(10, applicationReleaseDTO.getScreenshotName1());
statement.setString(11, applicationRelease.getScreenshotLoc3()); statement.setString(11, applicationReleaseDTO.getScreenshotName2());
statement.setString(12, applicationRelease.getAppHashValue()); statement.setString(12, applicationReleaseDTO.getScreenshotName3());
statement.setInt(13, applicationRelease.getIsSharedWithAllTenants()); statement.setString(13, applicationReleaseDTO.getAppHashValue());
statement.setString(14, applicationRelease.getMetaData()); statement.setBoolean(14, applicationReleaseDTO.getIsSharedWithAllTenants());
statement.setInt(15, applicationId); statement.setString(15, applicationReleaseDTO.getMetaData());
statement.setInt(16, tenantId); statement.setString(16, applicationReleaseDTO.getSupportedOsVersions());
statement.setInt(17, applicationRelease.getId()); statement.setString(17, applicationReleaseDTO.getCurrentState());
statement.executeUpdate(); statement.setInt(18, tenantId);
statement.setInt(19, applicationReleaseDTO.getId());
if (statement.executeUpdate() == 0) {
return null;
}
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException( throw new ApplicationManagementDAOException(
"Database connection exception while trying to update the application release", e); "Database connection exception while trying to update the application release", e);
@ -399,7 +486,7 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
} finally { } finally {
Util.cleanupResources(statement, null); Util.cleanupResources(statement, null);
} }
return applicationRelease; return applicationReleaseDTO;
} }
/** /**
@ -407,7 +494,7 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
* *
* @param id Id of the application Release. * @param id Id of the application Release.
* @param version version name of the application release. * @param version version name of the application release.
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
@Override public void deleteRelease(int id, String version) throws ApplicationManagementDAOException { @Override public void deleteRelease(int id, String version) throws ApplicationManagementDAOException {
Connection connection; Connection connection;
@ -432,35 +519,27 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
} }
@Override @Override
public boolean verifyReleaseExistenceByHash(int appId, String hashVal, int tenantId) throws ApplicationManagementDAOException { public boolean verifyReleaseExistenceByHash(String hashVal, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Verifying application release existence by application id:" + appId log.debug("Verifying application release existence by application hash value: " + hashVal);
+ " and application hash value: " + hashVal);
} }
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
String sql = String sql = "SELECT AR.ID AS RELEASE_ID FROM AP_APP_RELEASE AS AR WHERE AR.APP_HASH_VALUE = ? AND "
"SELECT AR.ID AS RELEASE_ID FROM AP_APP_RELEASE AS AR WHERE AR.AP_APP_ID = ? AND " + "AR.TENANT_ID = ?;";
+ "AR.APP_HASH_VALUE = ? AND AR.TENANT_ID = ?;";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, appId); stmt.setString(1, hashVal);
stmt.setString(2, hashVal); stmt.setInt(2, tenantId);
stmt.setInt(3, tenantId);
rs = stmt.executeQuery(); rs = stmt.executeQuery();
if (log.isDebugEnabled()) {
log.debug("Successfully retrieved basic details of the application release with the application ID "
+ appId + " Application release hash value: " + hashVal);
}
return rs.next(); return rs.next();
} catch (SQLException e) { } catch (SQLException e) {
throw new ApplicationManagementDAOException( throw new ApplicationManagementDAOException(
"Error occurred while getting application release details with app ID: " + appId "Error occurred while getting application release details for application release hash value: "
+ " App release hash value: " + hashVal + " While executing query ", e); + hashVal + " While executing query ", e);
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
} finally { } finally {
@ -528,7 +607,7 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Successfully retrieved basic details of the application release with the application ID " log.debug("Successfully retrieved basic details of the application release with the application ID "
+ appId + " Application release uuid: " + uuid); + appId + " ApplicationDTO release uuid: " + uuid);
} }
return rs.next(); return rs.next();
} catch (SQLException e) { } catch (SQLException e) {
@ -575,4 +654,81 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
Util.cleanupResources(stmt, rs); Util.cleanupResources(stmt, rs);
} }
} }
@Override
public String getReleaseHashValue(String uuid, int tenantId) throws ApplicationManagementDAOException{
if (log.isDebugEnabled()) {
log.debug("Getting application release artifact stored location paths for: " + uuid);
}
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
String releaseHashValue = null;
try {
conn = this.getDBConnection();
String sql = "SELECT "
+ "AR.APP_HASH_VALUE AS HASH_VALUE "
+ "FROM AP_APP_RELEASE AR "
+ "WHERE AR.UUID = ? AND AR.TENANT_ID = ?;";
stmt = conn.prepareStatement(sql);
stmt.setString(1, uuid);
stmt.setInt(2, tenantId);
rs = stmt.executeQuery();
if (log.isDebugEnabled()) {
log.debug(
"Successfully retrieved application release artifact details of the application release with the application UUID: "
+ uuid);
}
if (rs.getFetchSize() >1){
String msg = "Found more than one application release for UUID: " + uuid;
log.error(msg);
throw new ApplicationManagementDAOException(msg);
}
while(rs.next()){
releaseHashValue = rs.getString("HASH_VALUE");
}
return releaseHashValue;
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
"Error occurred when executing query to get application release artifact paths for App release uuid: "
+ uuid, e);
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
@Override
public boolean isActiveReleaseExisitForPackageName(String packageName, int tenantId, String inactiveState)
throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Verifying application release existence for package name:" + packageName);
}
Connection conn;
try {
conn = this.getDBConnection();
String sql = "SELECT AR.ID AS RELEASE_ID "
+ "FROM AP_APP_RELEASE AS AR "
+ "WHERE AR.PACKAGE_NAME = ? AND AR.CURRENT_STATE != ? AND AR.TENANT_ID = ? LIMIT 1";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, packageName);
stmt.setString(2, inactiveState);
stmt.setInt(3, tenantId);
try (ResultSet rs = stmt.executeQuery()) {
return rs.next();
}
}
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
"Error occurred while getting application release details for package name: " + packageName, e);
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
}
}
} }

View File

@ -18,7 +18,8 @@
*/ */
package org.wso2.carbon.device.application.mgt.core.dao.impl.lifecyclestate; package org.wso2.carbon.device.application.mgt.core.dao.impl.lifecyclestate;
import org.wso2.carbon.device.application.mgt.common.LifecycleState; import org.wso2.carbon.device.application.mgt.common.AppLifecycleState;
import org.wso2.carbon.device.application.mgt.common.dto.LifecycleStateDTO;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.core.dao.LifecycleStateDAO; 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.common.Util;
@ -40,7 +41,7 @@ import java.util.List;
public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements LifecycleStateDAO { public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements LifecycleStateDAO {
@Override @Override
public LifecycleState getLatestLifeCycleStateByReleaseID(int applicationReleaseId) throws LifeCycleManagementDAOException { public LifecycleStateDTO getLatestLifeCycleStateByReleaseID(int applicationReleaseId) throws LifeCycleManagementDAOException {
Connection conn = null; Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
@ -64,7 +65,7 @@ public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements Lif
} }
} }
public LifecycleState getLatestLifeCycleState(int appId, String uuid) throws LifeCycleManagementDAOException{ public LifecycleStateDTO getLatestLifeCycleState(int appId, String uuid) throws LifeCycleManagementDAOException{
Connection conn = null; Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
@ -87,13 +88,42 @@ public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements Lif
} finally { } finally {
Util.cleanupResources(stmt, rs); Util.cleanupResources(stmt, rs);
} }
} }
public String getAppReleaseCreatedUsername(int appId, String uuid, int tenantId) throws LifeCycleManagementDAOException{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = this.getDBConnection();
String sql = "SELECT UPDATED_BY FROM AP_APP_LIFECYCLE_STATE WHERE AP_APP_ID=? AND "
+ "AP_APP_RELEASE_ID=(SELECT ID FROM AP_APP_RELEASE WHERE UUID=?) AND CURRENT_STATE = ? AND TENANT_ID = ?;";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, appId);
stmt.setString(2, uuid);
stmt.setString(3, AppLifecycleState.CREATED.toString());
stmt.setInt(4, tenantId);
rs = stmt.executeQuery();
if (rs.next()) {
return rs.getString("UPDATED_BY");
}
return null;
} 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 to get latest"
+ " lifecycle state for a specific application", e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
@Override @Override
public List<LifecycleState> getLifecycleStates(int appReleaseId) throws LifeCycleManagementDAOException { public List<LifecycleStateDTO> getLifecycleStates(int appReleaseId) throws LifeCycleManagementDAOException {
List<LifecycleState> lifecycleStates = new ArrayList<>(); List<LifecycleStateDTO> lifecycleStates = new ArrayList<>();
Connection conn = null; Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
@ -105,7 +135,7 @@ public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements Lif
stmt.setInt(1,appReleaseId); stmt.setInt(1,appReleaseId);
rs = stmt.executeQuery(); rs = stmt.executeQuery();
while (rs.next()) { while (rs.next()) {
LifecycleState lifecycleState = new LifecycleState(); LifecycleStateDTO lifecycleState = new LifecycleStateDTO();
lifecycleState.setId(rs.getInt("ID")); lifecycleState.setId(rs.getInt("ID"));
lifecycleState.setCurrentState(rs.getString("CURRENT_STATE")); lifecycleState.setCurrentState(rs.getString("CURRENT_STATE"));
lifecycleState.setPreviousState(rs.getString("PREVIOUS_STATE")); lifecycleState.setPreviousState(rs.getString("PREVIOUS_STATE"));
@ -125,14 +155,20 @@ public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements Lif
} }
@Override @Override
public void addLifecycleState(LifecycleState state, int appId, String uuid, int tenantId) throws LifeCycleManagementDAOException { public void addLifecycleState(LifecycleStateDTO state, int appId, String uuid, int tenantId) throws LifeCycleManagementDAOException {
Connection conn = null; Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
String sql = "INSERT INTO AP_APP_LIFECYCLE_STATE (CURRENT_STATE, PREVIOUS_STATE, TENANT_ID, UPDATED_BY, " String sql = "INSERT INTO AP_APP_LIFECYCLE_STATE "
+ "UPDATED_AT, AP_APP_RELEASE_ID, AP_APP_ID) VALUES (?,?, ?, ?, ?, " + "(CURRENT_STATE, "
+ "(SELECT ID FROM AP_APP_RELEASE WHERE UUID=?),?);"; + "PREVIOUS_STATE, "
+ "TENANT_ID, "
+ "UPDATED_BY, "
+ "UPDATED_AT, "
+ "AP_APP_RELEASE_ID, "
+ "AP_APP_ID) "
+ "VALUES (?,?, ?, ?, ?, (SELECT ID FROM AP_APP_RELEASE WHERE UUID=?),?);";
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
Timestamp timestamp = new Timestamp(calendar.getTime().getTime()); Timestamp timestamp = new Timestamp(calendar.getTime().getTime());
@ -177,11 +213,11 @@ public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements Lif
} }
} }
private LifecycleState constructLifecycle(ResultSet rs) throws LifeCycleManagementDAOException { private LifecycleStateDTO constructLifecycle(ResultSet rs) throws LifeCycleManagementDAOException {
LifecycleState lifecycleState = null; LifecycleStateDTO lifecycleState = null;
try { try {
if (rs !=null && rs.next()) { if (rs !=null && rs.next()) {
lifecycleState = new LifecycleState(); lifecycleState = new LifecycleStateDTO();
lifecycleState.setId(rs.getInt("ID")); lifecycleState.setId(rs.getInt("ID"));
lifecycleState.setCurrentState(rs.getString("CURRENT_STATE")); lifecycleState.setCurrentState(rs.getString("CURRENT_STATE"));
lifecycleState.setPreviousState(rs.getString("PREVIOUS_STATE")); lifecycleState.setPreviousState(rs.getString("PREVIOUS_STATE"));

View File

@ -79,7 +79,9 @@ public class GenericVisibilityDAOImpl extends AbstractDAOImpl implements Visibil
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
List<String> unrestrictedRoles = new ArrayList<>(); List<String> unrestrictedRoles = new ArrayList<>();
String sql = "SELECT ID, ROLE FROM AP_UNRESTRICTED_ROLE WHERE AP_APP_ID = ? AND TENANT_ID = ?;"; String sql = "SELECT ROLE "
+ "FROM AP_UNRESTRICTED_ROLE "
+ "WHERE AP_APP_ID = ? AND TENANT_ID = ?";
try{ try{
conn = this.getDBConnection(); conn = this.getDBConnection();
conn.setAutoCommit(false); conn.setAutoCommit(false);
@ -89,7 +91,7 @@ public class GenericVisibilityDAOImpl extends AbstractDAOImpl implements Visibil
rs = stmt.executeQuery(); rs = stmt.executeQuery();
while (rs.next()){ while (rs.next()){
unrestrictedRoles.add(rs.getString("ROLE").toLowerCase()); unrestrictedRoles.add(rs.getString("ROLE"));
} }
return unrestrictedRoles; return unrestrictedRoles;

View File

@ -21,7 +21,7 @@ package org.wso2.carbon.device.application.mgt.core.exception;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
/** /**
* Exception thrown during the Application Management DAO operations. * Exception thrown during the ApplicationDTO Management DAO operations.
*/ */
public class ApplicationManagementDAOException extends ApplicationManagementException { public class ApplicationManagementDAOException extends ApplicationManagementException {

View File

@ -24,28 +24,25 @@ import com.dd.plist.NSString;
import com.dd.plist.PropertyListFormatException; import com.dd.plist.PropertyListFormatException;
import com.dd.plist.PropertyListParser; import com.dd.plist.PropertyListParser;
import net.dongliu.apk.parser.bean.ApkMeta; import net.dongliu.apk.parser.bean.ApkMeta;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.routines.UrlValidator;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.common.ApplicationRelease; import org.wso2.carbon.device.application.mgt.common.ApplicationInstaller;
import org.wso2.carbon.device.application.mgt.common.ApplicationType; import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO;
import org.wso2.carbon.device.application.mgt.common.DeviceType; import org.wso2.carbon.device.application.mgt.common.DeviceTypes;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationStorageManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationStorageManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.RequestValidatingException;
import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager;
import org.wso2.carbon.device.application.mgt.core.exception.ParsingException; import org.wso2.carbon.device.application.mgt.core.exception.ParsingException;
import org.wso2.carbon.device.application.mgt.core.util.ArtifactsParser; import org.wso2.carbon.device.application.mgt.core.util.ArtifactsParser;
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.Constants;
import org.wso2.carbon.device.application.mgt.core.util.StorageManagementUtil; import org.wso2.carbon.device.application.mgt.core.util.StorageManagementUtil;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.ParserConfigurationException;
import java.io.*; import java.io.*;
import java.nio.file.Files;
import java.text.ParseException; import java.text.ParseException;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -54,7 +51,7 @@ import java.util.Objects;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream; import java.util.zip.ZipInputStream;
import static org.wso2.carbon.device.application.mgt.core.util.StorageManagementUtil.deleteDir; import static org.wso2.carbon.device.application.mgt.core.util.StorageManagementUtil.delete;
import static org.wso2.carbon.device.application.mgt.core.util.StorageManagementUtil.saveFile; import static org.wso2.carbon.device.application.mgt.core.util.StorageManagementUtil.saveFile;
/** /**
@ -78,44 +75,44 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
} }
@Override @Override
public ApplicationRelease uploadImageArtifacts(ApplicationRelease applicationRelease, InputStream iconFileStream, public ApplicationReleaseDTO uploadImageArtifacts(ApplicationReleaseDTO applicationRelease, InputStream iconFileStream,
InputStream bannerFileStream, List<InputStream> screenShotStreams) InputStream bannerFileStream, List<InputStream> screenShotStreams)
throws ResourceManagementException { throws ResourceManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String artifactDirectoryPath; String artifactDirectoryPath;
String iconStoredLocation; String iconStoredLocation;
String bannerStoredLocation; String bannerStoredLocation;
String scStoredLocation; String scStoredLocation = null;
try { try {
artifactDirectoryPath = storagePath + applicationRelease.getAppHashValue(); artifactDirectoryPath = storagePath + applicationRelease.getAppHashValue();
StorageManagementUtil.createArtifactDirectory(artifactDirectoryPath); StorageManagementUtil.createArtifactDirectory(artifactDirectoryPath);
iconStoredLocation = artifactDirectoryPath + File.separator + Constants.IMAGE_ARTIFACTS[0]; iconStoredLocation = artifactDirectoryPath + File.separator + applicationRelease.getIconName();
bannerStoredLocation = artifactDirectoryPath + File.separator + Constants.IMAGE_ARTIFACTS[1]; bannerStoredLocation = artifactDirectoryPath + File.separator + applicationRelease.getBannerName();
if (iconFileStream != null) { if (iconFileStream != null) {
saveFile(iconFileStream, iconStoredLocation); saveFile(iconFileStream, iconStoredLocation);
applicationRelease.setIconLoc(iconStoredLocation);
} }
if (bannerFileStream != null) { if (bannerFileStream != null) {
saveFile(bannerFileStream, bannerStoredLocation); saveFile(bannerFileStream, bannerStoredLocation);
applicationRelease.setBannerLoc(bannerStoredLocation);
} }
if (!screenShotStreams.isEmpty()) { if (!screenShotStreams.isEmpty()) {
if (screenShotStreams.size() > screenShotMaxCount) { if (screenShotStreams.size() > screenShotMaxCount) {
throw new ApplicationStorageManagementException("Maximum limit for the screen-shot exceeds"); String msg = "Maximum limit for the screen-shot exceeds. You can't upload more than three "
+ "screenshot for an application release";
log.error(msg);
throw new ApplicationStorageManagementException(msg);
} }
int count = 1; int count = 1;
for (InputStream screenshotStream : screenShotStreams) { for (InputStream screenshotStream : screenShotStreams) {
scStoredLocation = artifactDirectoryPath + File.separator + Constants.IMAGE_ARTIFACTS[2] + count;
if (count == 1) { if (count == 1) {
applicationRelease.setScreenshotLoc1(scStoredLocation); scStoredLocation = artifactDirectoryPath + File.separator + applicationRelease.getScreenshotName1();
} }
if (count == 2) { if (count == 2) {
applicationRelease.setScreenshotLoc2(scStoredLocation); scStoredLocation = artifactDirectoryPath + File.separator + applicationRelease.getScreenshotName2();
} }
if (count == 3) { if (count == 3) {
applicationRelease.setScreenshotLoc3(scStoredLocation); scStoredLocation = artifactDirectoryPath + File.separator + applicationRelease.getScreenshotName3();
} }
saveFile(screenshotStream, scStoredLocation); saveFile(screenshotStream, scStoredLocation);
count++; count++;
@ -126,179 +123,150 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
throw new ApplicationStorageManagementException("IO Exception while saving the screens hots for " + throw new ApplicationStorageManagementException("IO Exception while saving the screens hots for " +
"the application " + applicationRelease.getUuid(), e); "the application " + applicationRelease.getUuid(), e);
} catch (ApplicationStorageManagementException e) { } catch (ApplicationStorageManagementException e) {
throw new ApplicationStorageManagementException("Application Management DAO exception while trying to " throw new ApplicationStorageManagementException("ApplicationDTO Management DAO exception while trying to "
+ "update the screen-shot count for the application " + applicationRelease.getUuid() + + "update the screen-shot count for the application " + applicationRelease.getUuid() +
" for the tenant id " + tenantId, e); " for the tenant id " + tenantId, e);
} }
} }
@Override @Override
public ApplicationRelease updateImageArtifacts(ApplicationRelease applicationRelease, InputStream public void deleteImageArtifacts(ApplicationReleaseDTO applicationReleaseDTO)
iconFileStream, InputStream bannerFileStream, List<InputStream> screenShotStreams)
throws ResourceManagementException { throws ResourceManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
try { try {
if (iconFileStream != null) { String iconName = applicationReleaseDTO.getIconName();
deleteApplicationReleaseArtifacts(applicationRelease.getIconLoc()); String bannerName = applicationReleaseDTO.getBannerName();
String sc1 = applicationReleaseDTO.getScreenshotName1();
String sc2 = applicationReleaseDTO.getScreenshotName2();
String sc3 = applicationReleaseDTO.getScreenshotName3();
String hashValue = applicationReleaseDTO.getAppHashValue();
if (iconName != null) {
deleteApplicationReleaseArtifacts(
storagePath + Constants.FORWARD_SLASH + hashValue + Constants.FORWARD_SLASH + iconName);
} }
if (bannerFileStream != null) { if (bannerName != null) {
deleteApplicationReleaseArtifacts(applicationRelease.getBannerLoc()); deleteApplicationReleaseArtifacts(
storagePath + Constants.FORWARD_SLASH + hashValue + Constants.FORWARD_SLASH + bannerName);
} }
if (!screenShotStreams.isEmpty()) {
if (screenShotStreams.size() > screenShotMaxCount) { if (sc1 != null) {
throw new ApplicationStorageManagementException("Maximum limit for the screen-shot exceeds"); deleteApplicationReleaseArtifacts(
storagePath + Constants.FORWARD_SLASH + hashValue + Constants.FORWARD_SLASH + sc1);
} }
int count = 1; if (sc2 != null) {
while (count < screenShotStreams.size()) { deleteApplicationReleaseArtifacts(
if (count == 1) { storagePath + Constants.FORWARD_SLASH + hashValue + Constants.FORWARD_SLASH + sc2);
deleteApplicationReleaseArtifacts(applicationRelease.getScreenshotLoc1());
} }
if (count == 2) { if (sc3 != null) {
deleteApplicationReleaseArtifacts(applicationRelease.getScreenshotLoc2()); deleteApplicationReleaseArtifacts(
storagePath + Constants.FORWARD_SLASH + hashValue + Constants.FORWARD_SLASH + sc3);
} }
if (count == 3) {
deleteApplicationReleaseArtifacts(applicationRelease.getScreenshotLoc3());
}
count++;
}
}
return applicationRelease;
} catch (ApplicationStorageManagementException e) { } catch (ApplicationStorageManagementException e) {
throw new ApplicationStorageManagementException("Application Storage exception while trying to" throw new ApplicationStorageManagementException("ApplicationDTO Storage exception while trying to"
+ " update the screen-shot count for the application Release " + applicationRelease.getUuid() + + " update the screen-shot count for the application Release " + applicationReleaseDTO.getUuid() +
" for the tenant " + tenantId, e); " for the tenant " + tenantId, e);
} }
} }
@Override public ApplicationInstaller getAppInstallerData(InputStream binaryFile, String deviceType)
public ApplicationRelease uploadReleaseArtifact(ApplicationRelease applicationRelease, String appType, throws ApplicationStorageManagementException {
String deviceType, InputStream binaryFile) throws ResourceManagementException, RequestValidatingException { ApplicationInstaller applicationInstaller = new ApplicationInstaller();
try { try {
if (ApplicationType.WEB_CLIP.toString().equals(appType)) { if (DeviceTypes.ANDROID.toString().equalsIgnoreCase(deviceType)) {
applicationRelease.setVersion(Constants.DEFAULT_VERSION); ApkMeta apkMeta = ArtifactsParser.readAndroidManifestFile(binaryFile);
UrlValidator urlValidator = new UrlValidator(); applicationInstaller.setVersion(apkMeta.getVersionName());
if (applicationRelease.getUrl() == null || !urlValidator.isValid(applicationRelease.getUrl())) { applicationInstaller.setPackageName(apkMeta.getPackageName());
throw new RequestValidatingException("Request payload doesn't contains Web Clip URL " + } else if (DeviceTypes.IOS.toString().equalsIgnoreCase(deviceType)) {
"with application release object or Web " +
"Clip URL is invalid");
}
applicationRelease.setAppStoredLoc(applicationRelease.getUrl());
applicationRelease.setAppHashValue(null);
return applicationRelease;
}
String artifactDirectoryPath;
String md5OfApp;
InputStream[] cloneInputStream = cloneInputStream(binaryFile);
md5OfApp = getMD5(binaryFile);
if (md5OfApp == null) {
throw new ApplicationStorageManagementException(
"Error occurred while md5sum value retrieving process: " +
"application UUID " + applicationRelease.getUuid());
}
if (DeviceType.ANDROID.toString().equalsIgnoreCase(deviceType)) {
ApkMeta apkMeta = ArtifactsParser.readAndroidManifestFile(cloneInputStream[2]);
applicationRelease.setVersion(apkMeta.getVersionName());
applicationRelease.setPackageName(apkMeta.getPackageName());
} else if (DeviceType.IOS.toString().equalsIgnoreCase(deviceType)) {
NSDictionary plistInfo = ArtifactsParser.readiOSManifestFile(binaryFile); NSDictionary plistInfo = ArtifactsParser.readiOSManifestFile(binaryFile);
applicationRelease applicationInstaller
.setVersion(plistInfo.objectForKey(ArtifactsParser.IPA_BUNDLE_VERSION_KEY).toString()); .setVersion(plistInfo.objectForKey(ArtifactsParser.IPA_BUNDLE_VERSION_KEY).toString());
applicationRelease applicationInstaller
.setPackageName(plistInfo.objectForKey(ArtifactsParser.IPA_BUNDLE_IDENTIFIER_KEY).toString()); .setPackageName(plistInfo.objectForKey(ArtifactsParser.IPA_BUNDLE_IDENTIFIER_KEY).toString());
} else { } else {
throw new ApplicationStorageManagementException("Application Type doesn't match with supporting " + String msg = "Application Type doesn't match with supporting application types " + deviceType;
"application types " + applicationRelease.getUuid()); log.error(msg);
throw new ApplicationStorageManagementException(msg);
} }
artifactDirectoryPath = storagePath + md5OfApp;
StorageManagementUtil.createArtifactDirectory(artifactDirectoryPath);
if (log.isDebugEnabled()) {
log.debug("Artifact Directory Path for saving the application release related artifacts related with "
+ "application UUID " + applicationRelease.getUuid() + " is " + artifactDirectoryPath);
}
String artifactPath = artifactDirectoryPath + File.separator + Constants.RELEASE_ARTIFACT +".apk";
saveFile(cloneInputStream[1], artifactPath);
applicationRelease.setAppStoredLoc(artifactPath);
applicationRelease.setAppHashValue(md5OfApp);
} catch (IOException e) {
throw new ApplicationStorageManagementException(
"IO Exception while saving the release artifacts in the server for the application UUID "
+ applicationRelease.getUuid(), e);
} catch (ParsingException e){ } catch (ParsingException e){
throw new ApplicationStorageManagementException( String msg = "Application Type doesn't match with supporting application types " + deviceType;
"Error occurred while parsing the artifact file. Application release UUID is " + applicationRelease log.error(msg);
.getUuid(), e); throw new ApplicationStorageManagementException(msg);
}
return applicationInstaller;
} }
return applicationRelease; @Override
public ApplicationReleaseDTO uploadReleaseArtifact(ApplicationReleaseDTO applicationReleaseDTO, String appType,
String deviceType, InputStream binaryFile) throws ResourceManagementException {
try {
String artifactDirectoryPath;
String artifactPath;
byte [] content = IOUtils.toByteArray(binaryFile);
artifactDirectoryPath = storagePath + applicationReleaseDTO.getAppHashValue();
StorageManagementUtil.createArtifactDirectory(artifactDirectoryPath);
artifactPath = artifactDirectoryPath + File.separator + applicationReleaseDTO.getInstallerName();
saveFile(new ByteArrayInputStream(content), artifactPath);
} catch (IOException e) {
String msg = "IO Exception while saving the release artifacts in the server for the application UUID "
+ applicationReleaseDTO.getUuid();
log.error(msg);
throw new ApplicationStorageManagementException( msg, e);
}
return applicationReleaseDTO;
} }
public InputStream[] cloneInputStream(InputStream inputStream) throws ApplicationStorageManagementException { @Override
public void copyImageArtifactsAndDeleteInstaller(String deletingAppHashValue,
ByteArrayOutputStream byteArrayOutputStream = null; ApplicationReleaseDTO applicationReleaseDTO) throws ApplicationStorageManagementException {
try { try {
byteArrayOutputStream = new ByteArrayOutputStream(); String basePath = storagePath + Constants.FORWARD_SLASH;
String appHashValue = applicationReleaseDTO.getAppHashValue();
String bannerName = applicationReleaseDTO.getBannerName();
String iconName = applicationReleaseDTO.getIconName();
String screenshot1 = applicationReleaseDTO.getScreenshotName1();
String screenshot2 = applicationReleaseDTO.getScreenshotName2();
String screenshot3 = applicationReleaseDTO.getScreenshotName3();
byte[] buffer = new byte[BUFFER_SIZE]; if (bannerName != null) {
int len; StorageManagementUtil
while ((len = inputStream.read(buffer)) > -1 ) { .copy(basePath + deletingAppHashValue + bannerName, basePath + appHashValue + bannerName);
byteArrayOutputStream.write(buffer, 0, len);
} }
byteArrayOutputStream.flush(); if (iconName != null) {
StorageManagementUtil
InputStream stream1 = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); .copy(basePath + deletingAppHashValue + iconName, basePath + appHashValue + iconName);
InputStream stream2 = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); }
InputStream stream3 = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); if (screenshot1 != null) {
StorageManagementUtil
return new InputStream[]{stream1, stream2, stream3}; .copy(basePath + deletingAppHashValue + screenshot1, basePath + appHashValue + screenshot1);
}
if (screenshot2 != null) {
StorageManagementUtil
.copy(basePath + deletingAppHashValue + screenshot2, basePath + appHashValue + screenshot2);
}
if (screenshot3 != null) {
StorageManagementUtil
.copy(basePath + deletingAppHashValue + screenshot3, basePath + appHashValue + screenshot3);
}
deleteApplicationReleaseArtifacts( basePath + deletingAppHashValue);
} catch (IOException e) { } catch (IOException e) {
throw new ApplicationStorageManagementException("Error occurred while cloning input stream ", e); String msg = "Application installer updating is failed because of I/O issue";
} finally { log.error(msg);
if (byteArrayOutputStream != null) { throw new ApplicationStorageManagementException(msg, e);
try {
byteArrayOutputStream.close();
} catch (IOException e) {
}
}
} }
} }
@Override @Override
public ApplicationRelease updateReleaseArtifacts(ApplicationRelease applicationRelease, String appType, public void deleteApplicationReleaseArtifacts(String artifactPath) throws ApplicationStorageManagementException {
String deviceType, InputStream binaryFile) throws ApplicationStorageManagementException, File artifact = new File(artifactPath);
RequestValidatingException {
try {
deleteApplicationReleaseArtifacts(applicationRelease.getAppStoredLoc());
applicationRelease = uploadReleaseArtifact(applicationRelease, appType, deviceType, binaryFile);
} catch (ApplicationStorageManagementException e) {
throw new ApplicationStorageManagementException("Application Artifact doesn't contains in the System", e);
} catch (ResourceManagementException e) {
throw new ApplicationStorageManagementException("Application Artifact Updating failed", e);
}
return applicationRelease;
}
@Override
public void deleteApplicationReleaseArtifacts(String directoryPath) throws ApplicationStorageManagementException {
File artifact = new File(directoryPath);
if (artifact.exists()) { if (artifact.exists()) {
try { try {
StorageManagementUtil.deleteDir(artifact); StorageManagementUtil.delete(artifact);
} catch (IOException e) { } catch (IOException e) {
throw new ApplicationStorageManagementException( throw new ApplicationStorageManagementException(
"Error occured while deleting application release artifacts", e); "Error occured while deleting application release artifacts", e);
@ -309,22 +277,22 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
} }
} }
@Override public void deleteAllApplicationReleaseArtifacts(List<String> directoryPaths) @Override
public void deleteAllApplicationReleaseArtifacts(List<String> directoryPaths)
throws ApplicationStorageManagementException { throws ApplicationStorageManagementException {
for (String directoryBasePath : directoryPaths) { for (String directoryBasePath : directoryPaths) {
deleteApplicationReleaseArtifacts(directoryBasePath); deleteApplicationReleaseArtifacts(storagePath + directoryBasePath);
} }
} }
private String getMD5(InputStream binaryFile) throws ApplicationStorageManagementException { public InputStream getFileSttream (String path) throws ApplicationStorageManagementException {
String md5; String filePath = storagePath + path;
try { try {
md5 = DigestUtils.md5Hex(IOUtils.toByteArray(binaryFile)); return StorageManagementUtil.getInputStream(filePath);
} catch (IOException e) { } catch (IOException e) {
throw new ApplicationStorageManagementException String msg = "Error occured when accessing the file in file path: " + filePath;
("IO Exception while trying to get the md5sum value of application"); throw new ApplicationStorageManagementException(msg, e);
} }
return md5;
} }
private synchronized Map<String, String> getIPAInfo(File ipaFile) throws ApplicationStorageManagementException { private synchronized Map<String, String> getIPAInfo(File ipaFile) throws ApplicationStorageManagementException {
@ -336,7 +304,7 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
ipaDirectory = new File(ipaAbsPath).getParent(); ipaDirectory = new File(ipaAbsPath).getParent();
if (new File(ipaDirectory + File.separator + Constants.PAYLOAD).exists()) { if (new File(ipaDirectory + File.separator + Constants.PAYLOAD).exists()) {
deleteDir(new File(ipaDirectory + File.separator + Constants.PAYLOAD)); delete(new File(ipaDirectory + File.separator + Constants.PAYLOAD));
} }
// unzip ipa zip file // unzip ipa zip file
@ -366,7 +334,7 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
if (ipaDirectory != null) { if (ipaDirectory != null) {
// remove unzip folder // remove unzip folder
deleteDir(new File(ipaDirectory + File.separator + Constants.PAYLOAD)); delete(new File(ipaDirectory + File.separator + Constants.PAYLOAD));
} }
} catch (ParseException e) { } catch (ParseException e) {

View File

@ -0,0 +1,91 @@
/* Copyright (c) 2018, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.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.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationStorageManagementException;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager;
import org.wso2.carbon.device.application.mgt.common.services.AppmDataHandler;
import org.wso2.carbon.device.application.mgt.common.config.UIConfiguration;
import org.wso2.carbon.device.application.mgt.core.dao.ApplicationReleaseDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory;
import org.wso2.carbon.device.application.mgt.core.dao.common.Util;
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 org.wso2.carbon.device.application.mgt.core.util.Constants;
import java.io.InputStream;
public class AppmDataHandlerImpl implements AppmDataHandler {
private UIConfiguration uiConfiguration;
private static final Log log = LogFactory.getLog(AppmDataHandlerImpl.class);
public AppmDataHandlerImpl(UIConfiguration config) {
this.uiConfiguration = config;
}
@Override
public UIConfiguration getUIConfiguration() {
return this.uiConfiguration;
}
@Override
public InputStream getArtifactStream(String uuid, String artifactName) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
ApplicationStorageManager applicationStorageManager = Util.getApplicationStorageManager();
ApplicationReleaseDAO applicationReleaseDAO = ApplicationManagementDAOFactory.getApplicationReleaseDAO();
String artifactPath;
String appReleaseHashValue;
try {
ConnectionManagerUtil.openDBConnection();
appReleaseHashValue = applicationReleaseDAO.getReleaseHashValue(uuid, tenantId);
if (appReleaseHashValue == null) {
String msg = "Could't find application release for UUID: " + uuid + ". Hence try with valid UUID.";
log.error(msg);
throw new NotFoundException(msg);
}
artifactPath = appReleaseHashValue + Constants.FORWARD_SLASH + artifactName;
InputStream inputStream = applicationStorageManager.getFileSttream(artifactPath);
if (inputStream == null) {
String msg = "Couldn't file the file in the file system. File path: " + artifactPath;
log.error(msg);
throw new ApplicationManagementException(msg);
}
return inputStream;
} catch (ApplicationManagementDAOException e) {
String msg =
"Error occurred when retrieving application release hash value for given application release UUID: "
+ uuid;
log.error(msg);
throw new ApplicationManagementException(msg);
} catch (ApplicationStorageManagementException e) {
String msg = "Error occurred when getting input stream of the " + artifactName + " file.";
log.error(msg);
throw new ApplicationManagementException(msg);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
}

View File

@ -1,35 +0,0 @@
/* Copyright (c) 2018, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.application.mgt.core.impl;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.services.ConfigManager;
import org.wso2.carbon.device.application.mgt.common.config.UIConfiguration;
public class ConfigManagerImpl implements ConfigManager {
private UIConfiguration uiConfiguration;
public ConfigManagerImpl(UIConfiguration config) {
this.uiConfiguration = config;
}
@Override public UIConfiguration getUIConfiguration() throws ApplicationManagementException {
return this.uiConfiguration;
}
}

View File

@ -74,7 +74,7 @@ public class MAMDeviceConnectorImpl implements DeviceConnector{
for (String username: userList) { for (String username: userList) {
List<Device> devices = getDeviceManagementService().getDevicesOfUser(username); List<Device> devices = getDeviceManagementService().getDevicesOfUser(username);
List<DeviceIdentifier> deviceIdentifiers = convertDeviceToDeviceIdentifier(devices); List<DeviceIdentifier> deviceIdentifiers = convertDeviceToDeviceIdentifier(devices);
// getDeviceManagementService().addOperation(appOperation.getApplication().getDeviceType(), // getDeviceManagementService().addOperation(appOperation.getApplication().getDeviceTypeName(),
// operationEKA, devices); // operationEKA, devices);
subscriptionDAO.subscribeDeviceToApplication(appOperation.getTenantId(), appOperation.getSubscribedBy(), subscriptionDAO.subscribeDeviceToApplication(appOperation.getTenantId(), appOperation.getSubscribedBy(),
devices, appOperation.getApplication().getId(), appOperation.getAppReleaseId(), devices, appOperation.getApplication().getId(), appOperation.getAppReleaseId(),

View File

@ -21,7 +21,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.common.AppOperation; import org.wso2.carbon.device.application.mgt.common.AppOperation;
import org.wso2.carbon.device.application.mgt.common.Application; import org.wso2.carbon.device.application.mgt.common.dto.ApplicationDTO;
import org.wso2.carbon.device.application.mgt.common.ApplicationInstallResponse; import org.wso2.carbon.device.application.mgt.common.ApplicationInstallResponse;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; 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.common.services.ApplicationManager;
@ -70,7 +70,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
log.debug("Install application: " + applicationUUID + " to " + deviceList.size() + "devices."); log.debug("Install application: " + applicationUUID + " to " + deviceList.size() + "devices.");
} }
ApplicationManager applicationManager = DataHolder.getInstance().getApplicationManager(); ApplicationManager applicationManager = DataHolder.getInstance().getApplicationManager();
Application application = applicationManager.getApplicationByRelease(applicationUUID); ApplicationDTO application = applicationManager.getApplicationByRelease(applicationUUID);
return installApplication(application, deviceList); return installApplication(application, deviceList);
} }
@ -82,7 +82,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
log.debug("Install application: " + applicationUUID + " to " + userList.size() + " users."); log.debug("Install application: " + applicationUUID + " to " + userList.size() + " users.");
} }
ApplicationManager applicationManager = DataHolder.getInstance().getApplicationManager(); ApplicationManager applicationManager = DataHolder.getInstance().getApplicationManager();
Application application = applicationManager.getApplicationByRelease(applicationUUID); ApplicationDTO application = applicationManager.getApplicationByRelease(applicationUUID);
List<DeviceIdentifier> deviceList = new ArrayList<>(); List<DeviceIdentifier> deviceList = new ArrayList<>();
for (String user : userList) { for (String user : userList) {
try { try {
@ -103,7 +103,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String subscriber = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String subscriber = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
int applicationReleaseId = application.getApplicationReleases().get(0).getId(); int applicationReleaseId = application.getApplicationReleaseDTOs().get(0).getId();
try { try {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
@ -123,7 +123,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
log.debug("Install application: " + applicationUUID + " to " + roleList.size() + " roles."); log.debug("Install application: " + applicationUUID + " to " + roleList.size() + " roles.");
} }
ApplicationManager applicationManager = DataHolder.getInstance().getApplicationManager(); ApplicationManager applicationManager = DataHolder.getInstance().getApplicationManager();
Application application = applicationManager.getApplicationByRelease(applicationUUID); ApplicationDTO application = applicationManager.getApplicationByRelease(applicationUUID);
List<DeviceIdentifier> deviceList = new ArrayList<>(); List<DeviceIdentifier> deviceList = new ArrayList<>();
for (String role : roleList) { for (String role : roleList) {
try { try {
@ -144,7 +144,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String subscriber = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String subscriber = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
int applicationReleaseId = application.getApplicationReleases().get(0).getId(); int applicationReleaseId = application.getApplicationReleaseDTOs().get(0).getId();
try { try {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
@ -164,7 +164,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
log.debug("Install application: " + applicationUUID + " to " + deviceGroupList.size() + " groups."); log.debug("Install application: " + applicationUUID + " to " + deviceGroupList.size() + " groups.");
} }
ApplicationManager applicationManager = DataHolder.getInstance().getApplicationManager(); ApplicationManager applicationManager = DataHolder.getInstance().getApplicationManager();
Application application = applicationManager.getApplicationByRelease(applicationUUID); ApplicationDTO application = applicationManager.getApplicationByRelease(applicationUUID);
GroupManagementProviderService groupManagementProviderService = HelperUtil.getGroupManagementProviderService(); GroupManagementProviderService groupManagementProviderService = HelperUtil.getGroupManagementProviderService();
List<DeviceGroup> groupList = new ArrayList<>(); List<DeviceGroup> groupList = new ArrayList<>();
List<DeviceIdentifier> deviceList = new ArrayList<>(); List<DeviceIdentifier> deviceList = new ArrayList<>();
@ -188,7 +188,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String subscriber = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String subscriber = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
int applicationReleaseId = application.getApplicationReleases().get(0).getId(); int applicationReleaseId = application.getApplicationReleaseDTOs().get(0).getId();
try { try {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
@ -207,7 +207,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
return null; return null;
} }
private ApplicationInstallResponse installApplication(Application application, private ApplicationInstallResponse installApplication(ApplicationDTO application,
List<DeviceIdentifier> deviceIdentifierList) throws ApplicationManagementException { List<DeviceIdentifier> deviceIdentifierList) throws ApplicationManagementException {
DeviceManagementProviderService deviceManagementProviderService = HelperUtil DeviceManagementProviderService deviceManagementProviderService = HelperUtil
.getDeviceManagementProviderService(); .getDeviceManagementProviderService();
@ -239,7 +239,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String subscriber = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String subscriber = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
int applicationReleaseId = application.getApplicationReleases().get(0).getId(); int applicationReleaseId = application.getApplicationReleaseDTOs().get(0).getId();
try { try {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
List<Device> deviceList = new ArrayList<>(); List<Device> deviceList = new ArrayList<>();
@ -259,15 +259,15 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
return response; return response;
} }
private Operation generateOperationPayloadByDeviceType(String deviceType, Application application) { private Operation generateOperationPayloadByDeviceType(String deviceType, ApplicationDTO application) {
ProfileOperation operation = new ProfileOperation(); ProfileOperation operation = new ProfileOperation();
operation.setCode(INSTALL_APPLICATION); operation.setCode(INSTALL_APPLICATION);
operation.setType(Operation.Type.PROFILE); operation.setType(Operation.Type.PROFILE);
//todo: generate operation payload correctly for all types of devices. //todo: generate operation payload correctly for all types of devices.
operation.setPayLoad( operation.setPayLoad(
"{'type':'enterprise', 'url':'" + application.getApplicationReleases().get(0).getAppStoredLoc() "{'type':'enterprise', 'url':'" + application.getApplicationReleaseDTOs().get(0).getInstallerName()
+ "', 'app':'" + application.getApplicationReleases().get(0).getUuid() + "'}"); + "', 'app':'" + application.getApplicationReleaseDTOs().get(0).getUuid() + "'}");
return operation; return operation;
} }

View File

@ -24,13 +24,13 @@ import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager;
import org.wso2.carbon.device.application.mgt.common.services.ConfigManager; import org.wso2.carbon.device.application.mgt.common.services.AppmDataHandler;
import org.wso2.carbon.device.application.mgt.common.services.ReviewManager; import org.wso2.carbon.device.application.mgt.common.services.ReviewManager;
import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager; import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager;
import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager; import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager;
import org.wso2.carbon.device.application.mgt.common.config.UIConfiguration; import org.wso2.carbon.device.application.mgt.common.config.UIConfiguration;
import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory; import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory;
import org.wso2.carbon.device.application.mgt.core.impl.ConfigManagerImpl; import org.wso2.carbon.device.application.mgt.core.impl.AppmDataHandlerImpl;
import org.wso2.carbon.device.application.mgt.core.lifecycle.LifecycleStateManager; import org.wso2.carbon.device.application.mgt.core.lifecycle.LifecycleStateManager;
import org.wso2.carbon.device.application.mgt.core.lifecycle.config.LifecycleState; import org.wso2.carbon.device.application.mgt.core.lifecycle.config.LifecycleState;
import org.wso2.carbon.device.application.mgt.core.util.ApplicationManagementUtil; import org.wso2.carbon.device.application.mgt.core.util.ApplicationManagementUtil;
@ -75,7 +75,6 @@ public class ApplicationManagementServiceComponent {
try { try {
String dataSourceName = ConfigurationManager.getInstance().getConfiguration().getDatasourceName(); String dataSourceName = ConfigurationManager.getInstance().getConfiguration().getDatasourceName();
ApplicationManagementDAOFactory.init(dataSourceName); ApplicationManagementDAOFactory.init(dataSourceName);
// ApplicationManagementDAOFactory.initDatabases();
List<LifecycleState> lifecycleStates = ConfigurationManager.getInstance(). List<LifecycleState> lifecycleStates = ConfigurationManager.getInstance().
getConfiguration().getLifecycleStates(); getConfiguration().getLifecycleStates();
@ -85,6 +84,8 @@ public class ApplicationManagementServiceComponent {
bundleContext.registerService(LifecycleStateManager.class.getName(), lifecycleStateManager, null); bundleContext.registerService(LifecycleStateManager.class.getName(), lifecycleStateManager, null);
ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance(); ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance();
applicationManager
.addAplicationCategories(ConfigurationManager.getInstance().getConfiguration().getAppCategories());
DataHolder.getInstance().setApplicationManager(applicationManager); DataHolder.getInstance().setApplicationManager(applicationManager);
bundleContext.registerService(ApplicationManager.class.getName(), applicationManager, null); bundleContext.registerService(ApplicationManager.class.getName(), applicationManager, null);
@ -103,9 +104,9 @@ public class ApplicationManagementServiceComponent {
UIConfiguration uiConfiguration = ConfigurationManager.getInstance(). UIConfiguration uiConfiguration = ConfigurationManager.getInstance().
getConfiguration().getUiConfiguration(); getConfiguration().getUiConfiguration();
ConfigManager configManager = new ConfigManagerImpl(uiConfiguration); AppmDataHandler configManager = new AppmDataHandlerImpl(uiConfiguration);
DataHolder.getInstance().setConfigManager(configManager); DataHolder.getInstance().setConfigManager(configManager);
bundleContext.registerService(ConfigManager.class.getName(), configManager, null); bundleContext.registerService(AppmDataHandler.class.getName(), configManager, null);
log.info("ApplicationManagement core bundle has been successfully initialized"); log.info("ApplicationManagement core bundle has been successfully initialized");
} catch (Throwable e) { } catch (Throwable e) {
@ -119,14 +120,14 @@ public class ApplicationManagementServiceComponent {
protected void setDeviceManagementService(DeviceManagementProviderService deviceManagementProviderService) { protected void setDeviceManagementService(DeviceManagementProviderService deviceManagementProviderService) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Setting Application Management OSGI Manager"); log.debug("Setting ApplicationDTO Management OSGI Manager");
} }
DataHolder.getInstance().setDeviceManagementService(deviceManagementProviderService); DataHolder.getInstance().setDeviceManagementService(deviceManagementProviderService);
} }
protected void unsetDeviceManagementService(DeviceManagementProviderService deviceManagementProviderService) { protected void unsetDeviceManagementService(DeviceManagementProviderService deviceManagementProviderService) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Removing Application Management OSGI Manager"); log.debug("Removing ApplicationDTO Management OSGI Manager");
} }
DataHolder.getInstance().setDeviceManagementService(null); DataHolder.getInstance().setDeviceManagementService(null);
} }

View File

@ -20,7 +20,7 @@ package org.wso2.carbon.device.application.mgt.core.internal;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager;
import org.wso2.carbon.device.application.mgt.common.services.ConfigManager; import org.wso2.carbon.device.application.mgt.common.services.AppmDataHandler;
import org.wso2.carbon.device.application.mgt.common.services.ReviewManager; import org.wso2.carbon.device.application.mgt.common.services.ReviewManager;
import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager; import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager;
import org.wso2.carbon.device.application.mgt.core.lifecycle.LifecycleStateManager; import org.wso2.carbon.device.application.mgt.core.lifecycle.LifecycleStateManager;
@ -46,7 +46,7 @@ public class DataHolder {
private LifecycleStateManager lifecycleStateManager; private LifecycleStateManager lifecycleStateManager;
private ConfigManager configManager; private AppmDataHandler configManager;
private static final DataHolder applicationMgtDataHolder = new DataHolder(); private static final DataHolder applicationMgtDataHolder = new DataHolder();
@ -114,11 +114,11 @@ public class DataHolder {
this.lifecycleStateManager = lifecycleStateManager; this.lifecycleStateManager = lifecycleStateManager;
} }
public ConfigManager getConfigManager() { public AppmDataHandler getConfigManager() {
return configManager; return configManager;
} }
public void setConfigManager(ConfigManager configManager) { public void setConfigManager(AppmDataHandler configManager) {
this.configManager = configManager; this.configManager = configManager;
} }
} }

View File

@ -101,11 +101,9 @@ public class LifecycleStateManager {
} }
private State getMatchingState(String currentState) { private State getMatchingState(String currentState) {
Iterator it = lifecycleStates.entrySet().iterator(); for (Map.Entry<String, State> stringStateEntry : lifecycleStates.entrySet()) {
while (it.hasNext()) { if (stringStateEntry.getKey().equalsIgnoreCase(currentState)) {
Map.Entry pair = (Map.Entry) it.next(); return lifecycleStates.get(stringStateEntry.getKey());
if (pair.getKey().toString().equalsIgnoreCase(currentState)) {
return lifecycleStates.get(pair.getKey().toString());
} }
} }
return null; return null;
@ -135,9 +133,96 @@ public class LifecycleStateManager {
return null; return null;
} }
public boolean isUpdatableState(String state) throws LifecycleManagementException {
State currentState = getMatchingState(state);
if (currentState != null) {
return currentState.isAppUpdatable();
} else {
String msg = "Couldn't find a lifecycle state that matches with " + state + " state.";
log.error(msg);
throw new LifecycleManagementException(msg);
}
}
public boolean isInstallableState(String state) throws LifecycleManagementException {
State currentState = getMatchingState(state);
if (currentState != null) {
return currentState.isAppInstallable();
} else {
String msg = "Couldn't find a lifecycle state that matches with " + state + " state.";
log.error(msg);
throw new LifecycleManagementException(msg);
}
}
public boolean isInitialState(String state) throws LifecycleManagementException {
State currentState = getMatchingState(state);
if (currentState != null) {
return currentState.isInitialState();
} else {
String msg = "Couldn't find a lifecycle state that matches with " + state + " state.";
log.error(msg);
throw new LifecycleManagementException(msg);
}
}
public boolean isEndState(String state) throws LifecycleManagementException {
State currentState = getMatchingState(state);
if (currentState != null) {
return currentState.isEndState();
} else {
String msg = "Couldn't find a lifecycle state that matches with " + state + " state.";
log.error(msg);
throw new LifecycleManagementException(msg);
}
}
public String getInitialState() throws LifecycleManagementException {
String initialState = null;
for (Map.Entry<String, State> stringStateEntry : lifecycleStates.entrySet()) {
if (stringStateEntry.getValue().isInitialState()) {
initialState = stringStateEntry.getKey();
break;
}
}
if (initialState == null){
String msg = "Haven't defined the initial state in the application-manager.xml. Please add initial state "
+ "to the <LifecycleStates> section in the app-manager.xml";
log.error(msg);
throw new LifecycleManagementException(msg);
}
return initialState;
}
public String getEndState() throws LifecycleManagementException {
String endState = null;
for (Map.Entry<String, State> stringStateEntry : lifecycleStates.entrySet()) {
if (stringStateEntry.getValue().isEndState()) {
endState = stringStateEntry.getKey();
break;
}
}
if (endState == null){
String msg = "Haven't defined the end state in the application-manager.xml. Please add end state "
+ "to the <LifecycleStates> section in the app-manager.xml";
log.error(msg);
throw new LifecycleManagementException(msg);
}
return endState;
}
public boolean isStateExist(String currentState) {
for (Map.Entry<String, State> stringStateEntry : lifecycleStates.entrySet()) {
if (stringStateEntry.getKey().equalsIgnoreCase(currentState)) {
return true;
}
}
return false;
}
public boolean isUpdatable(String state) { public boolean isUpdatable(String state) {
State currentState = getMatchingState(state); State currentState = getMatchingState(state);
if (currentState.getIsAppUpdatable()) { if (currentState.isAppUpdatable()) {
return true; return true;
} }
return false; return false;
@ -145,12 +230,13 @@ public class LifecycleStateManager {
public boolean isInstallable(String state) { public boolean isInstallable(String state) {
State currentState = getMatchingState(state); State currentState = getMatchingState(state);
if (currentState.getIsAppInstallable()) { if (currentState.isAppInstallable()) {
return true; return true;
} }
return false; return false;
} }
public void setLifecycleStates(Map<String, State> lifecycleStates) { public void setLifecycleStates(Map<String, State> lifecycleStates) {
this.lifecycleStates = lifecycleStates; this.lifecycleStates = lifecycleStates;
} }

View File

@ -12,7 +12,6 @@ public class State {
private Set<String> proceedingStates; private Set<String> proceedingStates;
private String stateName; private String stateName;
private String permission; private String permission;
private List<String> allowedActions;
private boolean isAppUpdatable; private boolean isAppUpdatable;
private boolean isAppInstallable; private boolean isAppInstallable;
private boolean isInitialState; private boolean isInitialState;
@ -41,12 +40,12 @@ public class State {
public String getPermission(){ return permission;} public String getPermission(){ return permission;}
public boolean getIsAppUpdatable(){ return isAppUpdatable;} public boolean isAppUpdatable(){ return isAppUpdatable;}
public boolean getIsAppInstallable(){ return isAppInstallable;} public boolean isAppInstallable(){ return isAppInstallable;}
public boolean getIsInitialState(){ return isInitialState;} public boolean isInitialState(){ return isInitialState;}
public boolean getIsEndState(){ return isEndState;} public boolean isEndState(){ return isEndState;}
} }

View File

@ -18,9 +18,11 @@
package org.wso2.carbon.device.application.mgt.core.util; package org.wso2.carbon.device.application.mgt.core.util;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.common.Filter;
import org.wso2.carbon.device.application.mgt.common.services.*; import org.wso2.carbon.device.application.mgt.common.services.*;
import org.wso2.carbon.device.application.mgt.common.ErrorResponse; import org.wso2.carbon.device.application.mgt.common.ErrorResponse;
@ -28,7 +30,7 @@ import javax.ws.rs.core.Response;
/** /**
* Holds util methods required for Application-Mgt API component. * Holds util methods required for ApplicationDTO-Mgt API component.
*/ */
public class APIUtil { public class APIUtil {
@ -38,7 +40,7 @@ public class APIUtil {
private static ApplicationStorageManager applicationStorageManager; private static ApplicationStorageManager applicationStorageManager;
private static SubscriptionManager subscriptionManager; private static SubscriptionManager subscriptionManager;
private static ReviewManager reviewManager; private static ReviewManager reviewManager;
private static ConfigManager configManager; private static AppmDataHandler appmDataHandler;
public static ApplicationManager getApplicationManager() { public static ApplicationManager getApplicationManager() {
if (applicationManager == null) { if (applicationManager == null) {
@ -48,7 +50,7 @@ public class APIUtil {
applicationManager = applicationManager =
(ApplicationManager) ctx.getOSGiService(ApplicationManager.class, null); (ApplicationManager) ctx.getOSGiService(ApplicationManager.class, null);
if (applicationManager == null) { if (applicationManager == null) {
String msg = "Application Manager service has not initialized."; String msg = "ApplicationDTO Manager service has not initialized.";
log.error(msg); log.error(msg);
throw new IllegalStateException(msg); throw new IllegalStateException(msg);
} }
@ -59,7 +61,7 @@ public class APIUtil {
} }
/** /**
* To get the Application Storage Manager from the osgi context. * To get the ApplicationDTO Storage Manager from the osgi context.
* @return ApplicationStoreManager instance in the current osgi context. * @return ApplicationStoreManager instance in the current osgi context.
*/ */
public static ApplicationStorageManager getApplicationStorageManager() { public static ApplicationStorageManager getApplicationStorageManager() {
@ -70,7 +72,7 @@ public class APIUtil {
applicationStorageManager = (ApplicationStorageManager) ctx applicationStorageManager = (ApplicationStorageManager) ctx
.getOSGiService(ApplicationStorageManager.class, null); .getOSGiService(ApplicationStorageManager.class, null);
if (applicationStorageManager == null) { if (applicationStorageManager == null) {
String msg = "Application Storage Manager service has not initialized."; String msg = "ApplicationDTO Storage Manager service has not initialized.";
log.error(msg); log.error(msg);
throw new IllegalStateException(msg); throw new IllegalStateException(msg);
} }
@ -141,17 +143,17 @@ public class APIUtil {
} }
/** /**
* To get the Config Manager from the osgi context. * To get the DataHandler from the osgi context.
* @return ConfigManager instance in the current osgi context. * @return AppmDataHandler instance in the current osgi context.
*/ */
public static ConfigManager getConfigManager() { public static AppmDataHandler getDataHandler() {
if (configManager == null) { if (appmDataHandler == null) {
synchronized (APIUtil.class) { synchronized (APIUtil.class) {
if (configManager == null) { if (appmDataHandler == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
configManager = appmDataHandler =
(ConfigManager) ctx.getOSGiService(ConfigManager.class, null); (AppmDataHandler) ctx.getOSGiService(AppmDataHandler.class, null);
if (configManager == null) { if (appmDataHandler == null) {
String msg = "Config Manager service has not initialized."; String msg = "Config Manager service has not initialized.";
log.error(msg); log.error(msg);
throw new IllegalStateException(msg); throw new IllegalStateException(msg);
@ -160,7 +162,32 @@ public class APIUtil {
} }
} }
return configManager; return appmDataHandler;
} }
// public static Filter constructFilter( String appName, String appType, String appCategory, String tags,
// boolean isFullMatch, String releaseState, int offset, int limit, String sortBy) {
// Filter filter = new Filter();
// filter.setOffset(offset);
// filter.setLimit(limit);
// filter.setSortBy(sortBy);
// filter.setFullMatch(isFullMatch);
// if (!StringUtils.isEmpty(appName)) {
// filter.setAppName(appName);
// }
// if (!StringUtils.isEmpty(appType)) {
// filter.setAppType(appType);
// }
// if (!StringUtils.isEmpty(appCategory)) {
// filter.setAppCategories(appCategory);
// }
// if (!StringUtils.isEmpty(tags)) {
// filter.setAppCategories(appCategory);
// }
// if (!StringUtils.isEmpty(releaseState)) {
// filter.setAppReleaseState(releaseState);
// }
// return filter;
// }
} }

View File

@ -37,6 +37,8 @@ public class Constants {
public static final String CF_BUNDLE_VERSION = "CFBundleVersion"; public static final String CF_BUNDLE_VERSION = "CFBundleVersion";
public static final String APP_EXTENSION = ".app"; public static final String APP_EXTENSION = ".app";
public static final String FORWARD_SLASH = "/";
/** /**
* Database types supported by Application Management. * Database types supported by Application Management.
*/ */
@ -51,12 +53,6 @@ public class Constants {
public static final String DB_TYPE_POSTGRESQL = "PostgreSQL"; public static final String DB_TYPE_POSTGRESQL = "PostgreSQL";
} }
/**
* Lifecycle states of the application life-cycle.
*/
public static final String[] LIFE_CYCLES = {"CREATED", "IN REVIEW", "APPROVED", "REJECTED", "PUBLISHED",
"UNPUBLISHED", "RETIRED"};
/** /**
* Name of the image artifacts that are saved in the file system. * Name of the image artifacts that are saved in the file system.

View File

@ -19,12 +19,17 @@
package org.wso2.carbon.device.application.mgt.core.util; package org.wso2.carbon.device.application.mgt.core.util;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.common.ImageArtifact; import org.wso2.carbon.device.application.mgt.common.ImageArtifact;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationStorageManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -35,6 +40,9 @@ import java.nio.file.Files;
* This is a util class that handles Storage Management related tasks. * This is a util class that handles Storage Management related tasks.
*/ */
public class StorageManagementUtil { public class StorageManagementUtil {
private static Log log = LogFactory.getLog(StorageManagementUtil.class);
/** /**
* This method is responsible for creating artifact parent directories in the given path. * This method is responsible for creating artifact parent directories in the given path.
* *
@ -55,16 +63,28 @@ public class StorageManagementUtil {
* *
* @param artifactDirectory Artifact Directory that need to be deleted. * @param artifactDirectory Artifact Directory that need to be deleted.
*/ */
public static void deleteDir(File artifactDirectory) throws IOException { public static void delete(File artifactDirectory) throws IOException {
File[] contents = artifactDirectory.listFiles(); File[] contents = artifactDirectory.listFiles();
if (contents != null) { if (contents != null) {
for (File file : contents) { for (File file : contents) {
deleteDir(file); delete(file);
} }
} }
Files.delete(artifactDirectory.toPath()); Files.delete(artifactDirectory.toPath());
} }
public static void copy(String source, String destination) throws IOException {
File sourceFile = new File(source);
File destinationFile = new File(destination);
if (sourceFile.exists() && destinationFile.exists()) {
Files.copy(sourceFile.toPath(), destinationFile.toPath());
} else {
String msg = "Source file " + source + " or destination file " + destination + " doesn't exist";
log.error(msg);
throw new IOException(msg);
}
}
/** /**
* To save a file in a given location. * To save a file in a given location.
* *
@ -99,4 +119,34 @@ public class StorageManagementUtil {
return imageArtifact; return imageArtifact;
} }
/***
* Get the fine input stream
* @param filePath File path
* @return {@link InputStream}
* @throws IOException throws if error occured when reading file or if couldn't find a file in the filePath
*/
public static InputStream getInputStream (String filePath) throws IOException {
File sourceFile = new File(filePath);
if (!sourceFile.exists()){
return null;
}
try {
return new FileInputStream(sourceFile);
} catch (FileNotFoundException e) {
String msg = "Couldn't file the file in file path: " + filePath;
log.error(msg);
throw new IOException(msg);
}
}
public static String getMD5(InputStream binaryFile) throws ApplicationStorageManagementException {
String md5;
try {
md5 = DigestUtils.md5Hex(binaryFile);
} catch (IOException e) {
throw new ApplicationStorageManagementException
("IO Exception while trying to get the md5sum value of application");
}
return md5;
}
} }

View File

@ -24,6 +24,8 @@ public class LifecycleManagementTest {
private final String NON_UPDATABLE_STATE = "Removed"; private final String NON_UPDATABLE_STATE = "Removed";
private final String INSTALLABLE_STATE = "Published"; private final String INSTALLABLE_STATE = "Published";
private final String UNINSTALlABLE_STATE = "Removed"; private final String UNINSTALlABLE_STATE = "Removed";
private final String INITIAL_STATE = "Created";
private final String END_STATE = "Removed";
@BeforeClass @BeforeClass
@ -50,35 +52,82 @@ public class LifecycleManagementTest {
} }
@Test @Test
public void CheckUpdatableState() { public void CheckUpdatableState() throws LifecycleManagementException {
Boolean isUpdatable = lifecycleStateManager.isUpdatable(UPDATABLE_STATE); boolean isUpdatable = lifecycleStateManager.isUpdatable(UPDATABLE_STATE);
System.out.println(isUpdatable); System.out.println(isUpdatable);
Assert.assertTrue("Updatable state: " + UPDATABLE_STATE, isUpdatable); Assert.assertTrue("Updatable state: " + UPDATABLE_STATE, isUpdatable);
} }
@Test @Test
public void CheckNonUpdatableState() { public void CheckNonUpdatableState() throws LifecycleManagementException {
Boolean isUpdatable = lifecycleStateManager.isUpdatable(NON_UPDATABLE_STATE); boolean isUpdatable = lifecycleStateManager.isUpdatable(NON_UPDATABLE_STATE);
Assert.assertFalse("Non Updatable state: " + NON_UPDATABLE_STATE, isUpdatable); Assert.assertFalse("Non Updatable state: " + NON_UPDATABLE_STATE, isUpdatable);
} }
@Test @Test
public void CheckInstallableState() { public void CheckInstallableState() throws LifecycleManagementException {
Boolean isInstallable = lifecycleStateManager.isInstallable(INSTALLABLE_STATE); boolean isInstallable = lifecycleStateManager.isInstallable(INSTALLABLE_STATE);
Assert.assertTrue("Installable state: " + INSTALLABLE_STATE, isInstallable); Assert.assertTrue("Installable state: " + INSTALLABLE_STATE, isInstallable);
} }
@Test @Test
public void CheckUnInstallableState() { public void CheckUnInstallableState() throws LifecycleManagementException {
Boolean isInstallable = lifecycleStateManager.isInstallable(UNINSTALlABLE_STATE); boolean isInstallable = lifecycleStateManager.isInstallable(UNINSTALlABLE_STATE);
Assert.assertFalse("UnInstallable state: " + UNINSTALlABLE_STATE, isInstallable); Assert.assertFalse("UnInstallable state: " + UNINSTALlABLE_STATE, isInstallable);
} }
@Test
public void CheckGetInitialState() throws LifecycleManagementException {
boolean isInitialState = lifecycleStateManager.getInitialState().equalsIgnoreCase(INITIAL_STATE);
Assert.assertTrue("Initial state: " + INITIAL_STATE, isInitialState);
}
@Test
public void CheckGetNonInitialState() throws LifecycleManagementException {
boolean isInitialState = lifecycleStateManager.getInitialState().equalsIgnoreCase(END_STATE);
Assert.assertFalse("Non initial state: " + END_STATE, isInitialState);
}
@Test
public void CheckGetEndState() throws LifecycleManagementException {
boolean isEndState = lifecycleStateManager.getEndState().equalsIgnoreCase(END_STATE);
Assert.assertTrue("End State: " + END_STATE, isEndState);
}
@Test
public void CheckGetNonEndState() throws LifecycleManagementException {
boolean isEndState = lifecycleStateManager.getEndState().equalsIgnoreCase(INITIAL_STATE);
Assert.assertFalse("Non End State : " + INITIAL_STATE, isEndState);
}
@Test
public void CheckIsInitialState() throws LifecycleManagementException {
boolean isInitialState = lifecycleStateManager.isInitialState(INITIAL_STATE);
Assert.assertTrue("Initial state: " + INITIAL_STATE, isInitialState);
}
@Test
public void CheckIsNonInitialState() throws LifecycleManagementException {
boolean isInitialState = lifecycleStateManager.isInitialState(END_STATE);
Assert.assertFalse("Non Initial state: " + END_STATE, isInitialState);
}
@Test
public void CheckIsEndState() throws LifecycleManagementException {
boolean isEndState = lifecycleStateManager.isEndState(END_STATE);
Assert.assertTrue("End state: " + END_STATE, isEndState);
}
@Test
public void CheckIsNonEndState() throws LifecycleManagementException {
boolean isEndState = lifecycleStateManager.isEndState(INITIAL_STATE);
Assert.assertFalse("Non End state: " + INITIAL_STATE, isEndState);
}
@Test @Test
public void check() { public void check() {
Set<String> proceedingStates = lifecycleStateManager.getNextLifecycleStates(CURRENT_STATE); Set<String> proceedingStates = lifecycleStateManager.getNextLifecycleStates(CURRENT_STATE);
Assert.assertFalse("Invalid proceeding state of: " + CURRENT_STATE, Assert.assertFalse("Invalid proceeding state of: " + CURRENT_STATE,
proceedingStates.contains(BOGUS_STATE.toUpperCase())); proceedingStates.contains(BOGUS_STATE.toUpperCase()));
} }
} }

View File

@ -39,7 +39,7 @@ public class StorageManagementUtilTest {
public void before() throws IOException { public void before() throws IOException {
File file = new File(TEMP_FOLDER); File file = new File(TEMP_FOLDER);
if (file.exists()) { if (file.exists()) {
StorageManagementUtil.deleteDir(file); StorageManagementUtil.delete(file);
} }
} }
@ -67,7 +67,7 @@ public class StorageManagementUtilTest {
@AfterMethod @AfterMethod
public void deleteFileTest() throws IOException, ResourceManagementException { public void deleteFileTest() throws IOException, ResourceManagementException {
File file = new File(TEMP_FOLDER); File file = new File(TEMP_FOLDER);
StorageManagementUtil.deleteDir(file); StorageManagementUtil.delete(file);
if (file.exists()) { if (file.exists()) {
Assert.fail("File deleting failed."); Assert.fail("File deleting failed.");
} }

View File

@ -18,7 +18,7 @@
--> -->
<ApplicationManagementConfiguration> <ApplicationManagementConfiguration>
<!-- Application Mgt DB schema --> <!-- ApplicationDTO Mgt DB schema -->
<DatasourceName>jdbc/APPM_DS</DatasourceName> <DatasourceName>jdbc/APPM_DS</DatasourceName>
<Extensions> <Extensions>

View File

@ -23,7 +23,6 @@ import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
@ -32,9 +31,10 @@ import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType; import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.wso2.carbon.device.application.mgt.common.ProxyResponse;
import org.wso2.carbon.device.application.mgt.handler.beans.AuthData; import org.wso2.carbon.device.application.mgt.handler.beans.AuthData;
import org.wso2.carbon.device.application.mgt.handler.util.HandlerConstants; import org.wso2.carbon.device.application.mgt.handler.util.HandlerConstants;
import org.wso2.carbon.device.application.mgt.handler.util.HandlerUtil;
import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet; import javax.servlet.annotation.WebServlet;
@ -43,13 +43,9 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter;
import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; import static java.net.HttpURLConnection.HTTP_BAD_REQUEST;
import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import static org.wso2.carbon.device.application.mgt.handler.util.HandlerUtil.execute; import static org.wso2.carbon.device.application.mgt.handler.util.HandlerUtil.execute;
import static org.wso2.carbon.device.application.mgt.handler.util.HandlerUtil.retrieveResponseString;
@MultipartConfig @MultipartConfig
@WebServlet("/invoke") @WebServlet("/invoke")
@ -60,51 +56,40 @@ public class InvokerHandler extends HttpServlet {
private static String apiEndpoint; private static String apiEndpoint;
private static String method; private static String method;
private static String serverUrl; private static String serverUrl;
private static String platform;
@Override
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
try { try {
if (!validateRequest(req, resp)) { if (!validateRequest(req, resp)) {
return; return;
} }
HttpRequestBase executor = constructExecutor(req); HttpRequestBase executor = constructExecutor(req);
if (executor == null) { if (executor == null) {
resp.sendError(HTTP_BAD_REQUEST, "Bad Request, method: " + method + " is not supported"); resp.sendError(HTTP_BAD_REQUEST, "Bad Request, method: " + method + " is not supported");
return; return;
} }
String accessToken = authData.getAccessToken(); executor.setHeader(HandlerConstants.AUTHORIZATION_HEADER_KEY, "Bearer " + authData.getAccessToken());
executor.setHeader("Authorization", "Bearer " + accessToken); ProxyResponse proxyResponse = execute(executor);
HttpResponse response = execute(executor); if (HandlerConstants.TOKEN_IS_EXPIRED.equals(proxyResponse.getExecutorResponse())) {
if (response == null) {
resp.sendError(HTTP_INTERNAL_ERROR, "Empty response retried for the API call.");
return;
}
int responseCode = response.getStatusLine().getStatusCode();
String result = retrieveResponseString(response);
if (responseCode == HttpStatus.SC_UNAUTHORIZED && (result.contains("Access token expired") || result
.contains("Invalid input. Access token validation failed"))) {
if (!refreshToken(req, resp)) { if (!refreshToken(req, resp)) {
return; return;
} }
response = execute(executor); executor.setHeader(HandlerConstants.AUTHORIZATION_HEADER_KEY, "Bearer " + authData.getAccessToken());
if (response == null) { proxyResponse = execute(executor);
resp.sendError(HTTP_INTERNAL_ERROR, "Empty response retried for the token renewal API call."); if (proxyResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
log.error("Error occurred while invoking the API after refreshing the token.");
HandlerUtil.handleError(req, resp, serverUrl, platform, proxyResponse);
return; return;
} }
responseCode = response.getStatusLine().getStatusCode();
result = retrieveResponseString(response);
} }
if (responseCode != HttpStatus.SC_OK && responseCode != HttpStatus.SC_CREATED) { if (proxyResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
resp.sendError(responseCode, "Error response retrieved for the API call."); log.error("Error occurred while invoking the API endpoint.");
HandlerUtil.handleError(req, resp, serverUrl, platform, proxyResponse);
return; return;
} }
try (PrintWriter writer = resp.getWriter()) { HandlerUtil.handleSuccess(req, resp, serverUrl, platform, proxyResponse);
writer.write(result);
}
} catch (IOException e) { } catch (IOException e) {
log.error("Error occured when processing invoke call.", e); log.error("Error occured when processing invoke call.", e);
} }
@ -149,23 +134,38 @@ public class InvokerHandler extends HttpServlet {
* @throws IOException If and error occurs while witting error response to client side * @throws IOException If and error occurs while witting error response to client side
*/ */
private static boolean validateRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException { private static boolean validateRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
serverUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort();
apiEndpoint = req.getParameter("api-endpoint");
method = req.getParameter("method");
HttpSession session = req.getSession(false); HttpSession session = req.getSession(false);
if (session == null) { if (session == null) {
resp.sendError(HTTP_UNAUTHORIZED, "Unauthorized, You are not logged in. Please log in to the portal"); log.error("Unauthorized, You are not logged in. Please log in to the portal");
ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setCode(HttpStatus.SC_UNAUTHORIZED);
proxyResponse.setExecutorResponse(
HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + HandlerUtil.getStatusKey(HttpStatus.SC_UNAUTHORIZED));
HandlerUtil.handleError(req, resp, serverUrl, platform, proxyResponse);
return false; return false;
} }
authData = (AuthData) session.getAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY); authData = (AuthData) session.getAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY);
platform = (String) session.getAttribute(HandlerConstants.PLATFORM);
if (authData == null) { if (authData == null) {
resp.sendError(HTTP_UNAUTHORIZED, "Unauthorized, Access token couldn't found in the current session"); log.error("Unauthorized, Access token couldn't found in the current session");
ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setCode(HttpStatus.SC_UNAUTHORIZED);
proxyResponse.setExecutorResponse(
HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + HandlerUtil.getStatusKey(HttpStatus.SC_UNAUTHORIZED));
HandlerUtil.handleError(req, resp, serverUrl, platform, proxyResponse);
return false; return false;
} }
apiEndpoint = req.getParameter("api-endpoint");
method = req.getParameter("method");
serverUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort();
if (apiEndpoint == null || method == null) { if (apiEndpoint == null || method == null) {
resp.sendError(HTTP_BAD_REQUEST, "Bad Request, Either api-endpoint or method is empty"); log.error("Bad Request, Either api-endpoint or method is empty");
ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setCode(HttpStatus.SC_BAD_REQUEST);
proxyResponse.setExecutorResponse(
HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + HandlerUtil.getStatusKey(HttpStatus.SC_BAD_REQUEST));
HandlerUtil.handleError(req, resp, serverUrl, platform, proxyResponse);
return false; return false;
} }
return true; return true;
@ -184,7 +184,12 @@ public class InvokerHandler extends HttpServlet {
serverUrl + HandlerConstants.API_COMMON_CONTEXT + HandlerConstants.TOKEN_ENDPOINT); serverUrl + HandlerConstants.API_COMMON_CONTEXT + HandlerConstants.TOKEN_ENDPOINT);
HttpSession session = req.getSession(false); HttpSession session = req.getSession(false);
if (session == null) { if (session == null) {
resp.sendError(HTTP_UNAUTHORIZED, "Session is expired. Please log in to the server."); log.error("Couldn't find a session, hence it is required to login and proceed.");
ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setCode(HttpStatus.SC_UNAUTHORIZED);
proxyResponse.setExecutorResponse(
HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + HandlerUtil.getStatusKey(HttpStatus.SC_UNAUTHORIZED));
HandlerUtil.handleError(req, resp, serverUrl, platform, proxyResponse);
return false; return false;
} }
@ -197,20 +202,16 @@ public class InvokerHandler extends HttpServlet {
tokenEndpoint.setHeader("Authorization", "Basic " + encodedClientApp); tokenEndpoint.setHeader("Authorization", "Basic " + encodedClientApp);
tokenEndpoint.setHeader("Content-Type", ContentType.APPLICATION_FORM_URLENCODED.toString()); tokenEndpoint.setHeader("Content-Type", ContentType.APPLICATION_FORM_URLENCODED.toString());
HttpResponse response = execute(tokenEndpoint); ProxyResponse tokenResultResponse = execute(tokenEndpoint);
if (response == null) { if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
resp.sendError(HTTP_INTERNAL_ERROR, log.error("Error occurred while refreshing access token.");
"Internal Server Error, response of the token refresh API call is null."); HandlerUtil.handleError(req, resp, serverUrl, platform, tokenResultResponse);
return false;
} else if ((response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)) {
resp.sendError(response.getStatusLine().getStatusCode(),
"Error occured while getting new access token by using refresh token.");
return false; return false;
} }
String tokenResult = retrieveResponseString(response);
JsonParser jsonParser = new JsonParser();
JsonElement jTokenResult = jsonParser.parse(tokenResult); JsonParser jsonParser = new JsonParser();
JsonElement jTokenResult = jsonParser.parse(tokenResultResponse.getData());
if (jTokenResult.isJsonObject()) { if (jTokenResult.isJsonObject()) {
JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject(); JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject();
AuthData newAuthData = new AuthData(); AuthData newAuthData = new AuthData();
@ -226,6 +227,13 @@ public class InvokerHandler extends HttpServlet {
session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, newAuthData); session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, newAuthData);
return true; return true;
} }
log.error("Error Occurred in token renewal process.");
ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
proxyResponse.setExecutorResponse(
HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + HandlerUtil.getStatusKey(HttpStatus.SC_INTERNAL_SERVER_ERROR));
HandlerUtil.handleError(req, resp, serverUrl, platform, proxyResponse);
return false; return false;
} }
} }

View File

@ -22,14 +22,16 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException; import com.google.gson.JsonSyntaxException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType; import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HTTP;
import org.wso2.carbon.device.application.mgt.common.ProxyResponse;
import org.wso2.carbon.device.application.mgt.handler.beans.AuthData; import org.wso2.carbon.device.application.mgt.handler.beans.AuthData;
import org.wso2.carbon.device.application.mgt.handler.exceptions.LoginException; import org.wso2.carbon.device.application.mgt.handler.exceptions.LoginException;
import org.wso2.carbon.device.application.mgt.handler.util.HandlerConstants; import org.wso2.carbon.device.application.mgt.handler.util.HandlerConstants;
@ -47,8 +49,6 @@ import java.io.IOException;
import java.util.Base64; import java.util.Base64;
import static org.wso2.carbon.device.application.mgt.handler.util.HandlerUtil.execute; import static org.wso2.carbon.device.application.mgt.handler.util.HandlerUtil.execute;
import static org.wso2.carbon.device.application.mgt.handler.util.HandlerUtil.loadUiConfig;
import static org.wso2.carbon.device.application.mgt.handler.util.HandlerUtil.retrieveResponseString;
@MultipartConfig @MultipartConfig
@WebServlet("/login") @WebServlet("/login")
@ -79,15 +79,40 @@ public class LoginHandler extends HttpServlet {
//setting session to expiry in 5 mins //setting session to expiry in 5 mins
httpSession.setMaxInactiveInterval(Math.toIntExact(HandlerConstants.TIMEOUT)); httpSession.setMaxInactiveInterval(Math.toIntExact(HandlerConstants.TIMEOUT));
JsonObject uiConfigAsJsonObject = loadUiConfig(uiConfigUrl); HttpGet uiConfigEndpoint = new HttpGet(uiConfigUrl);
if (uiConfigAsJsonObject == null) { JsonParser jsonParser = new JsonParser();
resp.sendRedirect(serverUrl + "/" + platform + HandlerConstants.DEFAULT_ERROR_CALLBACK); ProxyResponse uiConfigResponse = execute(uiConfigEndpoint);
String executorResponse = uiConfigResponse.getExecutorResponse();
if (!StringUtils.isEmpty(executorResponse) && executorResponse
.contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
log.error("Error occurred while getting UI configurations by invoking " + uiConfigUrl);
HandlerUtil.handleError(req, resp, serverUrl, platform, uiConfigResponse);
return; return;
} }
boolean isSsoEnable = uiConfigAsJsonObject.get("isSsoEnable").getAsBoolean(); String uiConfig = uiConfigResponse.getData();
JsonArray tags = uiConfigAsJsonObject.get("appRegistration").getAsJsonObject().get("tags").getAsJsonArray(); if (uiConfig == null){
JsonArray scopes = uiConfigAsJsonObject.get("scopes").getAsJsonArray(); log.error("UI config retrieval is failed, and didn't find UI configuration for App manager.");
HandlerUtil.handleError(req, resp, serverUrl, platform, null);
return;
}
JsonElement uiConfigJsonElement = jsonParser.parse(uiConfigResponse.getData());
JsonObject uiConfigJsonObject = null;
if (uiConfigJsonElement.isJsonObject()) {
uiConfigJsonObject = uiConfigJsonElement.getAsJsonObject();
httpSession.setAttribute(HandlerConstants.UI_CONFIG_KEY, uiConfigJsonObject);
httpSession.setAttribute(HandlerConstants.PLATFORM, serverUrl);
}
if (uiConfigJsonObject == null) {
log.error(
"Either UI config json element is not an json object or converting rom json element to json object is failed.");
HandlerUtil.handleError(req, resp, serverUrl, platform, null);
return;
}
boolean isSsoEnable = uiConfigJsonObject.get("isSsoEnable").getAsBoolean();
JsonArray tags = uiConfigJsonObject.get("appRegistration").getAsJsonObject().get("tags").getAsJsonArray();
JsonArray scopes = uiConfigJsonObject.get("scopes").getAsJsonArray();
if (isSsoEnable) { if (isSsoEnable) {
log.debug("SSO is enabled"); log.debug("SSO is enabled");
@ -98,22 +123,20 @@ public class LoginHandler extends HttpServlet {
.encodeToString((adminUsername + HandlerConstants.COLON + adminPwd).getBytes())); .encodeToString((adminUsername + HandlerConstants.COLON + adminPwd).getBytes()));
apiRegEndpoint.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); apiRegEndpoint.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
apiRegEndpoint.setEntity(constructAppRegPayload(tags)); apiRegEndpoint.setEntity(constructAppRegPayload(tags));
HttpResponse response = execute(apiRegEndpoint);
if (!evaluateResponse(response,resp, HttpStatus.SC_CREATED)){
return;
}
String clientAppResult = retrieveResponseString(response);
if (!clientAppResult.isEmpty() && persistTokenInSession(req, resp, clientAppResult, scopes)) { ProxyResponse clientAppResponse = execute(apiRegEndpoint);
resp.sendRedirect( String clientAppResult = clientAppResponse.getData();
serverUrl + "/" + platform + uiConfigAsJsonObject.get(HandlerConstants.LOGIN_RESPONSE_KEY)
if (!StringUtils.isEmpty(clientAppResult) && getTokenAndPersistInSession(req, resp,
clientAppResponse.getData(), scopes)) {
ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setCode(HttpStatus.SC_OK);
proxyResponse.setUrl(serverUrl + "/" + platform + uiConfigJsonObject.get(HandlerConstants.LOGIN_RESPONSE_KEY)
.getAsJsonObject().get("successCallback").getAsString()); .getAsJsonObject().get("successCallback").getAsString());
HandlerUtil.handleSuccess(req, resp, serverUrl, platform, proxyResponse);
return; return;
} }
resp.sendRedirect( HandlerUtil.handleError(req, resp, serverUrl, platform, null);
serverUrl + "/" + platform + uiConfigAsJsonObject.get(HandlerConstants.LOGIN_RESPONSE_KEY)
.getAsJsonObject().get(HandlerConstants.FAILURE_CALLBACK_KEY).getAsJsonObject()
.get(HandlerUtil.getStatusKey(HandlerConstants.INTERNAL_ERROR_CODE)).getAsString());
} }
} catch (IOException e) { } catch (IOException e) {
log.error("Error occured while sending the response into the socket. ", e); log.error("Error occured while sending the response into the socket. ", e);
@ -131,11 +154,9 @@ public class LoginHandler extends HttpServlet {
* @param scopes - scopes defied in the application-mgt.xml * @param scopes - scopes defied in the application-mgt.xml
* @throws LoginException - login exception throws when getting token result * @throws LoginException - login exception throws when getting token result
*/ */
private boolean persistTokenInSession(HttpServletRequest req, HttpServletResponse resp, String clientAppResult, private boolean getTokenAndPersistInSession(HttpServletRequest req, HttpServletResponse resp,
JsonArray scopes) throws LoginException { String clientAppResult, JsonArray scopes) throws LoginException {
JsonParser jsonParser = new JsonParser(); JsonParser jsonParser = new JsonParser();
String tokenResult;
try { try {
JsonElement jClientAppResult = jsonParser.parse(clientAppResult); JsonElement jClientAppResult = jsonParser.parse(clientAppResult);
if (jClientAppResult.isJsonObject()) { if (jClientAppResult.isJsonObject()) {
@ -145,9 +166,20 @@ public class LoginHandler extends HttpServlet {
String encodedClientApp = Base64.getEncoder() String encodedClientApp = Base64.getEncoder()
.encodeToString((clientId + ":" + clientSecret).getBytes()); .encodeToString((clientId + ":" + clientSecret).getBytes());
tokenResult = getTokenResult(encodedClientApp, scopes, resp); ProxyResponse tokenResultResponse = getTokenResult(encodedClientApp, scopes);
if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
log.error("Error occurred while invoking the API to get token data.");
HandlerUtil.handleError(req, resp, serverUrl, platform, tokenResultResponse);
return false;
}
String tokenResult = tokenResultResponse.getData();
if (tokenResult == null){
log.error("Invalid token response is received.");
HandlerUtil.handleError(req, resp, serverUrl, platform, tokenResultResponse);
return false;
}
if (tokenResult != null) {
JsonElement jTokenResult = jsonParser.parse(tokenResult); JsonElement jTokenResult = jsonParser.parse(tokenResult);
if (jTokenResult.isJsonObject()) { if (jTokenResult.isJsonObject()) {
JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject(); JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject();
@ -164,7 +196,7 @@ public class LoginHandler extends HttpServlet {
authData.setScope(jTokenResultAsJsonObject.get("scope").getAsString()); authData.setScope(jTokenResultAsJsonObject.get("scope").getAsString());
session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, authData); session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, authData);
return true; return true;
}
} }
} }
return false; return false;
@ -236,12 +268,10 @@ public class LoginHandler extends HttpServlet {
* *
* @param encodedClientApp - Base64 encoded clientId:clientSecret. * @param encodedClientApp - Base64 encoded clientId:clientSecret.
* @param scopes - Scopes which are retrieved by reading application-mgt configuration * @param scopes - Scopes which are retrieved by reading application-mgt configuration
* @param resp - {@link HttpServletResponse}
* @return Invoke token endpoint and return the response as string. * @return Invoke token endpoint and return the response as string.
* @throws IOException IO exception throws if an error occured when invoking token endpoint * @throws IOException IO exception throws if an error occured when invoking token endpoint
*/ */
private String getTokenResult(String encodedClientApp, JsonArray scopes, HttpServletResponse resp) private ProxyResponse getTokenResult(String encodedClientApp, JsonArray scopes) throws IOException {
throws IOException, LoginException {
HttpPost tokenEndpoint = new HttpPost(serverUrl + HandlerConstants.TOKEN_ENDPOINT); HttpPost tokenEndpoint = new HttpPost(serverUrl + HandlerConstants.TOKEN_ENDPOINT);
tokenEndpoint.setHeader("Authorization", "Basic " + encodedClientApp); tokenEndpoint.setHeader("Authorization", "Basic " + encodedClientApp);
@ -250,57 +280,14 @@ public class LoginHandler extends HttpServlet {
if (scopeString != null) { if (scopeString != null) {
scopeString = scopeString.trim(); scopeString = scopeString.trim();
} else {
scopeString = "default";
} }
StringEntity tokenEPPayload = new StringEntity( StringEntity tokenEPPayload = new StringEntity(
"grant_type=password&username=" + username + "&password=" + password + "&scope=" + scopeString, "grant_type=password&username=" + username + "&password=" + password + "&scope=" + scopeString,
ContentType.APPLICATION_FORM_URLENCODED); ContentType.APPLICATION_FORM_URLENCODED);
tokenEndpoint.setEntity(tokenEPPayload); tokenEndpoint.setEntity(tokenEPPayload);
HttpResponse response = execute(tokenEndpoint); return execute(tokenEndpoint);
if (evaluateResponse(response, resp, HttpStatus.SC_OK)){
return retrieveResponseString(response);
}
return null;
}
/***
*
* @param response {@link HttpResponse}
* @param resp {@link HttpServletResponse}
* @param expectedStatusCode expected status code of the response
* @return If response returns expected status code, then returns True otherwise returns False after redirect to
* corresponding error page.
* @throws LoginException If an {@link IOException} occurs when redirecting to corresponding error page.
*/
private boolean evaluateResponse(HttpResponse response, HttpServletResponse resp, int expectedStatusCode)
throws LoginException {
JsonObject uiJsonObject = loadUiConfig(uiConfigUrl);
try {
if (response == null) {
if (uiJsonObject != null) {
resp.sendRedirect(serverUrl + uiJsonObject.get(HandlerConstants.LOGIN_RESPONSE_KEY).getAsJsonObject()
.get(HandlerConstants.FAILURE_CALLBACK_KEY).getAsJsonObject()
.get(HandlerUtil.getStatusKey(HandlerConstants.INTERNAL_ERROR_CODE)).getAsString());
return false;
}
resp.sendRedirect(serverUrl + HandlerConstants.DEFAULT_ERROR_CALLBACK);
return false;
} else if (response.getStatusLine().getStatusCode() != expectedStatusCode) {
if (uiJsonObject != null) {
resp.sendRedirect(serverUrl + uiJsonObject.get(HandlerConstants.LOGIN_RESPONSE_KEY).getAsJsonObject()
.get(HandlerConstants.FAILURE_CALLBACK_KEY).getAsJsonObject()
.get(HandlerUtil.getStatusKey(response.getStatusLine().getStatusCode())).getAsString());
return false;
}
resp.sendRedirect(serverUrl + HandlerConstants.DEFAULT_ERROR_CALLBACK);
return false;
}
} catch (IOException e){
throw new LoginException("Error occured while redirecting to corresponding error page. ", e);
}
return true;
} }
} }

View File

@ -20,7 +20,7 @@ package org.wso2.carbon.device.application.mgt.handler.util;
public class HandlerConstants { public class HandlerConstants {
public static final String PUBLISHER_APPLICATION_NAME = "application-mgt-publisher"; public static final String PUBLISHER_APPLICATION_NAME = "application-mgt-publisher";
public static final String APP_REG_ENDPOINT = "/api-application-registration/register"; public static final String APP_REG_ENDPOINT = "/api-application-registration/register";
public static final String UI_CONFIG_ENDPOINT = "/api/application-mgt/v1.0/app-mgt/ui-config"; public static final String UI_CONFIG_ENDPOINT = "/api/application-mgt/v1.0/config/ui-config";
public static final String TOKEN_ENDPOINT = "/oauth2/token"; public static final String TOKEN_ENDPOINT = "/oauth2/token";
public static final String AUTHORIZATION = "Authorization"; public static final String AUTHORIZATION = "Authorization";
public static final String BASIC = "Basic "; public static final String BASIC = "Basic ";
@ -28,10 +28,16 @@ public class HandlerConstants {
public static final String TAGS_KEY = "tags"; public static final String TAGS_KEY = "tags";
public static final String APP_NAME_KEY = "applicationName"; public static final String APP_NAME_KEY = "applicationName";
public static final String SESSION_AUTH_DATA_KEY = "application-mgt"; public static final String SESSION_AUTH_DATA_KEY = "application-mgt";
public static final String AUTHORIZATION_HEADER_KEY = "Authorization";
public static final String UI_CONFIG_KEY = "ui-config";
public static final String PLATFORM = "platform";
public static final String SERVER_HOST = "server-host";
public static final String DEFAULT_ERROR_CALLBACK = "/pages/error/default"; public static final String DEFAULT_ERROR_CALLBACK = "/pages/error/default";
public static final String LOGIN_RESPONSE_KEY = "loginResponse"; public static final String LOGIN_RESPONSE_KEY = "loginResponse";
public static final String FAILURE_CALLBACK_KEY = "FailureCallback"; public static final String FAILURE_CALLBACK_KEY = "failureCallback";
public static final String API_COMMON_CONTEXT = "/api"; public static final String API_COMMON_CONTEXT = "/api";
public static final String EXECUTOR_EXCEPTION_PREFIX = "ExecutorException-";
public static final String TOKEN_IS_EXPIRED = "ACCESS_TOKEN_IS_EXPIRED";
public static final int INTERNAL_ERROR_CODE = 500; public static final int INTERNAL_ERROR_CODE = 500;
public static final long TIMEOUT = 300; public static final long TIMEOUT = 300;

View File

@ -17,9 +17,9 @@
package org.wso2.carbon.device.application.mgt.handler.util; package org.wso2.carbon.device.application.mgt.handler.util;
import com.google.gson.JsonElement; import com.google.gson.Gson;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
@ -28,16 +28,21 @@ import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
import org.wso2.carbon.device.application.mgt.handler.exceptions.LoginException; import org.json.JSONException;
import org.json.JSONObject;
import org.wso2.carbon.device.application.mgt.common.ProxyResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.PrintWriter;
public class HandlerUtil { public class HandlerUtil {
private static final Log log = LogFactory.getLog(HandlerUtil.class); private static final Log log = LogFactory.getLog(HandlerUtil.class);
private static JsonObject uiConfigAsJsonObject;
/*** /***
* *
@ -46,9 +51,9 @@ public class HandlerUtil {
* @return response as string * @return response as string
* @throws IOException IO exception returns if error occurs when executing the httpMethod * @throws IOException IO exception returns if error occurs when executing the httpMethod
*/ */
public static <T> HttpResponse execute(T httpMethod) throws IOException { public static <T> ProxyResponse execute(T httpMethod) throws IOException {
HttpResponse response = null;
try (CloseableHttpClient client = HttpClients.createDefault()) { try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpResponse response = null;
if (httpMethod instanceof HttpPost) { if (httpMethod instanceof HttpPost) {
HttpPost method = (HttpPost) httpMethod; HttpPost method = (HttpPost) httpMethod;
response = client.execute(method); response = client.execute(method);
@ -57,29 +62,48 @@ public class HandlerUtil {
response = client.execute(method); response = client.execute(method);
} }
if (response != null) { ProxyResponse proxyResponse = new ProxyResponse();
return response; if (response == null) {
} proxyResponse.setCode(HandlerConstants.INTERNAL_ERROR_CODE);
return null; proxyResponse.setExecutorResponse(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey(
} HandlerConstants.INTERNAL_ERROR_CODE));
} return proxyResponse;
} else {
/*** int statusCode = response.getStatusLine().getStatusCode();
* try (BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
* @param response {@link HttpResponse}
* @return {@link String} get the response payload by using Entity of the response
* @throws IOException if error occurs while reading the content of the response or reading {@link BufferedReader}
* object
*/
public static String retrieveResponseString (HttpResponse response) throws IOException{
try (BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()))) {
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
String line; String line;
while ((line = rd.readLine()) != null) { while ((line = rd.readLine()) != null) {
result.append(line); result.append(line);
} }
return result.toString();
String jsonString = result.toString();
if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
proxyResponse.setCode(statusCode);
proxyResponse.setData(jsonString);
proxyResponse.setExecutorResponse("SUCCESS");
return proxyResponse;
} else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
if (jsonString.contains("Access token expired") || jsonString
.contains("Invalid input. Access token validation failed")) {
proxyResponse.setCode(statusCode);
proxyResponse.setExecutorResponse("ACCESS_TOKEN_IS_EXPIRED");
return proxyResponse;
} else {
proxyResponse.setCode(statusCode);
proxyResponse.setData(jsonString);
proxyResponse.setExecutorResponse(
HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey(statusCode));
return proxyResponse;
}
}
proxyResponse.setCode(statusCode);
proxyResponse.setData(jsonString);
proxyResponse
.setExecutorResponse(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey(statusCode));
return proxyResponse;
}
}
} }
} }
@ -92,28 +116,28 @@ public class HandlerUtil {
String statusCodeKey; String statusCodeKey;
switch (statusCode) { switch (statusCode) {
case 500: case HttpStatus.SC_INTERNAL_SERVER_ERROR:
statusCodeKey = "internalServerError"; statusCodeKey = "internalServerError";
break; break;
case 400: case HttpStatus.SC_BAD_REQUEST:
statusCodeKey = "badRequest"; statusCodeKey = "badRequest";
break; break;
case 401: case HttpStatus.SC_UNAUTHORIZED:
statusCodeKey = "unauthorized"; statusCodeKey = "unauthorized";
break; break;
case 403: case HttpStatus.SC_FORBIDDEN:
statusCodeKey = "forbidden"; statusCodeKey = "forbidden";
break; break;
case 404: case HttpStatus.SC_NOT_FOUND:
statusCodeKey = "notFound"; statusCodeKey = "notFound";
break; break;
case 405: case HttpStatus.SC_METHOD_NOT_ALLOWED:
statusCodeKey = "methodNotAllowed"; statusCodeKey = "methodNotAllowed";
break; break;
case 406: case HttpStatus.SC_NOT_ACCEPTABLE:
statusCodeKey = "notAcceptable"; statusCodeKey = "notAcceptable";
break; break;
case 415: case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:
statusCodeKey = "unsupportedMediaType"; statusCodeKey = "unsupportedMediaType";
break; break;
default: default:
@ -123,34 +147,87 @@ public class HandlerUtil {
return statusCodeKey; return statusCodeKey;
} }
/*** /***
* *
* @param uiConfigUrl - JSON string of the UI configuration * @param resp {@link HttpServletResponse}
* @return - True returns if UI config load is succeeded and False returns if it fails. Further, if call ie * Return Error Response.
* succeeded assign values for uiConfigAsJsonObject static variable.
* @throws LoginException IO exception could occur if an error occured when invoking end point for getting UI
* configs
*/ */
public static JsonObject loadUiConfig(String uiConfigUrl) throws LoginException { public static void handleError(HttpServletRequest req, HttpServletResponse resp, String serverUrl,
String platform, ProxyResponse proxyResponse) throws IOException {
HttpSession httpSession = req.getSession(true);
Gson gson = new Gson();
if (proxyResponse == null){
proxyResponse = new ProxyResponse();
proxyResponse.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
proxyResponse.setExecutorResponse(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + HandlerUtil
.getStatusKey(HandlerConstants.INTERNAL_ERROR_CODE));
}
if (platform == null){
platform = "default";
}
resp.setStatus(proxyResponse.getCode());
resp.setContentType("application/json");
resp.setCharacterEncoding("UTF-8");
if (httpSession != null) {
JsonObject uiConfig = (JsonObject) httpSession.getAttribute(HandlerConstants.UI_CONFIG_KEY);
if (uiConfig == null){
proxyResponse.setUrl(serverUrl + "/" + platform + HandlerConstants.DEFAULT_ERROR_CALLBACK);
} else{
proxyResponse.setUrl(serverUrl + uiConfig.get(HandlerConstants.LOGIN_RESPONSE_KEY).getAsJsonObject()
.get(HandlerConstants.FAILURE_CALLBACK_KEY).getAsJsonObject()
.get(proxyResponse.getExecutorResponse().split(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)[1])
.getAsString());
}
} else {
proxyResponse.setUrl(serverUrl + "/" + platform + HandlerConstants.DEFAULT_ERROR_CALLBACK);
}
proxyResponse.setExecutorResponse(null);
try (PrintWriter writer = resp.getWriter()) {
writer.write(gson.toJson(proxyResponse));
}
}
/***
*
* @param resp {@link HttpServletResponse}
* Return Success Response.
*/
public static void handleSuccess(HttpServletRequest req, HttpServletResponse resp, String serverUrl,
String platform, ProxyResponse proxyResponse) throws IOException {
if (proxyResponse == null){
handleError(req,resp,serverUrl,platform,proxyResponse);
return;
}
resp.setStatus(proxyResponse.getCode());
resp.setContentType("application/json");
resp.setCharacterEncoding("UTF-8");
JSONObject response = new JSONObject();
String redirectUrl = proxyResponse.getUrl();
String responseData = proxyResponse.getData();
if (!StringUtils.isEmpty(redirectUrl)){
response.put("url", redirectUrl);
}
if (!StringUtils.isEmpty(responseData)){
try { try {
if (uiConfigAsJsonObject != null) { JSONObject responseDataJsonObj = new JSONObject(responseData);
return uiConfigAsJsonObject; response.put("data", responseDataJsonObj);
} } catch (JSONException e) {
HttpGet uiConfigEndpoint = new HttpGet(uiConfigUrl); log.debug("Response data is not valid json string");
JsonParser jsonParser = new JsonParser(); response.put("data", responseData);
HttpResponse response = execute(uiConfigEndpoint);
if (response != null && response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
String uiConfig = retrieveResponseString(response);
JsonElement uiConfigJsonElement = jsonParser.parse(uiConfig);
if (uiConfigJsonElement.isJsonObject()) {
uiConfigAsJsonObject = uiConfigJsonElement.getAsJsonObject();
return uiConfigAsJsonObject;
} }
} }
} catch (IOException e) {
throw new LoginException("Error occured while getting UI configs. ", e); try (PrintWriter writer = resp.getWriter()) {
writer.write(response.toString());
} }
return null;
} }
} }

View File

@ -34,6 +34,11 @@ import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes; import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.application.mgt.common.*; import org.wso2.carbon.device.application.mgt.common.*;
import org.wso2.carbon.device.application.mgt.common.ErrorResponse; import org.wso2.carbon.device.application.mgt.common.ErrorResponse;
import org.wso2.carbon.device.application.mgt.common.dto.ApplicationDTO;
import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO;
import org.wso2.carbon.device.application.mgt.common.response.ApplicationRelease;
import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationReleaseWrapper;
import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationWrapper;
import java.util.List; import java.util.List;
import javax.validation.Valid; import javax.validation.Valid;
@ -55,7 +60,7 @@ import javax.ws.rs.core.Response;
@SwaggerDefinition( @SwaggerDefinition(
info = @Info( info = @Info(
version = "1.0.0", version = "1.0.0",
title = "Application Management Service", title = "ApplicationDTO Management Service",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = "name", value = "ApplicationManagementService"), @ExtensionProperty(name = "name", value = "ApplicationManagementService"),
@ -64,20 +69,20 @@ import javax.ws.rs.core.Response;
} }
), ),
tags = { tags = {
@Tag(name = "application_management, device_management", description = "Application Management related " @Tag(name = "application_management, device_management", description = "ApplicationDTO Management related "
+ "APIs") + "APIs")
} }
) )
@Scopes( @Scopes(
scopes = { scopes = {
@Scope( @Scope(
name = "Get Application Details", name = "Get ApplicationDTO Details",
description = "Get application details", description = "Get application details",
key = "perm:app:publisher:view", key = "perm:app:publisher:view",
permissions = {"/device-mgt/application/view"} permissions = {"/device-mgt/application/view"}
), ),
@Scope( @Scope(
name = "Update an Application", name = "Update an ApplicationDTO",
description = "Update an application", description = "Update an application",
key = "perm:app:publisher:update", key = "perm:app:publisher:update",
permissions = {"/device-mgt/application/update"} permissions = {"/device-mgt/application/update"}
@ -85,14 +90,14 @@ import javax.ws.rs.core.Response;
} }
) )
@Path("/publisher/applications") @Path("/publisher/applications")
@Api(value = "Application Management", description = "This API carries all application management related operations " + @Api(value = "ApplicationDTO Management", description = "This API carries all application management related operations " +
"such as get all the applications, add application, etc.") "such as get all the applications, add application, etc.")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public interface ApplicationManagementAPI { public interface ApplicationManagementAPI {
String SCOPE = "scope"; String SCOPE = "scope";
@GET @POST
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ApiOperation( @ApiOperation(
@ -101,7 +106,7 @@ public interface ApplicationManagementAPI {
httpMethod = "GET", httpMethod = "GET",
value = "get all applications", value = "get all applications",
notes = "This will get all applications", notes = "This will get all applications",
tags = "Application Management", tags = "ApplicationDTO Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:view") @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:view")
@ -122,44 +127,12 @@ public interface ApplicationManagementAPI {
code = 500, code = 500,
message = "Internal Server Error. \n Error occurred while getting the application list.", message = "Internal Server Error. \n Error occurred while getting the application list.",
response = ErrorResponse.class) response = ErrorResponse.class)
}) }) Response getApplications(
Response getApplications(
@ApiParam( @ApiParam(
name = "name", name = "Filter",
value = "Name of the application") value = "Get application filter",
@QueryParam("name") String appName, required = true)
@ApiParam( @Valid Filter filter);
name = "type",
value = "Type of the application")
@QueryParam("type") String appType,
@ApiParam(
name = "category",
value = "Category of the application")
@QueryParam("category") String appCategory,
@ApiParam(
name = "exact-match",
value = "Is it requesting exactly matching application or partially matching application.")
@QueryParam("exact-match") boolean isFullMatch,
@ApiParam(
name = "release-state",
value = "Current state of the application release")
@QueryParam("release-state") String releaseState,
@ApiParam(
name = "offset",
value = "offset",
defaultValue = "0")
@QueryParam("offset") int offset,
@ApiParam(
name = "limit",
value = "limit",
defaultValue = "20")
@QueryParam("limit") int limit,
@ApiParam(
name = "sort",
value = "Sorting type",
defaultValue = "AES")
@QueryParam("sort") String sortBy
);
@GET @GET
@Path("/{appId}") @Path("/{appId}")
@ -171,7 +144,7 @@ public interface ApplicationManagementAPI {
httpMethod = "GET", httpMethod = "GET",
value = "get the application of requesting application id and state", value = "get the application of requesting application id and state",
notes = "This will get the application identified by the application id and state, if exists", notes = "This will get the application identified by the application id and state, if exists",
tags = "Application Management", tags = "ApplicationDTO Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:view") @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:view")
@ -183,7 +156,10 @@ public interface ApplicationManagementAPI {
@ApiResponse( @ApiResponse(
code = 200, code = 200,
message = "OK. \n Successfully retrieved relevant application.", message = "OK. \n Successfully retrieved relevant application.",
response = Application.class), response = ApplicationDTO.class),
@ApiResponse(
code = 403,
message = "Don't have permission to access the application"),
@ApiResponse( @ApiResponse(
code = 404, code = 404,
message = "Application not found"), message = "Application not found"),
@ -206,6 +182,7 @@ public interface ApplicationManagementAPI {
); );
@PUT @PUT
@Path("/{appId}")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ApiOperation( @ApiOperation(
@ -214,7 +191,7 @@ public interface ApplicationManagementAPI {
httpMethod = "PUT", httpMethod = "PUT",
value = "Edit an application", value = "Edit an application",
notes = "This will edit the new application", notes = "This will edit the new application",
tags = "Application Management", tags = "ApplicationDTO Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update") @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update")
@ -226,22 +203,27 @@ public interface ApplicationManagementAPI {
@ApiResponse( @ApiResponse(
code = 200, code = 200,
message = "OK. \n Successfully edited the application.", message = "OK. \n Successfully edited the application.",
response = Application.class), response = ApplicationDTO.class),
@ApiResponse( @ApiResponse(
code = 400, code = 400,
message = "Bad Request. \n " + message = "Bad Request. \n " +
"Application updating payload contains unacceptable or vulnerable data"), "ApplicationDTO updating payload contains unacceptable or vulnerable data"),
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server Error. \n Error occurred while editing the application.", message = "Internal Server Error. \n Error occurred while editing the application.",
response = ErrorResponse.class) response = ErrorResponse.class)
}) })
Response updateApplication( Response updateApplication(
@ApiParam(
name = "appId",
value = "application Id",
required = true)
@PathParam("appId") int appId,
@ApiParam( @ApiParam(
name = "application", name = "application",
value = "The application that need to be edited.", value = "The application that need to be edited.",
required = true) required = true)
@Valid Application application @Valid ApplicationWrapper applicationWrapper
); );
@POST @POST
@ -253,7 +235,7 @@ public interface ApplicationManagementAPI {
httpMethod = "POST", httpMethod = "POST",
value = "Create an application", value = "Create an application",
notes = "This will create a new application", notes = "This will create a new application",
tags = "Application Management", tags = "ApplicationDTO Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update") @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update")
@ -265,11 +247,11 @@ public interface ApplicationManagementAPI {
@ApiResponse( @ApiResponse(
code = 201, code = 201,
message = "OK. \n Successfully created an application.", message = "OK. \n Successfully created an application.",
response = Application.class), response = ApplicationDTO.class),
@ApiResponse( @ApiResponse(
code = 400, code = 400,
message = "Bad Request. \n " + message = "Bad Request. \n " +
"Application creating payload contains unacceptable or vulnerable data"), "ApplicationDTO creating payload contains unacceptable or vulnerable data"),
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server Error. \n Error occurred while creating the application.", message = "Internal Server Error. \n Error occurred while creating the application.",
@ -280,7 +262,7 @@ public interface ApplicationManagementAPI {
name = "application", name = "application",
value = "The application that need to be created.", value = "The application that need to be created.",
required = true) required = true)
@Multipart("application") Application application, @Multipart("application") ApplicationWrapper application,
@ApiParam( @ApiParam(
name = "binaryFile", name = "binaryFile",
value = "Binary file of uploading application", value = "Binary file of uploading application",
@ -316,14 +298,14 @@ public interface ApplicationManagementAPI {
@POST @POST
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Consumes("multipart/mixed") @Consumes("multipart/mixed")
@Path("/{deviceType}/{appType}/{appId}") @Path("/{appType}/{appId}")
@ApiOperation( @ApiOperation(
consumes = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "POST", httpMethod = "POST",
value = "Create an application", value = "Create an application",
notes = "This will create a new application", notes = "This will create a new application",
tags = "Application Management", tags = "ApplicationDTO Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update") @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update")
@ -335,25 +317,32 @@ public interface ApplicationManagementAPI {
@ApiResponse( @ApiResponse(
code = 201, code = 201,
message = "OK. \n Successfully created an application.", message = "OK. \n Successfully created an application.",
response = Application.class), response = ApplicationRelease.class),
@ApiResponse( @ApiResponse(
code = 400, code = 400,
message = "Bad Request. \n " + message = "Bad Request. \n " +
"Application creating payload contains unacceptable or vulnerable data"), "ApplicationDTO creating payload contains unacceptable or vulnerable data"),
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server Error. \n Error occurred while creating the application.", message = "Internal Server Error. \n Error occurred while creating the application.",
response = ErrorResponse.class) response = ErrorResponse.class)
}) })
Response createRelease( Response createRelease(
@PathParam("deviceType") String deviceType, @ApiParam(
@PathParam("appId") String appType, name = "appType",
value = "Application Type.",
required = true)
@PathParam("appType") String appType,
@ApiParam(
name = "appId",
value = "Id of the application.",
required = true)
@PathParam("appId") int appId, @PathParam("appId") int appId,
@ApiParam( @ApiParam(
name = "applicationRelease", name = "applicationRelease",
value = "The application release that need to be created.", value = "The application release that need to be created.",
required = true) required = true)
@Multipart("applicationRelease") ApplicationRelease applicationRelease, @Multipart("applicationRelease") ApplicationReleaseWrapper applicationReleaseWrapper,
@ApiParam( @ApiParam(
name = "binaryFile", name = "binaryFile",
value = "Binary file of uploading application", value = "Binary file of uploading application",
@ -395,7 +384,7 @@ public interface ApplicationManagementAPI {
httpMethod = "DELETE", httpMethod = "DELETE",
value = "Delete the application with the given UUID", value = "Delete the application with the given UUID",
notes = "This will delete the application with the given UUID", notes = "This will delete the application with the given UUID",
tags = "Application Management", tags = "ApplicationDTO Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update") @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update")
@ -416,13 +405,13 @@ public interface ApplicationManagementAPI {
Response deleteApplication( Response deleteApplication(
@ApiParam( @ApiParam(
name = "UUID", name = "UUID",
value = "Unique identifier of the Application", value = "Unique identifier of the ApplicationDTO",
required = true) required = true)
@PathParam("appid") int applicationId @PathParam("appid") int applicationId
); );
@PUT @PUT
@Path("/image-artifacts/{appId}/{uuid}") @Path("/image-artifacts/{uuid}")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Consumes("multipart/mixed") @Consumes("multipart/mixed")
@ApiOperation( @ApiOperation(
@ -431,7 +420,7 @@ public interface ApplicationManagementAPI {
httpMethod = "POST", httpMethod = "POST",
value = "Upload artifacts", value = "Upload artifacts",
notes = "This will create a new application", notes = "This will create a new application",
tags = "Application Management", tags = "ApplicationDTO Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update") @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update")
@ -443,6 +432,10 @@ public interface ApplicationManagementAPI {
@ApiResponse( @ApiResponse(
code = 200, code = 200,
message = "OK. \n Successfully updated artifacts."), message = "OK. \n Successfully updated artifacts."),
@ApiResponse(
code = 400,
message = "Bad Request. \n Requesting to update image artifacts with invalid application "
+ "or application release data."),
@ApiResponse( @ApiResponse(
code = 403, code = 403,
message = "FORBIDDEN. \n Can't Update the application release in PUBLISHED or DEPRECATED " message = "FORBIDDEN. \n Can't Update the application release in PUBLISHED or DEPRECATED "
@ -456,11 +449,6 @@ public interface ApplicationManagementAPI {
response = ErrorResponse.class) response = ErrorResponse.class)
}) })
Response updateApplicationImageArtifacts( Response updateApplicationImageArtifacts(
@ApiParam(
name = "appId",
value = "ID of the application",
required = true)
@PathParam("appId") int applicatioId,
@ApiParam( @ApiParam(
name = "uuid", name = "uuid",
value = "UUID of the application", value = "UUID of the application",
@ -503,7 +491,7 @@ public interface ApplicationManagementAPI {
httpMethod = "POST", httpMethod = "POST",
value = "Upload artifacts", value = "Upload artifacts",
notes = "This will create a new application", notes = "This will create a new application",
tags = "Application Management", tags = "ApplicationDTO Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update") @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update")
@ -518,26 +506,36 @@ public interface ApplicationManagementAPI {
@ApiResponse( @ApiResponse(
code = 400, code = 400,
message = "Bad Request. \n " + message = "Bad Request. \n " +
"Application artifact updating payload contains unacceptable or vulnerable data"), "ApplicationDTO artifact updating payload contains unacceptable or vulnerable data"),
@ApiResponse(
code = 404,
message = "NOT FOUND. \n Couldn't found application/application release to update applocation release artifact."),
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server Error. \n Error occurred while getting the application list.", message = "Internal Server Error. \n Error occurred while getting the application list.",
response = ErrorResponse.class) response = ErrorResponse.class)
}) })
Response updateApplicationArtifact( Response updateApplicationArtifact(
@ApiParam(name = "deviceType", value = "Type of the device i.e Android, IOS etc", required = true) @ApiParam(
name = "deviceType",
value = "Type of the device i.e Android, IOS etc",
required = true)
@PathParam("deviceType") String deviceType, @PathParam("deviceType") String deviceType,
@ApiParam(name = "appType", value = "Type of the application i.e Mobile, WEB, WEB-CLIP etc", required = true) @ApiParam(
name = "appType",
value = "Type of the application i.e ENTERPRISE, PUBLIC, WEB, WEB-CLIP etc",
required = true)
@PathParam("appType") String appType, @PathParam("appType") String appType,
@ApiParam(name = "appId", value = "Id of the application", required = true) @ApiParam(
@PathParam("appId") int applicationId, name = "uuid",
@ApiParam(name = "uuid", value = "UUID of the application", required = true) value = "UUID of the application",
required = true)
@PathParam("uuid") String applicationUUID, @PathParam("uuid") String applicationUUID,
@Multipart("binaryFile") Attachment binaryFile @Multipart("binaryFile") Attachment binaryFile
); );
@PUT @PUT
@Path("/{appId}/{uuid}") @Path("/{deviceType}/{appId}/{uuid}")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA) @Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation( @ApiOperation(
@ -546,7 +544,7 @@ public interface ApplicationManagementAPI {
httpMethod = "PUT", httpMethod = "PUT",
value = "Update an application release", value = "Update an application release",
notes = "This will update a new application release", notes = "This will update a new application release",
tags = "Application Management", tags = "ApplicationDTO Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update") @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update")
@ -558,24 +556,33 @@ public interface ApplicationManagementAPI {
@ApiResponse( @ApiResponse(
code = 201, code = 201,
message = "OK. \n Successfully created an application release.", message = "OK. \n Successfully created an application release.",
response = ApplicationRelease.class), response = ApplicationReleaseDTO.class),
@ApiResponse( @ApiResponse(
code = 400, code = 400,
message = "Bad Request. \n " + message = "Bad Request. \n " +
"Application release updating payload contains unacceptable or vulnerable data"), "ApplicationDTO release updating payload contains unacceptable or vulnerable data"),
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server Error. \n Error occurred while releasing the application.", message = "Internal Server Error. \n Error occurred while releasing the application.",
response = ErrorResponse.class) response = ErrorResponse.class)
}) })
Response updateApplicationRelease( Response updateApplicationRelease(
@ApiParam(name = "appId", value = "Identifier of the Application", required = true) @PathParam("appId") int applicationId, @ApiParam(name = "deviceType", value = "Supported device type of the application", required = true)
@ApiParam(name = "UUID", value = "Unique identifier of the Application Release", required = true) @PathParam("uuid") String applicationUUID, @PathParam("deviceType") String deviceType,
@Multipart(value = "applicationRelease", required = false, type = "application/json") ApplicationRelease applicationRelease, @ApiParam(name = "appId", value = "Identifier of the ApplicationDTO", required = true)
@PathParam("appId") int applicationId,
@ApiParam(name = "UUID", value = "Unique identifier of the ApplicationDTO Release", required = true)
@PathParam("uuid") String applicationUUID,
@Multipart(value = "applicationRelease", required = false, type = "application/json") ApplicationReleaseDTO applicationRelease,
@Multipart(value = "binaryFile", required = false) Attachment binaryFile, @Multipart(value = "binaryFile", required = false) Attachment binaryFile,
@Multipart(value = "icon", required = false) Attachment iconFile, @Multipart(value = "icon", required = false) Attachment iconFile,
@Multipart(value = "banner", required = false) Attachment bannerFile, @Multipart(value = "banner", required = false) Attachment bannerFile,
@Multipart(value = "screenshot", required = false) List<Attachment> attachmentList); @ApiParam(name = "screenshot1", value = "Screen Shots of the uploading application", required = true)
@Multipart(value = "screenshot1") Attachment screenshot1,
@ApiParam(name = "screenshot2", value = "Screen Shots of the uploading application")
@Multipart(value = "screenshot2") Attachment screenshot2,
@ApiParam(name = "screenshot3", value = "Screen Shots of the uploading application")
@Multipart(value = "screenshot3") Attachment screenshot3);
@GET @GET
@Path("/lifecycle/{appId}/{uuid}") @Path("/lifecycle/{appId}/{uuid}")
@ -629,7 +636,7 @@ public interface ApplicationManagementAPI {
@ApiResponse( @ApiResponse(
code = 201, code = 201,
message = "OK. \n Successfully add a lifecycle state.", message = "OK. \n Successfully add a lifecycle state.",
response = Application.class), response = ApplicationDTO.class),
@ApiResponse( @ApiResponse(
code = 400, code = 400,
message = "Bad Request. \n " + message = "Bad Request. \n " +
@ -646,12 +653,12 @@ public interface ApplicationManagementAPI {
Response addLifecycleState( Response addLifecycleState(
@ApiParam( @ApiParam(
name = "appId", name = "appId",
value = "Identifier of the Application", value = "Identifier of the ApplicationDTO",
required = true) required = true)
@PathParam("appId") int applicationId, @PathParam("appId") int applicationId,
@ApiParam( @ApiParam(
name = "uuid", name = "uuid",
value = "UUID of the Application Release", value = "UUID of the ApplicationDTO Release",
required = true) required = true)
@PathParam("uuid") String applicationUuid, @PathParam("uuid") String applicationUuid,
@ApiParam( @ApiParam(

View File

@ -23,22 +23,32 @@ import org.apache.commons.logging.LogFactory;
import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.cxf.jaxrs.ext.multipart.Multipart; import org.apache.cxf.jaxrs.ext.multipart.Multipart;
import org.wso2.carbon.device.application.mgt.common.*; import org.wso2.carbon.device.application.mgt.common.*;
import org.wso2.carbon.device.application.mgt.common.dto.ApplicationDTO;
import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO;
import org.wso2.carbon.device.application.mgt.common.dto.LifecycleStateDTO;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationStorageManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationStorageManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.RequestValidatingException; import org.wso2.carbon.device.application.mgt.common.exception.RequestValidatingException;
import org.wso2.carbon.device.application.mgt.common.response.Application;
import org.wso2.carbon.device.application.mgt.common.response.ApplicationRelease;
import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationReleaseWrapper;
import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationWrapper;
import org.wso2.carbon.device.application.mgt.core.exception.BadRequestException;
import org.wso2.carbon.device.application.mgt.core.exception.ForbiddenException;
import org.wso2.carbon.device.application.mgt.core.exception.ValidationException;
import org.wso2.carbon.device.application.mgt.core.util.APIUtil; import org.wso2.carbon.device.application.mgt.core.util.APIUtil;
import org.wso2.carbon.device.application.mgt.publisher.api.services.ApplicationManagementAPI; import org.wso2.carbon.device.application.mgt.publisher.api.services.ApplicationManagementAPI;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager; 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.exception.NotFoundException;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.Map;
import javax.activation.DataHandler;
import javax.validation.Valid; import javax.validation.Valid;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE; import javax.ws.rs.DELETE;
@ -62,44 +72,24 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
private static Log log = LogFactory.getLog(ApplicationManagementAPIImpl.class); private static Log log = LogFactory.getLog(ApplicationManagementAPIImpl.class);
@GET @POST
@Override @Override
@Consumes("application/json") @Consumes("application/json")
public Response getApplications( public Response getApplications(
@QueryParam("name") String appName, @Valid Filter filter ){
@QueryParam("type") String appType,
@QueryParam("category") String appCategory,
@QueryParam("exact-match") boolean isFullMatch,
@QueryParam("release-state") String releaseState,
@DefaultValue("0") @QueryParam("offset") int offset,
@DefaultValue("20") @QueryParam("limit") int limit,
@DefaultValue("ASC") @QueryParam("sort") String sortBy) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
try { try {
Filter filter = new Filter();
filter.setOffset(offset);
filter.setLimit(limit);
filter.setSortBy(sortBy);
filter.setFullMatch(isFullMatch);
if (appName != null && !appName.isEmpty()) {
filter.setAppName(appName);
}
if (appType != null && !appType.isEmpty()) {
filter.setAppType(appType);
}
if (appCategory != null && !appCategory.isEmpty()) {
filter.setAppCategory(appCategory);
}
if (releaseState != null && !releaseState.isEmpty()) {
filter.setCurrentAppReleaseState(releaseState);
}
ApplicationList applications = applicationManager.getApplications(filter); ApplicationList applications = applicationManager.getApplications(filter);
if (applications.getApplications().isEmpty()) { if (applications.getApplications().isEmpty()) {
return Response.status(Response.Status.NOT_FOUND) return Response.status(Response.Status.OK)
.entity("Couldn't find any application for requested query.").build(); .entity("Couldn't find any application for the requested query.").build();
} }
return Response.status(Response.Status.OK).entity(applications).build(); return Response.status(Response.Status.OK).entity(applications).build();
} catch(BadRequestException e){
String msg = "Incompatible request payload is found. Please try with valid reuest payload.";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}catch (ApplicationManagementException e) { }catch (ApplicationManagementException e) {
String msg = "Error occurred while getting the application list for publisher "; String msg = "Error occurred while getting the application list for publisher ";
log.error(msg, e); log.error(msg, e);
@ -116,12 +106,23 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
try { try {
Application application = applicationManager.getApplicationById(appId, state); Application application = applicationManager.getApplicationById(appId, state);
if (application == null){
String msg = "Couldn't found an application release which is in " + state + " state for application id "
+ appId;
log.error(msg);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
return Response.status(Response.Status.OK).entity(application).build(); return Response.status(Response.Status.OK).entity(application).build();
} catch (NotFoundException e) { } catch (NotFoundException e) {
String msg = "Application with application id: " + appId + " not found"; String msg = "ApplicationDTO with application id: " + appId + " not found";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (ApplicationManagementException e) { } catch(ForbiddenException e){
String msg = "You don't have permission to access the application. application id: " + appId;
log.error(msg);
return Response.status(Response.Status.FORBIDDEN).entity(msg).build();
}
catch (ApplicationManagementException e) {
String msg = "Error occurred while getting application with the id " + appId; String msg = "Error occurred while getting application with the id " + appId;
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
@ -131,7 +132,7 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
@POST @POST
@Consumes("multipart/mixed") @Consumes("multipart/mixed")
public Response createApplication( public Response createApplication(
@Multipart("application") Application application, @Multipart("application") ApplicationWrapper applicationWrapper,
@Multipart("binaryFile") Attachment binaryFile, @Multipart("binaryFile") Attachment binaryFile,
@Multipart("icon") Attachment iconFile, @Multipart("icon") Attachment iconFile,
@Multipart("banner") Attachment bannerFile, @Multipart("banner") Attachment bannerFile,
@ -139,14 +140,11 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
@Multipart("screenshot2") Attachment screenshot2, @Multipart("screenshot2") Attachment screenshot2,
@Multipart("screenshot3") Attachment screenshot3) { @Multipart("screenshot3") Attachment screenshot3) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
InputStream iconFileStream;
InputStream bannerFileStream;
List<InputStream> attachments = new ArrayList<>();
List<ApplicationRelease> applicationReleases = new ArrayList<>();
ApplicationRelease applicationRelease;
List<Attachment> attachmentList = new ArrayList<>(); List<Attachment> attachmentList = new ArrayList<>();
if (screenshot1 != null) {
attachmentList.add(screenshot1); attachmentList.add(screenshot1);
}
if (screenshot2 != null) { if (screenshot2 != null) {
attachmentList.add(screenshot2); attachmentList.add(screenshot2);
} }
@ -155,85 +153,40 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
} }
try { try {
if (!isValidAppCreatingRequest(iconFile, bannerFile, attachmentList, application)) { applicationManager.validateAppCreatingRequest(applicationWrapper);
return Response.status(Response.Status.BAD_REQUEST).build(); applicationManager.validateReleaseCreatingRequest(applicationWrapper.getApplicationReleaseWrappers().get(0),
} applicationWrapper.getType());
applicationManager.validateBinaryArtifact(binaryFile, applicationWrapper.getType());
// The application executable artifacts such as apks are uploaded. applicationManager.validateImageArtifacts(iconFile, bannerFile, attachmentList);
if (!ApplicationType.ENTERPRISE.toString().equals(application.getType())) {
applicationRelease = application.getApplicationReleases().get(0);
applicationRelease = applicationStorageManager
.uploadReleaseArtifact(applicationRelease, application.getType(), application.getDeviceType(),
null);
} else {
if (binaryFile == null){
String msg = "Binary file is not found for the application release. Application name: " + application.getName()
+ " Application type: " + application.getType();
return Response.status(Response.Status.BAD_REQUEST).entity(new ApplicationManagementException(msg))
.build();
}
applicationRelease = application.getApplicationReleases().get(0);
applicationRelease = applicationStorageManager
.uploadReleaseArtifact(applicationRelease, application.getType(), application.getDeviceType(),
binaryFile.getDataHandler().getInputStream());
if (applicationRelease.getAppStoredLoc() == null || applicationRelease.getAppHashValue() == null) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
iconFileStream = iconFile.getDataHandler().getInputStream();
bannerFileStream = bannerFile.getDataHandler().getInputStream();
for (Attachment screenshot : attachmentList) {
attachments.add(screenshot.getDataHandler().getInputStream());
}
// Upload images
applicationRelease = applicationStorageManager
.uploadImageArtifacts(applicationRelease, iconFileStream, bannerFileStream, attachments);
applicationRelease.setUuid(UUID.randomUUID().toString());
applicationReleases.add(applicationRelease);
application.setApplicationReleases(applicationReleases);
// Created new application entry // Created new application entry
Application createdApplication = applicationManager.createApplication(application); Application application = applicationManager.createApplication(applicationWrapper,
if (createdApplication != null) { constructApplicationArtifact(binaryFile, iconFile, bannerFile, attachmentList));
return Response.status(Response.Status.CREATED).entity(createdApplication).build(); if (application != null) {
return Response.status(Response.Status.CREATED).entity(application).build();
} else { } else {
String msg = "Application creation is failed"; String msg = "ApplicationDTO creation is failed";
log.error(msg); log.error(msg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
String msg = "Error occurred while creating the application"; String msg = "Error occurred while creating the application";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (ResourceManagementException e) {
String msg =
"Error occurred while uploading the releases artifacts of the application " + application.getName();
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (IOException e) {
String msg =
"Error while uploading binary file and resources for the application release of the application "
+ application.getName();
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (RequestValidatingException e) { } catch (RequestValidatingException e) {
String msg = "Error occurred while handling the application creating request"; String msg = "Error occurred while handling the application creating request";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).build(); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} }
} }
@POST @POST
@Consumes("multipart/mixed") @Consumes("multipart/mixed")
@Path("/{deviceType}/{appType}/{appId}") @Path("/{appType}/{appId}")
public Response createRelease( public Response createRelease(
@PathParam("deviceType") String deviceType, @PathParam("appType") String appType,
@PathParam("appId") String appType,
@PathParam("appId") int appId, @PathParam("appId") int appId,
@Multipart("applicationRelease") ApplicationRelease applicationRelease, @Multipart("applicationRelease") ApplicationReleaseWrapper applicationReleaseWrapper,
@Multipart("binaryFile") Attachment binaryFile, @Multipart("binaryFile") Attachment binaryFile,
@Multipart("icon") Attachment iconFile, @Multipart("icon") Attachment iconFile,
@Multipart("banner") Attachment bannerFile, @Multipart("banner") Attachment bannerFile,
@ -241,12 +194,11 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
@Multipart("screenshot2") Attachment screenshot2, @Multipart("screenshot2") Attachment screenshot2,
@Multipart("screenshot3") Attachment screenshot3) { @Multipart("screenshot3") Attachment screenshot3) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
InputStream iconFileStream;
InputStream bannerFileStream;
List<InputStream> attachments = new ArrayList<>();
List<Attachment> attachmentList = new ArrayList<>(); List<Attachment> attachmentList = new ArrayList<>();
if (screenshot1 != null) {
attachmentList.add(screenshot1); attachmentList.add(screenshot1);
}
if (screenshot2 != null) { if (screenshot2 != null) {
attachmentList.add(screenshot2); attachmentList.add(screenshot2);
} }
@ -255,56 +207,23 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
} }
try { try {
if (!isValidReleaseCreatingRequest(binaryFile, iconFile, bannerFile, attachmentList, appType)) { applicationManager.validateReleaseCreatingRequest(applicationReleaseWrapper, appType);
return Response.status(Response.Status.BAD_REQUEST).build(); applicationManager.validateBinaryArtifact(binaryFile, appType);
} applicationManager.validateImageArtifacts(iconFile, bannerFile, attachmentList);
// The application executable artifacts such as apks are uploaded. // Created new application release
if (!ApplicationType.ENTERPRISE.toString().equals(appType)) { ApplicationRelease release = applicationManager.createRelease(appId, applicationReleaseWrapper,
applicationRelease = applicationStorageManager constructApplicationArtifact(binaryFile, iconFile, bannerFile, attachmentList));
.uploadReleaseArtifact(applicationRelease, appType, deviceType, null);
} else {
applicationRelease = applicationStorageManager
.uploadReleaseArtifact(applicationRelease, appType, deviceType,
binaryFile.getDataHandler().getInputStream());
if (applicationRelease.getAppStoredLoc() == null || applicationRelease.getAppHashValue() == null) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
iconFileStream = iconFile.getDataHandler().getInputStream();
bannerFileStream = bannerFile.getDataHandler().getInputStream();
for (Attachment screenshot : attachmentList) {
attachments.add(screenshot.getDataHandler().getInputStream());
}
// Upload images
applicationRelease = applicationStorageManager
.uploadImageArtifacts(applicationRelease, iconFileStream, bannerFileStream, attachments);
applicationRelease.setUuid(UUID.randomUUID().toString());
// Created new application release entry
ApplicationRelease release = applicationManager.createRelease(appId, applicationRelease);
if (release != null) { if (release != null) {
return Response.status(Response.Status.CREATED).entity(release).build(); return Response.status(Response.Status.CREATED).entity(release).build();
} else { } else {
log.error("Application Creation Failed"); log.error("ApplicationDTO Creation Failed");
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} }
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
String msg = "Error occurred while creating the application"; String msg = "Error occurred while creating the application";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (ResourceManagementException e) {
String msg = "Error occurred while uploading the releases artifacts of the application ID: " + appId;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (IOException e) {
String msg = "Error while uploading binary file and resources for the application release of the "
+ "application ID: " + appId;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (RequestValidatingException e) { } catch (RequestValidatingException e) {
String msg = "Error occurred while handling the application creating request"; String msg = "Error occurred while handling the application creating request";
log.error(msg, e); log.error(msg, e);
@ -316,186 +235,189 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
@PUT @PUT
@Consumes("multipart/mixed") @Consumes("multipart/mixed")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Path("/image-artifacts/{appId}/{uuid}") @Path("/image-artifacts/{uuid}")
public Response updateApplicationImageArtifacts( public Response updateApplicationImageArtifacts(
@PathParam("appId") int appId, @PathParam("uuid") String applicationUuid, @PathParam("uuid") String applicationReleaseUuid,
@Multipart("icon") Attachment iconFile, @Multipart("banner") Attachment bannerFile, @Multipart("icon") Attachment iconFile,
@Multipart("screenshot1") Attachment screenshot1, @Multipart("screenshot2") Attachment screenshot2, @Multipart("banner") Attachment bannerFile,
@Multipart("screenshot1") Attachment screenshot1,
@Multipart("screenshot2") Attachment screenshot2,
@Multipart("screenshot3") Attachment screenshot3) { @Multipart("screenshot3") Attachment screenshot3) {
try { try {
InputStream iconFileStream = null; List<Attachment> attachments = new ArrayList<>();
InputStream bannerFileStream = null;
List<InputStream> attachments = new ArrayList<>();
if (iconFile != null) { if (screenshot1 != null) {
iconFileStream = iconFile.getDataHandler().getInputStream(); attachments.add(screenshot1);
} }
if (bannerFile != null) {
bannerFileStream = bannerFile.getDataHandler().getInputStream();
}
attachments.add(screenshot1.getDataHandler().getInputStream());
if (screenshot2 != null) { if (screenshot2 != null) {
attachments.add(screenshot2.getDataHandler().getInputStream()); attachments.add(screenshot2);
} }
if (screenshot3 != null) { if (screenshot3 != null) {
attachments.add(screenshot3.getDataHandler().getInputStream()); attachments.add(screenshot3);
} }
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
applicationManager.updateApplicationImageArtifact(appId, applicationUuid, iconFileStream, bannerFileStream, applicationManager.validateImageArtifacts(iconFile, bannerFile, attachments);
attachments); applicationManager.updateApplicationImageArtifact(applicationReleaseUuid,
constructApplicationArtifact(null, iconFile, bannerFile, attachments));
return Response.status(Response.Status.OK) return Response.status(Response.Status.OK)
.entity("Successfully uploaded artifacts for the application " + applicationUuid).build(); .entity("Successfully uploaded artifacts for the application " + applicationReleaseUuid).build();
} catch (RequestValidatingException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
} catch (NotFoundException e) { } catch (NotFoundException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
return APIUtil.getResponse(e, Response.Status.NOT_FOUND); return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
} catch (ForbiddenException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.FORBIDDEN).entity(e.getMessage()).build();
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
String msg = "Error occurred while updating the application."; String msg = "Error occurred while updating the application image artifacts for application release uuid: "
+ applicationReleaseUuid;
log.error(msg, e); log.error(msg, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (IOException e) {
String msg = "Exception while trying to read icon, banner files for the application " + applicationUuid;
log.error(msg);
return APIUtil
.getResponse(new ApplicationManagementException(msg, e), Response.Status.INTERNAL_SERVER_ERROR);
} catch (ResourceManagementException e) {
log.error("Error occurred while uploading the image artifacts of the application with the uuid "
+ applicationUuid, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} }
} }
@Override @Override
@PUT @PUT
@Consumes("multipart/mixed") @Consumes("multipart/mixed")
@Path("/app-artifacts/{deviceType}/{appType}/{appId}/{uuid}") @Path("/app-artifact/{deviceType}/{appType}/{uuid}")
public Response updateApplicationArtifact( public Response updateApplicationArtifact(
@PathParam("deviceType") String deviceType, @PathParam("deviceType") String deviceType,
@PathParam("appType") String appType, @PathParam("appType") String appType,
@PathParam("appId") int applicationId, @PathParam("uuid") String applicationReleaseUuid,
@PathParam("uuid") String applicationUuid,
@Multipart("binaryFile") Attachment binaryFile) { @Multipart("binaryFile") Attachment binaryFile) {
try { try {
ApplicationManager applicationManager = APIUtil.getApplicationManager();
if (binaryFile == null) { if (!ApplicationType.ENTERPRISE.toString().equals(appType)) {
return APIUtil.getResponse("Uploading artifacts for the application is failed " + applicationUuid, String msg = "If ApplicationDTO type is " + appType
Response.Status.BAD_REQUEST); + ", therefore you don't have application release artifact to update for application release UUID: "
} + applicationReleaseUuid;
APIUtil.getApplicationManager().updateApplicationArtifact(applicationId, applicationUuid,
binaryFile.getDataHandler().getInputStream());
return Response.status(Response.Status.OK)
.entity("Successfully uploaded artifacts for the application release. UUID is " + applicationUuid)
.build();
} catch (IOException e) {
String msg = "Error occurred while trying to read icon, banner files for the application release"
+ applicationUuid;
log.error(msg); log.error(msg);
return APIUtil.getResponse(new ApplicationManagementException(msg, e), Response.Status.BAD_REQUEST); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ResourceManagementException e) { }
log.error("Error occurred while uploading the image artifacts of the application with the uuid " applicationManager.validateBinaryArtifact(binaryFile, appType);
+ applicationUuid, e); applicationManager.updateApplicationArtifact(deviceType, appType, applicationReleaseUuid,
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR); constructApplicationArtifact(binaryFile, null, null, null));
return Response.status(Response.Status.OK)
.entity("Successfully uploaded artifacts for the application release. UUID is "
+ applicationReleaseUuid).build();
} catch (RequestValidatingException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
} catch (NotFoundException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
log.error("Error occurred while updating the image artifacts of the application with the uuid " log.error("Error occurred while updating the image artifacts of the application with the uuid "
+ applicationUuid, e); + applicationReleaseUuid, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
} catch (RequestValidatingException e) {
log.error(
"Error occured while handling the application artifact updating request. application release UUID: "
+ applicationUuid);
return APIUtil.getResponse(e, Response.Status.BAD_REQUEST);
} catch (DeviceManagementException e) {
log.error("Error occurred while updating the image artifacts of the application with the uuid "
+ applicationUuid, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} }
} }
@PUT @PUT
@Consumes("application/json") @Consumes("application/json")
public Response updateApplication(@Valid Application application) { @Path("/{appId}")
public Response updateApplication(
@PathParam("appId") int applicationId,
@Valid ApplicationWrapper applicationWrapper) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
try { try {
application = applicationManager.updateApplication(application); //todo wrong
applicationManager.updateApplication(applicationId, applicationWrapper);
return Response.status(Response.Status.OK)
.entity("Application was updated successfully. ApplicationID " + applicationId).build();
} catch (NotFoundException e) { } catch (NotFoundException e) {
return APIUtil.getResponse(e, Response.Status.NOT_FOUND); log.error(e.getMessage());
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
} catch (ForbiddenException e) {
log.error(e.getMessage());
return Response.status(Response.Status.FORBIDDEN).entity(e.getMessage()).build();
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
String msg = "Error occurred while modifying the application"; String msg = "Error occurred while modifying the application";
log.error(msg, e); log.error(msg, e);
return APIUtil.getResponse(e, Response.Status.BAD_REQUEST); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} }
return Response.status(Response.Status.OK).entity(application).build();
} }
@Override @Override
@PUT @PUT
@Path("/{appId}/{uuid}") @Path("/{deviceType}/{appId}/{uuid}")
public Response updateApplicationRelease( public Response updateApplicationRelease(
@PathParam("deviceType") String deviceType,
@PathParam("appId") int applicationId, @PathParam("appId") int applicationId,
@PathParam("uuid") String applicationUUID, @PathParam("uuid") String applicationUUID,
@Multipart("applicationRelease") ApplicationRelease applicationRelease, @Multipart("applicationRelease") ApplicationReleaseDTO applicationRelease,
@Multipart("binaryFile") Attachment binaryFile, @Multipart("binaryFile") Attachment binaryFile,
@Multipart("icon") Attachment iconFile, @Multipart("icon") Attachment iconFile,
@Multipart("banner") Attachment bannerFile, @Multipart("banner") Attachment bannerFile,
@Multipart("screenshot") List<Attachment> attachmentList) { @Multipart("screenshot1") Attachment screenshot1,
@Multipart("screenshot2") Attachment screenshot2,
@Multipart("screenshot3") Attachment screenshot3) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager(); InputStream iconFileStream;
InputStream iconFileStream = null; InputStream bannerFileStream;
InputStream bannerFileStream = null; InputStream binaryFileStram;
List<InputStream> attachments = new ArrayList<>(); List<InputStream> attachments = new ArrayList<>();
List<Attachment> attachmentList = new ArrayList<>();
try { if (screenshot1 != null){
Application application = applicationManager.getApplicationIfAccessible(applicationId); attachmentList.add(screenshot1);
}
if (!applicationManager.isAcceptableAppReleaseUpdate(application.getId(), applicationRelease.getUuid())) { if (screenshot2 != null) {
String msg = "Application release is in the " + applicationRelease.getLifecycleState().getCurrentState() attachmentList.add(screenshot2);
+ " state. Hence updating is not acceptable when application in this state"; }
log.error(msg); if (screenshot3 != null) {
attachmentList.add(screenshot3);
}
if (iconFile == null || bannerFile == null || binaryFile == null || attachmentList.isEmpty()){
String msg = "Invalid data is received for application release updating. application id: " + applicationId
+ " and application release UUID: " + applicationUUID;
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} }
if (binaryFile != null) {
applicationRelease = applicationStorageManager try {
.updateReleaseArtifacts(applicationRelease, application.getType(), application.getDeviceType(), binaryFileStram = binaryFile.getDataHandler().getInputStream();
binaryFile.getDataHandler().getInputStream());
}
if (iconFile != null) {
iconFileStream = iconFile.getDataHandler().getInputStream(); iconFileStream = iconFile.getDataHandler().getInputStream();
}
if (bannerFile != null) {
bannerFileStream = bannerFile.getDataHandler().getInputStream(); bannerFileStream = bannerFile.getDataHandler().getInputStream();
}
if (!attachmentList.isEmpty()) {
for (Attachment screenshot : attachmentList) { for (Attachment screenshot : attachmentList) {
attachments.add(screenshot.getDataHandler().getInputStream()); attachments.add(screenshot.getDataHandler().getInputStream());
} }
boolean status = applicationManager
.updateRelease(applicationId, applicationUUID, deviceType, applicationRelease, binaryFileStram,
iconFileStream, bannerFileStream, attachments);
if (!status){
log.error("ApplicationDTO release updating is failed. Please contact the administrator. ApplicationDTO id: "
+ applicationId + ", ApplicationDTO release UUID: " + applicationUUID + ", Supported device type: "
+ deviceType);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(applicationRelease).build();
} }
return Response.status(Response.Status.OK).entity("ApplicationDTO release is successfully updated.").build();
// applicationRelease = applicationStorageManager } catch(BadRequestException e){
// .updateImageArtifacts(applicationRelease, iconFileStream, bannerFileStream, attachments); String msg = "Invalid request to update application release for application release UUID " + applicationUUID;
// applicationRelease = applicationManager.updateRelease(applicationId, applicationRelease); log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
return Response.status(Response.Status.OK).entity(applicationRelease).build(); } catch (NotFoundException e) {
} catch (ApplicationManagementException e) { String msg = "Couldn't found application or application release for application id: " + applicationId
log.error("Error while updating the application release of the application with UUID " + applicationUUID); + " and application release UUID " + applicationUUID;
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR); log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (ForbiddenException e) {
String msg = "You don't have require permission to update the application release which has UUID "
+ applicationUUID;
log.error(msg, e);
return Response.status(Response.Status.FORBIDDEN).entity(msg).build();
}
catch (ApplicationManagementException e) {
String msg = "Error while updating the application release of the application with UUID " + applicationUUID;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (IOException e) { } catch (IOException e) {
log.error("Error while updating the release artifacts of the application with UUID " + applicationUUID); String msg = "Error while updating the release artifacts of the application with UUID " + applicationUUID;
return APIUtil.getResponse(new ApplicationManagementException( log.error(msg, e);
"Error while updating the release artifacts of the application with UUID " + applicationUUID), return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
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.getVersion(), e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} catch (RequestValidatingException e) {
log.error(
"Error occured while handling the application release updating request. application release UUID: "
+ applicationUUID);
return APIUtil.getResponse(e, Response.Status.BAD_REQUEST);
} }
} }
@ -510,14 +432,23 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
applicationStorageManager.deleteAllApplicationReleaseArtifacts(storedLocations); applicationStorageManager.deleteAllApplicationReleaseArtifacts(storedLocations);
String responseMsg = "Successfully deleted the application and application releases: " + applicationId; String responseMsg = "Successfully deleted the application and application releases: " + applicationId;
return Response.status(Response.Status.OK).entity(responseMsg).build(); return Response.status(Response.Status.OK).entity(responseMsg).build();
} catch (NotFoundException e) {
String msg =
"Couldn't found application for application id: " + applicationId + " to delete the application";
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (ForbiddenException e) {
String msg = "You don't have require permission to delete the application which has ID " + applicationId;
log.error(msg, e);
return Response.status(Response.Status.FORBIDDEN).entity(msg).build();
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
String msg = "Error occurred while deleting the application: " + applicationId; String msg = "Error occurred while deleting the application: " + applicationId;
log.error(msg, e); log.error(msg, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (ApplicationStorageManagementException e) { } catch (ApplicationStorageManagementException e) {
String msg = "Error occurred while deleting the application storage: " + applicationId; String msg = "Error occurred while deleting the application storage: " + applicationId;
log.error(msg, e); log.error(msg, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
@ -529,18 +460,29 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager(); ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
try { try {
String storedLocation = applicationManager.deleteApplicationRelease(applicationId, releaseUuid, true); String storedLocation = applicationManager.deleteApplicationRelease(applicationId, releaseUuid);
applicationStorageManager.deleteApplicationReleaseArtifacts(storedLocation); applicationStorageManager.deleteApplicationReleaseArtifacts(storedLocation);
String responseMsg = "Successfully deleted the application release of: " + applicationId + ""; String responseMsg = "Successfully deleted the application release of: " + applicationId + "";
return Response.status(Response.Status.OK).entity(responseMsg).build(); return Response.status(Response.Status.OK).entity(responseMsg).build();
} catch (NotFoundException e) {
String msg = "Couldn't found application release which is having application id: " + applicationId
+ " and application release UUID:" + releaseUuid;
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (ForbiddenException e) {
String msg =
"You don't have require permission to delete the application release which has UUID " + releaseUuid
+ " and application ID " + applicationId;
log.error(msg, e);
return Response.status(Response.Status.FORBIDDEN).entity(msg).build();
}catch (ApplicationManagementException e) { }catch (ApplicationManagementException e) {
String msg = "Error occurred while deleting the application: " + applicationId; String msg = "Error occurred while deleting the application: " + applicationId;
log.error(msg, e); log.error(msg, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (ApplicationStorageManagementException e) { } catch (ApplicationStorageManagementException e) {
String msg = "Error occurred while deleting the application storage: " + applicationId; String msg = "Error occurred while deleting the application storage: " + applicationId;
log.error(msg, e); log.error(msg, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
@ -549,15 +491,16 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
public Response getLifecycleState( public Response getLifecycleState(
@PathParam("appId") int applicationId, @PathParam("appId") int applicationId,
@PathParam("uuid") String applicationUuid) { @PathParam("uuid") String applicationUuid) {
LifecycleState lifecycleState; LifecycleStateDTO lifecycleState;
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
try { try {
lifecycleState = applicationManager.getLifecycleState(applicationId, applicationUuid); lifecycleState = applicationManager.getLifecycleState(applicationId, applicationUuid);
} catch (NotFoundException e) { if (lifecycleState == null) {
String msg = "Couldn't found application lifecycle details for appid: " + applicationId String msg = "Couldn't found application lifecycle details for appid: " + applicationId
+ " and app release UUID: " + applicationUuid; + " and app release UUID: " + applicationUuid;
log.error(msg, e); log.error(msg);
return Response.status(Response.Status.NOT_FOUND).build(); return Response.status(Response.Status.NOT_FOUND).build();
}
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
String msg = "Error occurred while getting lifecycle state."; String msg = "Error occurred while getting lifecycle state.";
log.error(msg, e); log.error(msg, e);
@ -579,7 +522,7 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
log.error(msg); log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).build(); return Response.status(Response.Status.BAD_REQUEST).build();
} }
LifecycleState state = new LifecycleState(); LifecycleStateDTO state = new LifecycleStateDTO();
state.setCurrentState(action); state.setCurrentState(action);
applicationManager.changeLifecycleState(applicationId, applicationUuid, state); applicationManager.changeLifecycleState(applicationId, applicationUuid, state);
} catch (NotFoundException e) { } catch (NotFoundException e) {
@ -595,60 +538,112 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
return Response.status(Response.Status.CREATED).entity("Lifecycle state added successfully.").build(); return Response.status(Response.Status.CREATED).entity("Lifecycle state added successfully.").build();
} }
private boolean isValidAppCreatingRequest(Attachment iconFile, Attachment bannerFile, /***
List<Attachment> attachmentList, Application application) { *
* @param binaryFile binary file of the application release
// if (application.getApplicationReleases().size() > 1) { * @param iconFile icon file of the application release
// log.error("Invalid application creating request. Application creating request must have single application " * @param bannerFile banner file of the application release
// + "release. Application name:" + application.getName() + " and type: " + application.getType()); * @param attachmentList list of screenshot of the application release
// return false; * @return {@link ApplicationArtifact}
// } * @throws ApplicationManagementException if an error occurs when reading the attached data.
*/
if (iconFile == null) { private ApplicationArtifact constructApplicationArtifact(Attachment binaryFile, Attachment iconFile,
log.error("Icon file is not found for the application release. Application name: " + application.getName() Attachment bannerFile, List<Attachment> attachmentList) throws ApplicationManagementException {
+ " and type: " + application.getType()); try {
return false; ApplicationArtifact applicationArtifact = new ApplicationArtifact();
DataHandler dataHandler;
if (binaryFile != null) {
dataHandler = binaryFile.getDataHandler();
InputStream installerStream = dataHandler.getInputStream();
String installerFileName = dataHandler.getName();
if (installerStream == null) {
String msg = "Stream of the application release installer is null. Hence can't proceed. Please "
+ "verify the installer file.";
log.error(msg);
throw new BadRequestException(msg);
}
if (installerFileName == null) {
String msg = "Installer file name retrieving is failed.. Hence can't proceed. Please verify the "
+ "installer file.";
log.error(msg);
throw new BadRequestException(msg);
}
applicationArtifact.setInstallerName(installerFileName);
applicationArtifact.setInstallerStream(installerStream);
} }
if (bannerFile == null) { if (iconFile != null) {
log.error("Banner file is not found for the application release. Application name: " + application.getName() dataHandler = iconFile.getDataHandler();
+ " and application type: " + application.getType()); String iconFileName = dataHandler.getName();
return false; InputStream iconStream = dataHandler.getInputStream();
if (iconStream == null) {
String msg = "Stream of the application release icon is null. Hence can't proceed. Please "
+ "verify the uploaded icon file.";
log.error(msg);
throw new BadRequestException(msg);
}
if (iconFileName == null) {
String msg = "Icon file name retrieving is failed.. Hence can't proceed. Please verify the "
+ "icon file.";
log.error(msg);
throw new BadRequestException(msg);
}
applicationArtifact.setIconName(iconFileName);
applicationArtifact.setIconStream(iconStream);
} }
if (attachmentList == null || attachmentList.isEmpty()) { if (bannerFile != null) {
log.error( dataHandler = bannerFile.getDataHandler();
"Screenshots are not found for the application release. Application name: " + application.getName() String bannerFileName = dataHandler.getName();
+ " Application type: " + application.getType()); InputStream bannerStream = dataHandler.getInputStream();
return false; if (bannerStream == null) {
String msg = "Stream of the application release banner is null. Hence can't proceed. Please "
+ "verify the uploaded banner file.";
log.error(msg);
throw new BadRequestException(msg);
}
if (bannerFileName == null) {
String msg = "Banner file name retrieving is failed.. Hence can't proceed. Please verify the "
+ "banner file.";
log.error(msg);
throw new BadRequestException(msg);
}
applicationArtifact.setBannerName(bannerFileName);
applicationArtifact.setBannerStream(bannerStream);
} }
return true; if (attachmentList != null) {
Map<String, InputStream> scrrenshotData = new HashMap<>();
for (Attachment sc : attachmentList) {
dataHandler = sc.getDataHandler();
String screenshotrFileName = dataHandler.getName();
InputStream screenshotStream = dataHandler.getInputStream();
if (screenshotStream == null) {
String msg =
"Stream of one of the application release screenshot is null. Hence can't proceed. Please "
+ "verify the uploaded screenshots.";
log.error(msg);
throw new BadRequestException(msg);
}
if (screenshotrFileName == null) {
String msg =
"Screenshot file name retrieving is failed for one screenshot. Hence can't proceed. "
+ "Please verify the screenshots.";
log.error(msg);
throw new BadRequestException(msg);
}
scrrenshotData.put(screenshotrFileName, screenshotStream);
}
applicationArtifact.setScreenshots(scrrenshotData);
}
return applicationArtifact;
} catch (IOException e) {
String msg = "Error occurred when reading attachment data.";
log.error(msg, e);
throw new ApplicationManagementException(msg);
} }
private boolean isValidReleaseCreatingRequest(Attachment binaryFile, Attachment iconFile, Attachment bannerFile,
List<Attachment> attachmentList, String appType) {
if (iconFile == null) {
log.error("Icon file is not found with the application release creating request.");
return false;
} }
if (bannerFile == null) {
log.error("Banner file is not found with the application release creating request.");
return false;
}
if (attachmentList == null || attachmentList.isEmpty()) {
log.error("Screenshots are not found with the application release creating request.");
return false;
}
if (binaryFile == null && ApplicationType.ENTERPRISE.toString().equals(appType)) {
log.error("Binary file is not found with the application release creating request. Application type: "
+ appType);
return false;
}
return true;
}
} }

View File

@ -30,7 +30,7 @@
<PermissionConfiguration> <PermissionConfiguration>
<APIVersion></APIVersion> <APIVersion></APIVersion>
<!-- Application related permissions --> <!-- ApplicationDTO related permissions -->
<Permission> <Permission>
<name>Get Application Details</name> <name>Get Application Details</name>
<path>/device-mgt/application/get</path> <path>/device-mgt/application/get</path>

View File

@ -10,13 +10,16 @@
}, },
"license": "Apache License 2.0", "license": "Apache License 2.0",
"dependencies": { "dependencies": {
"acorn": "^6.1.1",
"antd": "^3.15.0", "antd": "^3.15.0",
"axios": "^0.18.0",
"react": "^16.8.4", "react": "^16.8.4",
"react-dom": "^16.8.4", "react-dom": "^16.8.4",
"react-highlight-words": "^0.16.0", "react-highlight-words": "^0.16.0",
"react-router-config": "^5.0.0", "react-router-config": "^5.0.0",
"react-router-dom": "latest", "react-router-dom": "latest",
"react-scripts": "2.1.8" "react-scripts": "2.1.8",
"react-router": "latest"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.0.0", "@babel/core": "^7.0.0",
@ -48,6 +51,7 @@
"react": "^15.6.2", "react": "^15.6.2",
"react-dom": "^15.6.2", "react-dom": "^15.6.2",
"react-intl": "^2.4.0", "react-intl": "^2.4.0",
"react-redux": "^7.0.2",
"redux": "^4.0.1", "redux": "^4.0.1",
"sass-loader": "^6.0.7", "sass-loader": "^6.0.7",
"style-loader": "^0.18.2", "style-loader": "^0.18.2",

View File

@ -1841,7 +1841,7 @@ c29.2568 87.7715 113.371 149.942 212.114 149.942z" />
d="M512 411.429v-413.257h-512v413.257h512zM138.972 257.828h175.543v87.7715h-175.543v-87.7715zM318.172 213.942h-175.543v-65.8281h175.543v65.8281zM142.629 42.0576h175.543v65.8281h-175.543v-65.8281zM43.8857 345.6v-87.7715h54.8574v87.7715h-54.8574z d="M512 411.429v-413.257h-512v413.257h512zM138.972 257.828h175.543v87.7715h-175.543v-87.7715zM318.172 213.942h-175.543v-65.8281h175.543v65.8281zM142.629 42.0576h175.543v65.8281h-175.543v-65.8281zM43.8857 345.6v-87.7715h54.8574v87.7715h-54.8574z
M362.058 257.828h106.057v87.7715h-106.057v-87.7715zM95.0859 148.114v65.8281h-54.8574v-65.8281h54.8574zM362.058 148.114h106.057v65.8281h-106.057v-65.8281zM43.8857 104.229v-65.8281h54.8574v65.8281h-54.8574zM468.114 104.229h-106.057v-65.8281h106.057v65.8281 M362.058 257.828h106.057v87.7715h-106.057v-87.7715zM95.0859 148.114v65.8281h-54.8574v-65.8281h54.8574zM362.058 148.114h106.057v65.8281h-106.057v-65.8281zM43.8857 104.229v-65.8281h54.8574v65.8281h-54.8574zM468.114 104.229h-106.057v-65.8281h106.057v65.8281
z" /> z" />
<glyph glyph-name="tag" unicode="&#xe67a;" <glyph glyph-name="tagDTO" unicode="&#xe67a;"
d="M336.724 352.915l175.542 -179.201l-171.886 -182.856l-193.828 182.856l-32.916 128l32.916 36.5723c-7.31543 3.65625 -10.9717 3.65625 -14.6299 3.65625c-10.9707 -3.65625 -25.5986 -10.9717 -32.9131 -18.2861 d="M336.724 352.915l175.542 -179.201l-171.886 -182.856l-193.828 182.856l-32.916 128l32.916 36.5723c-7.31543 3.65625 -10.9717 3.65625 -14.6299 3.65625c-10.9707 -3.65625 -25.5986 -10.9717 -32.9131 -18.2861
c-10.9707 -14.627 -10.9707 -29.2568 -10.9707 -47.542c0 -18.2861 3.65625 -36.5723 7.3125 -54.8574c0 0 21.9443 -80.458 -40.2275 -87.7705c-62.1719 0 -54.8574 87.7705 -54.8574 87.7705v25.6006v7.31445c0 14.627 3.65625 29.2568 10.9707 43.8857 c-10.9707 -14.627 -10.9707 -29.2568 -10.9707 -47.542c0 -18.2861 3.65625 -36.5723 7.3125 -54.8574c0 0 21.9443 -80.458 -40.2275 -87.7705c-62.1719 0 -54.8574 87.7705 -54.8574 87.7705v25.6006v7.31445c0 14.627 3.65625 29.2568 10.9707 43.8857
c21.9443 62.1699 91.4287 84.1143 128 73.1436c10.9717 0 21.9443 -3.65918 29.2568 -7.31543l25.6006 25.6006zM62.4375 250.514c-3.29199 27.4287 5.85059 73.5088 9.87305 79.7275c-32.1807 -25.6006 -42.7881 -61.4424 -46.4443 -72.4131 c21.9443 62.1699 91.4287 84.1143 128 73.1436c10.9717 0 21.9443 -3.65918 29.2568 -7.31543l25.6006 25.6006zM62.4375 250.514c-3.29199 27.4287 5.85059 73.5088 9.87305 79.7275c-32.1807 -25.6006 -42.7881 -61.4424 -46.4443 -72.4131

Before

Width:  |  Height:  |  Size: 443 KiB

After

Width:  |  Height:  |  Size: 443 KiB

View File

@ -31,3 +31,7 @@
transform: rotate(360deg); transform: rotate(360deg);
} }
} }
.ant-upload.ant-upload-drag {
height: 170px;
}

View File

@ -7,33 +7,37 @@ import Dashboard from "./pages/dashboard/Dashboard";
import Apps from "./pages/dashboard/apps/Apps"; import Apps from "./pages/dashboard/apps/Apps";
import AddNewApp from "./pages/dashboard/add-new-app/AddNewApp"; import AddNewApp from "./pages/dashboard/add-new-app/AddNewApp";
import './index.css'; import './index.css';
import store from "./js/store/index";
import {Provider} from "react-redux";
const routes = [ const routes = [
{ {
path: '/publisher/Login', path: '/publisher/login',
component: Login component: Login
}, },
{ {
path: '/publisher/dashboard', path: '/publisher',
component: Dashboard, component: Dashboard,
routes: [ routes: [
{ {
path: '/publisher/dashboard/apps', path: '/publisher/apps',
component: Apps component: Apps
}, },
{ {
path: '/publisher/dashboard/new-app', path: '/publisher/new-app',
component: AddNewApp component: AddNewApp
} }
] ]
} }
] ];
ReactDOM.render(
ReactDOM.render( <App routes={routes}/>, document.getElementById('root')); <Provider store={store}>
<App routes={routes}/>
</Provider>,
document.getElementById('root'));
// If you want your app to work offline and load faster, you can change // If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls. // unregister() to register() below. Note this comes with some pitfalls.

View File

@ -0,0 +1,9 @@
const initialState = {
};
function rootReducer(state = initialState, action) {
return state;
}
export default rootReducer;

View File

@ -0,0 +1,4 @@
import { createStore } from "redux";
import rootReducer from "../reducers/index";
const store = createStore(rootReducer);
export default store;

View File

@ -1,7 +1,10 @@
import React from "react"; import React from "react";
import {Typography, Row, Col, Form, Icon, Input, Button, Checkbox,} from 'antd'; import {Typography, Row, Col, Form, Icon, Input, Button, Checkbox} from 'antd';
import styles from './Login.less'; import styles from './Login.less';
import axios from 'axios';
const {Title} = Typography; const {Title} = Typography;
const {Text} = Typography;
class Login extends React.Component { class Login extends React.Component {
render() { render() {
@ -33,33 +36,77 @@ class Login extends React.Component {
} }
class NormalLoginForm extends React.Component { class NormalLoginForm extends React.Component {
constructor(props) {
super(props);
this.state = {
inValid: false,
loading : false
};
}
handleSubmit = (e) => { handleSubmit = (e) => {
const thisForm = this;
e.preventDefault(); e.preventDefault();
this.props.form.validateFields((err, values) => { this.props.form.validateFields((err, values) => {
thisForm.setState({
inValid: false
});
if (!err) { if (!err) {
thisForm.setState({
loading: true
});
console.log('Received values of form: ', values); console.log('Received values of form: ', values);
let data = "username=" + values.username + "&password=" + values.password + "&platform=publisher";
axios.post('https://localhost:9443/api/application-mgt-handler/v1.0/login', data
).then(res => {
if (res.status === 200) {
window.location = res.data.url;
}
}).catch(function (error) {
if (error.response.status === 400) {
thisForm.setState({
inValid: true,
loading: false
});
} }
}); });
} }
});
};
render() { render() {
const {getFieldDecorator} = this.props.form; const {getFieldDecorator} = this.props.form;
let errorMsg = "";
if (this.state.inValid) {
errorMsg = <Text type="danger">Invalid Login Details</Text>;
}
let loading = "";
if (this.state.loading) {
loading = <Text type="secondary">Loading..</Text>;
}
return ( return (
<Form onSubmit={this.handleSubmit} className="login-form"> <Form onSubmit={this.handleSubmit} className="login-form">
<Form.Item> <Form.Item>
{getFieldDecorator('userName', { {getFieldDecorator('username', {
rules: [{required: true, message: 'Please input your username!'}], rules: [{required: true, message: 'Please input your username!'}],
})( })(
<Input style={{height: 32}} prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="Username" /> <Input style={{height: 32}} prefix={<Icon type="user" style={{color: 'rgba(0,0,0,.25)'}}/>}
placeholder="Username"/>
)} )}
</Form.Item> </Form.Item>
<Form.Item> <Form.Item>
{getFieldDecorator('password', { {getFieldDecorator('password', {
rules: [{required: true, message: 'Please input your Password!'}], rules: [{required: true, message: 'Please input your Password!'}],
})( })(
<Input style={{height: 32}} className={styles.input} prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="Password" /> <Input style={{height: 32}} className={styles.input}
prefix={<Icon type="lock" style={{color: 'rgba(0,0,0,.25)'}}/>} type="password"
placeholder="Password"/>
)} )}
</Form.Item> </Form.Item>
{loading}
{errorMsg}
<Form.Item> <Form.Item>
{getFieldDecorator('remember', { {getFieldDecorator('remember', {
valuePropName: 'checked', valuePropName: 'checked',
@ -67,11 +114,11 @@ class NormalLoginForm extends React.Component {
})( })(
<Checkbox>Remember me</Checkbox> <Checkbox>Remember me</Checkbox>
)} )}
<br/>
<a className="login-form-forgot" href="">Forgot password</a> <a className="login-form-forgot" href="">Forgot password</a>
<Button block type="primary" htmlType="submit" className="login-form-button"> <Button block type="primary" htmlType="submit" className="login-form-button">
Log in Log in
</Button> </Button>
Or <a href="">register now!</a>
</Form.Item> </Form.Item>
</Form> </Form>
); );

View File

@ -7,6 +7,7 @@ import styles from './Dashboard.less';
import Logo from "../../../public/images/logo.svg"; import Logo from "../../../public/images/logo.svg";
import {Link, NavLink} from "react-router-dom"; import {Link, NavLink} from "react-router-dom";
import RouteWithSubRoutes from "../../components/RouteWithSubRoutes" import RouteWithSubRoutes from "../../components/RouteWithSubRoutes"
import { Switch, Redirect } from 'react-router'
class Dashboard extends React.Component { class Dashboard extends React.Component {
@ -36,10 +37,14 @@ class Dashboard extends React.Component {
</Menu> </Menu>
</Header> </Header>
<Content style={{padding: '0 0'}}> <Content style={{padding: '0 0'}}>
<Switch>
<Redirect exact from="/publisher" to="/publisher/apps"/>
{this.state.routes.map((route) => ( {this.state.routes.map((route) => (
<RouteWithSubRoutes key={route.path} {...route} /> <RouteWithSubRoutes key={route.path} {...route} />
))} ))}
</Switch>
</Content> </Content>
<Footer style={{textAlign: 'center'}}> <Footer style={{textAlign: 'center'}}>
©2019 entgra.io ©2019 entgra.io

View File

@ -1,12 +1,33 @@
import React from "react"; import React from "react";
import "antd/dist/antd.css"; import "antd/dist/antd.css";
import {PageHeader, Typography, Card, Steps, Button, message, Row, Col} from "antd"; import {
import Step1 from "./Step1" PageHeader,
import Step2 from "./Step2" Typography,
import Step3 from "./Step3" Card,
Steps,
Button,
message,
Row,
Col,
Tag,
Tooltip,
Input,
Icon,
Select,
Switch,
Form,
Upload,
Divider
} from "antd";
import Step1 from "./Step1";
import Step2 from "./Step2";
import Step3 from "./Step3";
import styles from "./Style.less";
import IconImage from "./IconImg";
import UploadScreenshots from "./UploadScreenshots";
const Paragraph = Typography; const Paragraph = Typography;
const Dragger = Upload.Dragger;
const routes = [ const routes = [
{ {
path: 'index', path: 'index',
@ -22,6 +43,23 @@ const routes = [
}, },
]; ];
const props = {
name: 'file',
multiple: false,
action: '//jsonplaceholder.typicode.com/posts/',
onChange(info) {
const status = info.file.status;
if (status !== 'uploading') {
console.log(info.file, info.fileList);
}
if (status === 'done') {
message.success(`${info.file.name} file uploaded successfully.`);
} else if (status === 'error') {
message.error(`${info.file.name} file upload failed.`);
}
},
};
const Step = Steps.Step; const Step = Steps.Step;
const steps = [{ const steps = [{
@ -36,6 +74,96 @@ const steps = [{
}]; }];
const {Option} = Select;
const {TextArea} = Input;
const InputGroup = Input.Group;
const formItemLayout = {
labelCol: {
span: 4,
},
wrapperCol: {
span: 20,
},
};
class EditableTagGroup extends React.Component {
state = {
tags: [],
inputVisible: false,
inputValue: '',
};
handleClose = (removedTag) => {
const tags = this.state.tags.filter(tag => tag !== removedTag);
console.log(tags);
this.setState({tags});
}
showInput = () => {
this.setState({inputVisible: true}, () => this.input.focus());
}
handleInputChange = (e) => {
this.setState({inputValue: e.target.value});
}
handleInputConfirm = () => {
const {inputValue} = this.state;
let {tags} = this.state;
if (inputValue && tags.indexOf(inputValue) === -1) {
tags = [...tags, inputValue];
}
console.log(tags);
this.setState({
tags,
inputVisible: false,
inputValue: '',
});
}
saveInputRef = input => this.input = input
render() {
const {tags, inputVisible, inputValue} = this.state;
return (
<div>
{tags.map((tag, index) => {
const isLongTag = tag.length > 20;
const tagElem = (
<Tag key={tag} closable={index !== 0} onClose={() => this.handleClose(tag)}>
{isLongTag ? `${tag.slice(0, 20)}...` : tag}
</Tag>
);
return isLongTag ? <Tooltip title={tag} key={tag}>{tagElem}</Tooltip> : tagElem;
})}
{inputVisible && (
<Input
ref={this.saveInputRef}
type="text"
size="small"
style={{width: 78}}
value={inputValue}
onChange={this.handleInputChange}
onBlur={this.handleInputConfirm}
onPressEnter={this.handleInputConfirm}
/>
)}
{!inputVisible && (
<Tag
onClick={this.showInput}
style={{background: '#fff', borderStyle: 'dashed'}}
>
<Icon type="plus"/> New Tag
</Tag>
)}
</div>
);
}
}
class AddNewApp extends React.Component { class AddNewApp extends React.Component {
constructor(props) { constructor(props) {
@ -45,6 +173,12 @@ class AddNewApp extends React.Component {
}; };
} }
tags = [];
addTag(key, value){
this.tags.push(<Option key={key}>{value}</Option>);
}
next() { next() {
const current = this.state.current + 1; const current = this.state.current + 1;
this.setState({current}); this.setState({current});
@ -59,6 +193,8 @@ class AddNewApp extends React.Component {
render() { render() {
const {current} = this.state; const {current} = this.state;
const Content = steps[current].content; const Content = steps[current].content;
this.addTag('1','Lorem');
this.addTag('2','Ipsum');
return ( return (
<div> <div>
<PageHeader <PageHeader
@ -75,33 +211,116 @@ class AddNewApp extends React.Component {
</PageHeader> </PageHeader>
<div style={{background: '#f0f2f5', padding: 24, minHeight: 720}}> <div style={{background: '#f0f2f5', padding: 24, minHeight: 720}}>
<Row> <Row>
<Col span={16} offset={4}> <Col span={20} offset={2}>
<Card> <Card>
<Row>
<Col span={12}>
<div> <div>
<Steps current={current}> <Form labelAlign="left" layout="horizontal" className={styles.stepForm}
{steps.map(item => <Step key={item.title} title={item.title}/>)} hideRequiredMark>
</Steps> <Form.Item {...formItemLayout} label="Platform">
<Content/> <Select placeholder="ex: android">
<div className="steps-action"> <Option value="Android">Android</Option>
{ <Option value="iOS">iOS</Option>
current < steps.length - 1 </Select>
&& <Button type="primary" onClick={() => this.next()}>Next</Button> </Form.Item>
} <Form.Item {...formItemLayout} label="Type">
{ <Select value="Enterprise">
current === steps.length - 1 <Option value="Enterprise" selected>Enterprise</Option>
&& <Button type="primary" </Select>
onClick={() => message.success('Processing complete!')}>Done</Button> </Form.Item>
} <Form.Item {...formItemLayout} label="App Name">
{ <Input placeholder="ex: Lorem App"/>
current > 0 </Form.Item>
&& ( <Form.Item {...formItemLayout} label="Description">
<Button style={{marginLeft: 8}} onClick={() => this.prev()}> <TextArea placeholder="Enter the description..." rows={7}/>
Previous </Form.Item>
</Button> <Form.Item {...formItemLayout} label="Category">
) <Select placeholder="Select a category">
} <Option value="travel">Travel</Option>
<Option value="entertainment">Entertainment</Option>
</Select>
</Form.Item>
<Form.Item {...formItemLayout} label="Price">
<Input prefix="$" placeholder="00.00"/>
</Form.Item>
<Form.Item {...formItemLayout} label="Is Sahred?">
<Switch checkedChildren={<Icon type="check" />} unCheckedChildren={<Icon type="close" />} defaultChecked />
</Form.Item>
<Divider/>
<Form.Item {...formItemLayout} label="Tags">
<InputGroup>
<Row gutter={8}>
<Col span={22}>
<Select
mode="multiple"
style={{ width: '100%' }}
placeholder="Tags Mode"
>
{this.tags}
</Select>
</Col>
<Col span={2}>
<Button type="dashed" shape="circle" icon="plus"/>
</Col>
</Row>
</InputGroup>
</Form.Item>
<Form.Item {...formItemLayout} label="Meta Daa">
<InputGroup>
<Row gutter={8}>
<Col span={10}>
<Input placeholder="Key"/>
</Col>
<Col span={12}>
<Input placeholder="value"/>
</Col>
<Col span={2}>
<Button type="dashed" shape="circle" icon="plus"/>
</Col>
</Row>
</InputGroup>
</Form.Item>
</Form>
</div> </div>
</Col>
<Col span={12} style={{paddingTop: 40, paddingLeft: 20}}>
<p>Application</p>
<div style={{height: 170}}>
<Dragger {...props}>
<p className="ant-upload-drag-icon">
<Icon type="inbox"/>
</p>
<p className="ant-upload-text">Click or drag file to this area to
upload</p>
<p className="ant-upload-hint">Support for a single or bulk upload.
Strictly prohibit from uploading company data or other band
files</p>
</Dragger>
</div> </div>
<Row style={{marginTop: 40}}>
<Col span={12}>
<p>Icon</p>
<IconImage/>
</Col>
<Col span={12}>
<p>Banner</p>
<IconImage/>
</Col>
</Row>
<Row style={{marginTop: 40}}>
<Col span={24}>
<p>Screenshots</p>
<UploadScreenshots/>
</Col>
</Row>
</Col>
</Row>
</Card> </Card>
</Col> </Col>
</Row> </Row>

View File

@ -0,0 +1,66 @@
import React from "react";
import { Upload, Icon, message } from 'antd';
function getBase64(img, callback) {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result));
reader.readAsDataURL(img);
}
function beforeUpload(file) {
const isJPG = file.type === 'image/jpeg';
if (!isJPG) {
message.error('You can only upload JPG file!');
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('Image must smaller than 2MB!');
}
return isJPG && isLt2M;
}
class IconImage extends React.Component {
state = {
loading: false,
};
handleChange = (info) => {
if (info.file.status === 'uploading') {
this.setState({ loading: true });
return;
}
if (info.file.status === 'done') {
// Get this url from response in real world.
getBase64(info.file.originFileObj, imageUrl => this.setState({
imageUrl,
loading: false,
}));
}
}
render() {
const uploadButton = (
<div>
<Icon type={this.state.loading ? 'loading' : 'plus'} />
<div className="ant-upload-text">Upload</div>
</div>
);
const imageUrl = this.state.imageUrl;
return (
<Upload
name="avatar"
listType="picture-card"
className="avatar-uploader"
showUploadList={false}
action="//jsonplaceholder.typicode.com/posts/"
beforeUpload={beforeUpload}
onChange={this.handleChange}
>
{imageUrl ? <img src={imageUrl} alt="avatar" /> : uploadButton}
</Upload>
);
}
}
export default IconImage;

View File

@ -0,0 +1,49 @@
import React from "react";
import { Upload, Icon, Modal} from 'antd';
class UploadScreenshots extends React.Component {
state = {
previewVisible: false,
previewImage: '',
fileList: [],
};
handleCancel = () => this.setState({ previewVisible: false });
handlePreview = (file) => {
this.setState({
previewImage: file.url || file.thumbUrl,
previewVisible: true,
});
};
handleChange = ({ fileList }) => this.setState({ fileList });
render() {
const { previewVisible, previewImage, fileList } = this.state;
const uploadButton = (
<div>
<Icon type="plus" />
<div className="ant-upload-text">Upload</div>
</div>
);
return (
<div className="clearfix">
<Upload
action="//jsonplaceholder.typicode.com/posts/"
listType="picture-card"
fileList={fileList}
onPreview={this.handlePreview}
onChange={this.handleChange}
>
{fileList.length >= 3 ? null : uploadButton}
</Upload>
<Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
<img alt="example" style={{ width: '100%' }} src={previewImage} />
</Modal>
</div>
);
}
}
export default UploadScreenshots;

View File

@ -0,0 +1,49 @@
import React from "react";
import { Upload, Icon, Modal} from 'antd';
class AddTagModal extends React.Component {
state = {
previewVisible: false,
previewImage: '',
fileList: [],
};
handleCancel = () => this.setState({ previewVisible: false });
handlePreview = (file) => {
this.setState({
previewImage: file.url || file.thumbUrl,
previewVisible: true,
});
};
handleChange = ({ fileList }) => this.setState({ fileList });
render() {
const { previewVisible, previewImage, fileList } = this.state;
const uploadButton = (
<div>
<Icon type="plus" />
<div className="ant-upload-text">Upload</div>
</div>
);
return (
<div className="clearfix">
<Upload
action="//jsonplaceholder.typicode.com/posts/"
listType="picture-card"
fileList={fileList}
onPreview={this.handlePreview}
onChange={this.handleChange}
>
{fileList.length >= 3 ? null : uploadButton}
</Upload>
<Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
<img alt="example" style={{ width: '100%' }} src={previewImage} />
</Modal>
</div>
);
}
}
export default AddTagModal;

View File

@ -31,7 +31,7 @@ import io.swagger.annotations.Tag;
import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes; import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.application.mgt.common.ErrorResponse; import org.wso2.carbon.device.application.mgt.common.ErrorResponse;
import org.wso2.carbon.device.application.mgt.common.Application; import org.wso2.carbon.device.application.mgt.common.dto.ApplicationDTO;
import org.wso2.carbon.device.application.mgt.common.ApplicationList; import org.wso2.carbon.device.application.mgt.common.ApplicationList;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
@ -49,7 +49,7 @@ import javax.ws.rs.core.Response;
@SwaggerDefinition( @SwaggerDefinition(
info = @Info( info = @Info(
version = "1.0.0", version = "1.0.0",
title = "Application Storage Management Service", title = "ApplicationDTO Storage Management Service",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = "name", value = "ApplicationStorageManagementService"), @ExtensionProperty(name = "name", value = "ApplicationStorageManagementService"),
@ -58,14 +58,14 @@ import javax.ws.rs.core.Response;
} }
), ),
tags = { tags = {
@Tag(name = "application_management, device_management", description = "Application Storage Management " @Tag(name = "application_management, device_management", description = "ApplicationDTO Storage Management "
+ "related APIs") + "related APIs")
} }
) )
@Scopes( @Scopes(
scopes = { scopes = {
@Scope( @Scope(
name = "Get Application Details", name = "Get ApplicationDTO Details",
description = "Get application details", description = "Get application details",
key = "perm:app:store:view", key = "perm:app:store:view",
permissions = {"/device-mgt/application/get"} permissions = {"/device-mgt/application/get"}
@ -73,7 +73,7 @@ import javax.ws.rs.core.Response;
} }
) )
@Path("/store/applications") @Path("/store/applications")
@Api(value = "Application Management", description = "This API carries all app store management related operations " + @Api(value = "ApplicationDTO Management", description = "This API carries all app store management related operations " +
"such as get all the applications etc.") "such as get all the applications etc.")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public interface ApplicationManagementAPI { public interface ApplicationManagementAPI {
@ -89,7 +89,7 @@ public interface ApplicationManagementAPI {
httpMethod = "GET", httpMethod = "GET",
value = "get all applications", value = "get all applications",
notes = "This will get all applications", notes = "This will get all applications",
tags = "Application Management", tags = "ApplicationDTO Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:get") @ExtensionProperty(name = SCOPE, value = "perm:application:get")
@ -121,7 +121,7 @@ public interface ApplicationManagementAPI {
@QueryParam("type") String appType, @QueryParam("type") String appType,
@ApiParam( @ApiParam(
name = "category", name = "category",
value = "Category of the application") value = "CategoryDTO of the application")
@QueryParam("category") String appCategory, @QueryParam("category") String appCategory,
@ApiParam( @ApiParam(
name = "exact-match", name = "exact-match",
@ -152,7 +152,7 @@ public interface ApplicationManagementAPI {
httpMethod = "GET", httpMethod = "GET",
value = "get the application of requesting application type", value = "get the application of requesting application type",
notes = "This will get the application identified by the application type and name, if exists", notes = "This will get the application identified by the application type and name, if exists",
tags = "Application Management", tags = "ApplicationDTO Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:get") @ExtensionProperty(name = SCOPE, value = "perm:application:get")
@ -164,10 +164,10 @@ public interface ApplicationManagementAPI {
@ApiResponse( @ApiResponse(
code = 200, code = 200,
message = "OK. \n Successfully retrieved relevant application.", message = "OK. \n Successfully retrieved relevant application.",
response = Application.class), response = ApplicationDTO.class),
@ApiResponse( @ApiResponse(
code = 404, code = 404,
message = "Application not found"), message = "ApplicationDTO not found"),
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server Error. \n Error occurred while getting relevant application.", message = "Internal Server Error. \n Error occurred while getting relevant application.",

View File

@ -28,7 +28,7 @@ import io.swagger.annotations.Info;
import io.swagger.annotations.SwaggerDefinition; import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Tag; import io.swagger.annotations.Tag;
import org.wso2.carbon.apimgt.annotations.api.Scopes; import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.application.mgt.common.Application; import org.wso2.carbon.device.application.mgt.common.dto.ApplicationDTO;
import org.wso2.carbon.device.application.mgt.common.ApplicationInstallResponse; import org.wso2.carbon.device.application.mgt.common.ApplicationInstallResponse;
import org.wso2.carbon.device.application.mgt.common.EnterpriseInstallationDetails; import org.wso2.carbon.device.application.mgt.common.EnterpriseInstallationDetails;
import org.wso2.carbon.device.application.mgt.common.InstallationDetails; import org.wso2.carbon.device.application.mgt.common.InstallationDetails;
@ -65,13 +65,13 @@ import javax.ws.rs.core.Response;
@Scopes( @Scopes(
scopes = { scopes = {
@org.wso2.carbon.apimgt.annotations.api.Scope( @org.wso2.carbon.apimgt.annotations.api.Scope(
name = "Install an Application", name = "Install an ApplicationDTO",
description = "Install an application", description = "Install an application",
key = "perm:subscription:install", key = "perm:subscription:install",
permissions = {"/device-mgt/subscription/install"} permissions = {"/device-mgt/subscription/install"}
), ),
@org.wso2.carbon.apimgt.annotations.api.Scope( @org.wso2.carbon.apimgt.annotations.api.Scope(
name = "Install an Application", name = "Install an ApplicationDTO",
description = "Install an application", description = "Install an application",
key = "perm:application-mgt:login", key = "perm:application-mgt:login",
permissions = {"/device-mgt/application-mgt/login"} permissions = {"/device-mgt/application-mgt/login"}
@ -117,7 +117,7 @@ public interface SubscriptionManagementAPI {
), ),
@ApiResponse( @ApiResponse(
code = 404, code = 404,
message = "Not Found. \n Application cannot be found to install." message = "Not Found. \n ApplicationDTO cannot be found to install."
), ),
@ApiResponse( @ApiResponse(
code = 500, code = 500,
@ -162,7 +162,7 @@ public interface SubscriptionManagementAPI {
), ),
@ApiResponse( @ApiResponse(
code = 404, code = 404,
message = "Not Found. \n Application cannot be found to install." message = "Not Found. \n ApplicationDTO cannot be found to install."
), ),
@ApiResponse( @ApiResponse(
code = 500, code = 500,
@ -198,7 +198,7 @@ public interface SubscriptionManagementAPI {
@ApiResponse( @ApiResponse(
code = 200, code = 200,
message = "OK. \n Successfully uninstalled the application.", message = "OK. \n Successfully uninstalled the application.",
response = Application.class response = ApplicationDTO.class
), ),
@ApiResponse( @ApiResponse(
code = 304, code = 304,
@ -206,7 +206,7 @@ public interface SubscriptionManagementAPI {
), ),
@ApiResponse( @ApiResponse(
code = 404, code = 404,
message = "Not Found. \n Application cannot be found to uninstall." message = "Not Found. \n ApplicationDTO cannot be found to uninstall."
), ),
@ApiResponse( @ApiResponse(
code = 500, code = 500,
@ -242,7 +242,7 @@ public interface SubscriptionManagementAPI {
@ApiResponse( @ApiResponse(
code = 200, code = 200,
message = "OK. \n Successfully uninstalled the application.", message = "OK. \n Successfully uninstalled the application.",
response = Application.class response = ApplicationDTO.class
), ),
@ApiResponse( @ApiResponse(
code = 304, code = 304,
@ -250,7 +250,7 @@ public interface SubscriptionManagementAPI {
), ),
@ApiResponse( @ApiResponse(
code = 404, code = 404,
message = "Not Found. \n Application cannot be found to uninstall." message = "Not Found. \n ApplicationDTO cannot be found to uninstall."
), ),
@ApiResponse( @ApiResponse(
code = 500, code = 500,
@ -287,7 +287,7 @@ public interface SubscriptionManagementAPI {
@ApiResponse( @ApiResponse(
code = 200, code = 200,
message = "OK. \n Successfully installed the application.", message = "OK. \n Successfully installed the application.",
response = Application.class response = ApplicationDTO.class
), ),
@ApiResponse( @ApiResponse(
code = 304, code = 304,
@ -302,7 +302,7 @@ public interface SubscriptionManagementAPI {
Response getApplication( Response getApplication(
@ApiParam( @ApiParam(
name = "applicationUUID", name = "applicationUUID",
value = "Application ID" value = "ApplicationDTO ID"
) )
@QueryParam("applicationUUID") String applicationUUID, @QueryParam("applicationUUID") String applicationUUID,
@ApiParam( @ApiParam(

View File

@ -21,7 +21,7 @@ package org.wso2.carbon.device.application.mgt.store.api.services.impl;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.common.AppLifecycleState; import org.wso2.carbon.device.application.mgt.common.AppLifecycleState;
import org.wso2.carbon.device.application.mgt.common.Application; import org.wso2.carbon.device.application.mgt.common.dto.ApplicationDTO;
import org.wso2.carbon.device.application.mgt.common.ApplicationList; 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.Filter;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
@ -67,16 +67,16 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
filter.setLimit(limit); filter.setLimit(limit);
filter.setSortBy(sortBy); filter.setSortBy(sortBy);
filter.setFullMatch(isFullMatch); filter.setFullMatch(isFullMatch);
filter.setCurrentAppReleaseState(AppLifecycleState.PUBLISHED.toString()); filter.setAppReleaseState(AppLifecycleState.PUBLISHED.toString());
if (appName != null && !appName.isEmpty()) { if (appName != null && !appName.isEmpty()) {
filter.setAppName(appName); filter.setAppName(appName);
} }
if (appType != null && !appType.isEmpty()) { if (appType != null && !appType.isEmpty()) {
filter.setAppType(appType); filter.setAppType(appType);
} }
if (appCategory != null && !appCategory.isEmpty()) { // if (appCategory != null && !appCategory.isEmpty()) {
filter.setAppCategory(appCategory); // filter.setAppCategories(appCategory);
} // }
ApplicationList applications = applicationManager.getApplications(filter); ApplicationList applications = applicationManager.getApplications(filter);
if (applications.getApplications().isEmpty()) { if (applications.getApplications().isEmpty()) {
return Response.status(Response.Status.NOT_FOUND) return Response.status(Response.Status.NOT_FOUND)
@ -97,7 +97,7 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
@PathParam("uuid") String uuid) { @PathParam("uuid") String uuid) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
try { try {
Application application = applicationManager ApplicationDTO application = applicationManager
.getApplicationByUuid(uuid, AppLifecycleState.PUBLISHED.toString()); .getApplicationByUuid(uuid, AppLifecycleState.PUBLISHED.toString());
return Response.status(Response.Status.OK).entity(application).build(); return Response.status(Response.Status.OK).entity(application).build();
} catch (NotFoundException e) { } catch (NotFoundException e) {

View File

@ -48,7 +48,7 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
@Override @Override
@POST @POST
@Path("/install-application") @Path("/install-application")
public Response installApplication(@ApiParam(name = "installationDetails", value = "Application ID and list of" + public Response installApplication(@ApiParam(name = "installationDetails", value = "ApplicationDTO ID and list of" +
"devices", required = true) @Valid InstallationDetails installationDetails) { "devices", required = true) @Valid InstallationDetails installationDetails) {
SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager(); SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager();
String applicationUUID = installationDetails.getApplicationUUID(); String applicationUUID = installationDetails.getApplicationUUID();
@ -81,7 +81,7 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
ApplicationInstallResponse response; ApplicationInstallResponse response;
if (applicationUUID.isEmpty()) { if (applicationUUID.isEmpty()) {
msg = "Application UUID is empty in the incoming request. Therefore unable to proceed with the " msg = "ApplicationDTO UUID is empty in the incoming request. Therefore unable to proceed with the "
+ "installation."; + "installation.";
log.error(msg); log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
@ -128,7 +128,7 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
} }
@Override @Override
public Response getApplication(@ApiParam(name = "applicationUUID", value = "Application ID") String public Response getApplication(@ApiParam(name = "applicationUUID", value = "ApplicationDTO ID") String
applicationUUID, @ApiParam(name = "deviceId", value = "The device ID") applicationUUID, @ApiParam(name = "deviceId", value = "The device ID")
String deviceId) { String deviceId) {
return null; return null;

View File

@ -30,7 +30,7 @@
<PermissionConfiguration> <PermissionConfiguration>
<APIVersion></APIVersion> <APIVersion></APIVersion>
<!-- Application related permissions --> <!-- ApplicationDTO related permissions -->
<Permission> <Permission>
<name>Get Application</name> <name>Get Application</name>
<path>/device-mgt/application/get</path> <path>/device-mgt/application/get</path>

View File

@ -28,12 +28,31 @@
</parent> </parent>
<artifactId>org.wso2.carbon.device.application.mgt.store.ui</artifactId> <artifactId>org.wso2.carbon.device.application.mgt.store.ui</artifactId>
<version>3.2.2-SNAPSHOT</version> <version>3.2.2-SNAPSHOT</version>
<packaging>war</packaging>
<name>WSO2 Carbon - Application Management Store UI Component</name>
<url>http://wso2.org</url>
<description>This Component contains Application Management store UI</description>
<dependencies> <dependencies>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<packagingExcludes>WEB-INF/lib/*cxf*.jar</packagingExcludes>
<warName>store</warName>
<webResources>
<resource>
<directory>${npm.output.directory}/dist</directory>
</resource>
<resource>
<directory>${npm.output.directory}/public</directory>
<targetPath>public</targetPath>
</resource>
</webResources>
</configuration>
</plugin>
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId> <artifactId>exec-maven-plugin</artifactId>
@ -46,10 +65,11 @@
</goals> </goals>
<phase>initialize</phase> <phase>initialize</phase>
<configuration> <configuration>
<workingDirectory>${basedir}/src/main/resources/store</workingDirectory> <workingDirectory>react-app</workingDirectory>
<executable>${npm.executable}</executable> <executable>${npm.executable}</executable>
<arguments> <arguments>
<argument>install</argument> <argument>install</argument>
<argument>--silent</argument>
</arguments> </arguments>
</configuration> </configuration>
</execution> </execution>
@ -60,7 +80,7 @@
</goals> </goals>
<phase>compile</phase> <phase>compile</phase>
<configuration> <configuration>
<workingDirectory>${basedir}/src/main/resources/store</workingDirectory> <workingDirectory>react-app</workingDirectory>
<executable>${npm.executable}</executable> <executable>${npm.executable}</executable>
<arguments> <arguments>
<argument>run</argument> <argument>run</argument>
@ -73,7 +93,6 @@
<workingDirectory>${npm.working.dir}</workingDirectory> <workingDirectory>${npm.working.dir}</workingDirectory>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<profiles> <profiles>
@ -94,6 +113,8 @@
<maven.test.skip>false</maven.test.skip> <maven.test.skip>false</maven.test.skip>
<npm.executable>npm</npm.executable> <npm.executable>npm</npm.executable>
<npm.build.command>build_prod</npm.build.command> <npm.build.command>build_prod</npm.build.command>
<npm.working.dir>./src/main/</npm.working.dir> <npm.working.dir>./react-app</npm.working.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<npm.output.directory>react-app</npm.output.directory>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,11 @@
module.exports = function (api) {
api.cache(true);
const presets = [ "@babel/preset-env",
"@babel/preset-react" ];
const plugins = ["@babel/plugin-proposal-class-properties"];
return {
presets,
plugins
};
};

View File

@ -0,0 +1,71 @@
{
"name": "store",
"version": "1.0.0",
"description": "WSO2 IoT Server App Publisher",
"main": "App.js",
"proxy": "http://localhost:3001",
"repository": {
"type": "git",
"url": "git://github.com/wso2/carbon-devicemgt"
},
"license": "Apache License 2.0",
"dependencies": {
"acorn": "^6.1.1",
"antd": "^3.15.0",
"react": "^16.8.4",
"react-dom": "^16.8.4",
"react-router-config": "^5.0.0",
"react-router-dom": "latest",
"react-scripts": "2.1.8"
},
"devDependencies": {
"@babel/core": "^7.0.0",
"@babel/plugin-proposal-class-properties": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"@babel/preset-react": "^7.0.0",
"@babel/register": "^7.0.0",
"babel-loader": "^8.0.0",
"body-parser": "^1.18.3",
"chai": "^4.1.2",
"css-loader": "^0.28.11",
"express": "^4.16.4",
"express-pino-logger": "^4.0.0",
"file-loader": "^2.0.0",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"img-loader": "^3.0.1",
"less": "^3.9.0",
"less-loader": "^4.1.0",
"mini-css-extract-plugin": "^0.5.0",
"mocha": "^5.2.0",
"mock-local-storage": "^1.0.5",
"node-env-run": "^3.0.2",
"node-sass": "^4.11.0",
"nodemon": "^1.18.9",
"npm-run-all": "^4.1.5",
"pino-colada": "^1.4.4",
"postcss-loader": "^3.0.0",
"react": "^15.6.2",
"react-dom": "^15.6.2",
"react-intl": "^2.4.0",
"redux": "^4.0.1",
"sass-loader": "^6.0.7",
"style-loader": "^0.18.2",
"url-loader": "^1.1.2",
"webpack": "^4.27.1",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.10"
},
"scripts": {
"start": "webpack-dev-server --mode development --open",
"dev": "webpack --mode development",
"build": "webpack --mode production",
"watch": "webpack --watch --mode development",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"build_prod": "NODE_ENV=production NODE_OPTIONS=--max_old_space_size=4096 webpack -p --display errors-only --hide-modules",
"build_dev": "NODE_ENV=development webpack -d --watch ",
"server": "node-env-run server --exec nodemon | pino-colada",
"dev2": "run-p server start"
}
}

View File

@ -7,5 +7,6 @@
"hostname": "localhost", "hostname": "localhost",
"httpsPort": "9443", "httpsPort": "9443",
"apiPort": "8243" "apiPort": "8243"
} },
"serverUrl" : "https://localhost:9443"
} }

View File

@ -1,6 +1,6 @@
{ {
"short_name": "App Store", "short_name": "App Publisher",
"name": "WSO2 IoT App Store", "name": "WSO2 IoT App Publisher",
"icons": [ "icons": [
{ {
"src": "images/favicon.png", "src": "images/favicon.png",

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