From 2f74a6be8973eab31b8d097117d2d1d12366a0d9 Mon Sep 17 00:00:00 2001 From: nancylizi Date: Wed, 31 Aug 2016 14:22:36 +0800 Subject: modify catalog code fit for check style Change-Id: I782b72fc1a4af37f20116fde624a4826d4154546 Signed-off-by: nancylizi --- .../org/openo/commontosca/catalog/CatalogApp.java | 260 ++-- .../catalog/CatalogAppConfiguration.java | 399 +++--- .../catalog/cometd/CometdException.java | 72 +- .../commontosca/catalog/cometd/CometdService.java | 151 +- .../commontosca/catalog/cometd/CometdServlet.java | 102 +- .../commontosca/catalog/cometd/CometdUtil.java | 61 +- .../commontosca/catalog/common/CommonConstant.java | 35 +- .../catalog/common/CommonErrorResponse.java | 29 +- .../openo/commontosca/catalog/common/Config.java | 15 +- .../commontosca/catalog/common/DateTimeUtil.java | 19 +- .../catalog/common/EnumUploadStatus.java | 5 +- .../openo/commontosca/catalog/common/FileUtil.java | 265 ++-- .../commontosca/catalog/common/FtpClient.java | 318 +++-- .../catalog/common/HttpServerAddrConfig.java | 20 +- .../catalog/common/HttpServerPathConfig.java | 20 +- .../openo/commontosca/catalog/common/MSBUtil.java | 57 - .../commontosca/catalog/common/MsbAddrConfig.java | 19 +- .../openo/commontosca/catalog/common/MsbUtil.java | 56 + .../openo/commontosca/catalog/common/RestUtil.java | 26 +- .../catalog/common/ServiceRegistrer.java | 131 +- .../openo/commontosca/catalog/common/ToolUtil.java | 560 +++++--- .../commontosca/catalog/common/ZipCompressor.java | 156 +- .../catalog/db/common/CatalogResuorceType.java | 13 +- .../commontosca/catalog/db/common/Parameters.java | 9 +- .../openo/commontosca/catalog/db/dao/BaseDao.java | 323 +++-- .../commontosca/catalog/db/dao/DaoManager.java | 223 +-- .../catalog/db/dao/NodeTemplateDao.java | 11 +- .../commontosca/catalog/db/dao/PackageDao.java | 11 +- .../catalog/db/dao/ServiceTemplateDao.java | 14 +- .../catalog/db/dao/ServiceTemplateMappingDao.java | 14 +- .../commontosca/catalog/db/dao/TemplateDao.java | 86 +- .../commontosca/catalog/db/entity/BaseData.java | 1 + .../catalog/db/entity/NodeTemplateData.java | 104 +- .../commontosca/catalog/db/entity/PackageData.java | 303 ++-- .../catalog/db/entity/ServiceTemplateData.java | 166 +-- .../db/entity/ServiceTemplateMappingData.java | 87 +- .../catalog/db/entity/TemplateData.java | 29 +- .../db/exception/CatalogResourceException.java | 77 +- .../catalog/db/exception/ErrorCodeException.java | 177 +-- .../catalog/db/resource/PackageManager.java | 233 +-- .../catalog/db/resource/TemplateManager.java | 401 ++++-- .../commontosca/catalog/db/util/CatalogDbUtil.java | 41 +- .../commontosca/catalog/db/util/HqlFactory.java | 314 +++-- .../catalog/db/wrapper/BaseHandler.java | 302 ++-- .../catalog/db/wrapper/NodeTemplateHandler.java | 55 +- .../catalog/db/wrapper/PackageHandler.java | 194 ++- .../catalog/db/wrapper/ServiceTemplateHandler.java | 104 +- .../db/wrapper/ServiceTemplateMappingHandler.java | 137 +- .../catalog/db/wrapper/TemplateHandler.java | 101 +- .../commontosca/catalog/entity/CSARPackage.java | 101 -- .../catalog/entity/CSARQueryCondition.java | 38 - .../commontosca/catalog/entity/CsarPackage.java | 102 ++ .../catalog/entity/CsarQueryCondition.java | 39 + .../catalog/entity/EnumOnboardState.java | 25 +- .../catalog/entity/EnumOperationalState.java | 3 +- .../catalog/entity/EnumProcessState.java | 7 +- .../openo/commontosca/catalog/entity/EnumType.java | 3 +- .../commontosca/catalog/entity/EnumUsageState.java | 3 +- .../commontosca/catalog/entity/VnfPackage.java | 163 +-- .../catalog/entity/request/PackageBasicInfo.java | 13 +- .../request/UploadPackageFromFtpRequest.java | 13 +- .../entity/response/CsarFileUriResponse.java | 9 +- .../catalog/entity/response/PackageMeta.java | 39 +- .../entity/response/UpdatePackageResponse.java | 3 +- .../entity/response/UploadPackageResponse.java | 3 +- .../msb/MicroserviceBusConsumer.java | 38 +- .../externalservice/msb/MicroserviceBusRest.java | 19 +- .../catalog/externalservice/msb/ServiceNode.java | 11 +- .../externalservice/msb/ServiceRegisterEntity.java | 45 +- .../catalog/filemanage/FileManager.java | 24 +- .../catalog/filemanage/FileManagerFactory.java | 46 +- .../catalog/filemanage/FileManagerType.java | 9 +- .../catalog/filemanage/entity/FileLink.java | 5 +- .../filemanage/http/HttpFileManagerImpl.java | 111 +- .../catalog/filemanage/http/ToolUtil.java | 264 ++-- .../org/openo/commontosca/catalog/ftp/Ftp.java | 16 +- .../org/openo/commontosca/catalog/ftp/FtpUtil.java | 328 +++-- .../catalog/health/ConsoleHealthCheck.java | 23 +- .../model/common/EnumToscaNodeTypeDefinition.java | 86 +- .../common/EnumToscaRelationShipDefinition.java | 55 +- .../catalog/model/common/TemplateDataHelper.java | 414 +++--- .../catalog/model/entity/EnumDataType.java | 31 +- .../catalog/model/entity/InputParameter.java | 15 +- .../catalog/model/entity/KeyValuePair.java | 5 +- .../catalog/model/entity/NfvTemplate.java | 14 +- .../catalog/model/entity/NodeTemplate.java | 17 +- .../catalog/model/entity/OutputParameter.java | 34 + .../catalog/model/entity/Parameters.java | 32 + .../model/entity/QueryRawDataCondition.java | 9 +- .../catalog/model/entity/RelationShip.java | 19 +- .../catalog/model/entity/ServiceTemplate.java | 31 +- .../model/entity/ServiceTemplateOperation.java | 16 +- .../model/entity/ServiceTemplateRawData.java | 5 +- .../catalog/model/entity/SubstitutionMapping.java | 72 +- .../container/ContainerSelfServiceProvider.java | 55 +- .../container/ContainerServiceConsumer.java | 373 +++-- .../ContainerServiceNodeTemplateProvider.java | 77 +- .../container/ContainerServicePackageProvider.java | 57 +- .../ContainerServiceTemplateProvider.java | 58 +- .../container/IContainerExtPackageRest.java | 30 +- .../container/IContainerPortabilityRest.java | 14 +- .../container/IContainerSelfServiceRest.java | 39 +- .../container/IContainerTemplateRest.java | 26 +- .../externalservice/container/NamespaceFilter.java | 97 +- .../externalservice/container/StringProvider.java | 27 +- .../entity/container/ContainerSelfService.java | 88 ++ .../container/ContainerSelfServiceOption.java | 97 ++ .../container/ContainerServiceCommonParam.java | 46 + .../container/ContainerServiceNodeTemplate.java | 316 +++++ .../ContainerServiceNodeTemplateList.java | 41 + .../ContainerServiceOperationParameter.java | 21 + .../entity/container/ContainerServicePackage.java | 59 + .../container/ContainerServicePackageList.java | 43 + .../container/ContainerServiceRelationShip.java | 80 ++ .../entity/container/ContainerServiceTemplate.java | 330 +++++ .../container/ContainerServiceTemplateList.java | 42 + .../containerEntity/ContainerSelfService.java | 87 -- .../ContainerSelfServiceOption.java | 82 -- .../ContainerServiceCommonParam.java | 45 - .../ContainerServiceNodeTemplate.java | 320 ----- .../ContainerServiceNodeTemplateList.java | 40 - .../ContainerServiceOperationParameter.java | 24 - .../containerEntity/ContainerServicePackage.java | 53 - .../ContainerServicePackageList.java | 41 - .../ContainerServiceRelationShip.java | 79 -- .../containerEntity/ContainerServiceTemplate.java | 336 ----- .../ContainerServiceTemplateList.java | 40 - .../entity/lifecycle/InstanceEntity.java | 29 + .../entity/lifecycleEnity/InstanceEntity.java | 28 - .../entity/ro/ResourceResponseEntity.java | 40 + .../model/externalservice/entity/ro/VimEntity.java | 75 + .../entity/roEntity/ResourceResponseEntity.java | 42 - .../externalservice/entity/roEntity/VimEntity.java | 63 - .../lifecycle/ILifeCycleServiceRest.java | 10 +- .../lifecycle/LifeCycleServiceConsumer.java | 70 +- .../externalservice/ro/IResourceServiceRest.java | 12 +- .../ro/ResourceServiceConsumer.java | 97 +- .../catalog/model/parser/AbstractModelParser.java | 14 +- .../catalog/model/parser/EnumPackageFormat.java | 6 +- .../catalog/model/parser/EnumTemplateType.java | 3 +- .../catalog/model/parser/ModelParserFactory.java | 59 +- .../catalog/model/parser/ToscaYamlModelParser.java | 588 ++++---- .../catalog/model/parser/yaml/IYamlParseRest.java | 24 +- .../parser/yaml/YamlParseServiceConsumer.java | 57 +- .../yaml/entity/EnumYamlServiceTemplateInfo.java | 42 +- .../yaml/entity/ParseYamlRequestParemeter.java | 69 +- .../model/parser/yaml/entity/ParseYamlResult.java | 1490 ++++++++++---------- .../catalog/model/plan/wso2/IWSO2RestService.java | 63 - .../catalog/model/plan/wso2/Iwso2RestService.java | 57 + .../catalog/model/plan/wso2/RestResponse.java | 34 + .../catalog/model/plan/wso2/RestfulClient.java | 117 ++ .../model/plan/wso2/WSO2ServiceConsumer.java | 123 -- .../model/plan/wso2/Wso2ServiceConsumer.java | 185 +++ .../plan/wso2/entity/DeletePackageResponse.java | 22 +- .../plan/wso2/entity/DeployPackageResponse.java | 26 +- .../plan/wso2/entity/StartProcessRequest.java | 13 +- .../plan/wso2/entity/StartProcessResponse.java | 24 +- .../catalog/model/service/ModelService.java | 55 + .../model/wrapper/ServiceTemplateWrapper.java | 575 ++++---- .../resources/CatalogBadRequestException.java | 70 +- .../catalog/resources/PackageResource.java | 408 +++--- .../commontosca/catalog/resources/RestUtils.java | 35 +- .../catalog/resources/TemplateResource.java | 739 +++++----- .../catalog/wrapper/PackageWrapper.java | 822 ++++++----- .../catalog/wrapper/PackageWrapperUtil.java | 627 ++++---- .../catalog/db/resource/IntegrationManager.java | 270 ++-- .../catalog/db/resource/PackageManagerTest.java | 245 ++-- .../catalog/db/resource/TemplateManagerTest.java | 232 +-- .../db/resource/TemplateMappingManagerTest.java | 242 ++-- .../catalog/db/resource/dao/PackageDaoTest.java | 188 +-- .../catalog/db/util/CatalogDbUtilTest.java | 72 +- .../commontosca/catalog/db/util/H2DbServer.java | 56 +- .../catalog/db/util/H2DbServerUtil.java | 69 +- .../catalog/db/util/HibernateSession.java | 94 +- .../catalog/db/util/HqlFactoryTest.java | 168 +-- .../catalog/wrapper/PackageWrapperTest.java | 504 +++---- 176 files changed, 10981 insertions(+), 9799 deletions(-) delete mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/MSBUtil.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/MsbUtil.java delete mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/CSARPackage.java delete mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/CSARQueryCondition.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/CsarPackage.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/CsarQueryCondition.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/OutputParameter.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/Parameters.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerSelfService.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerSelfServiceOption.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceCommonParam.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceNodeTemplate.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceNodeTemplateList.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceOperationParameter.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServicePackage.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServicePackageList.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceRelationShip.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceTemplate.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceTemplateList.java delete mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerSelfService.java delete mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerSelfServiceOption.java delete mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceCommonParam.java delete mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceNodeTemplate.java delete mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceNodeTemplateList.java delete mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceOperationParameter.java delete mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServicePackage.java delete mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServicePackageList.java delete mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceRelationShip.java delete mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceTemplate.java delete mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceTemplateList.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/lifecycle/InstanceEntity.java delete mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/lifecycleEnity/InstanceEntity.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/ro/ResourceResponseEntity.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/ro/VimEntity.java delete mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/roEntity/ResourceResponseEntity.java delete mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/roEntity/VimEntity.java delete mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/IWSO2RestService.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/Iwso2RestService.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/RestResponse.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/RestfulClient.java delete mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/WSO2ServiceConsumer.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/Wso2ServiceConsumer.java create mode 100644 catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/service/ModelService.java (limited to 'catalog-core/catalog-mgr/src') diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/CatalogApp.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/CatalogApp.java index 903a0a2e..63577826 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/CatalogApp.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/CatalogApp.java @@ -13,8 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog; +import com.fasterxml.jackson.annotation.JsonInclude; + import io.dropwizard.Application; import io.dropwizard.assets.AssetsBundle; import io.dropwizard.db.DataSourceFactory; @@ -26,150 +29,147 @@ import io.dropwizard.setup.Environment; import io.swagger.jaxrs.config.BeanConfig; import io.swagger.jaxrs.listing.ApiListingResource; -import java.util.EnumSet; - -import javax.servlet.DispatcherType; - import org.eclipse.jetty.servlets.CrossOriginFilter; import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.openo.commontosca.catalog.common.Config; +import org.openo.commontosca.catalog.common.HttpServerAddrConfig; +import org.openo.commontosca.catalog.common.HttpServerPathConfig; import org.openo.commontosca.catalog.common.MsbAddrConfig; import org.openo.commontosca.catalog.common.ServiceRegistrer; +import org.openo.commontosca.catalog.db.dao.DaoManager; +import org.openo.commontosca.catalog.db.entity.NodeTemplateData; +import org.openo.commontosca.catalog.db.entity.PackageData; import org.openo.commontosca.catalog.db.entity.ServiceTemplateData; import org.openo.commontosca.catalog.db.entity.ServiceTemplateMappingData; import org.openo.commontosca.catalog.health.ConsoleHealthCheck; import org.openo.commontosca.catalog.resources.PackageResource; import org.openo.commontosca.catalog.resources.TemplateResource; -import org.openo.commontosca.catalog.common.HttpServerAddrConfig; -import org.openo.commontosca.catalog.common.HttpServerPathConfig; -import org.openo.commontosca.catalog.db.dao.DaoManager; -import org.openo.commontosca.catalog.db.entity.NodeTemplateData; -import org.openo.commontosca.catalog.db.entity.PackageData; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.fasterxml.jackson.annotation.JsonInclude; +import java.util.EnumSet; +import javax.servlet.DispatcherType; + public class CatalogApp extends Application { - private static final Logger LOGGER = LoggerFactory.getLogger(CatalogApp.class); - - public static void main(String[] args) throws Exception { - new CatalogApp().run(args); - } - - @Override - public String getName() { - return "OPENO-Catalog"; - } - - private final HibernateBundle bundle = - new HibernateBundle(ServiceTemplateData.class, - PackageData.class, NodeTemplateData.class, ServiceTemplateMappingData.class) { - @Override - public DataSourceFactory getDataSourceFactory(CatalogAppConfiguration configuration) { - return configuration.getDataSourceFactory(); - } - }; - - @Override - public void initialize(Bootstrap bootstrap) { - bootstrap.addBundle(new AssetsBundle("/api-doc", "/api-doc", "index.html", "api-doc")); - initDB(bootstrap); - } - - private void initDao() { - DaoManager.getInstance().setSessionFactory(bundle.getSessionFactory()); - } - - private void initDB(Bootstrap bootstrap) { - bootstrap.addBundle(bundle); - bootstrap.addBundle(new MigrationsBundle() { - @Override - public DataSourceFactory getDataSourceFactory(CatalogAppConfiguration configuration) { - return configuration.getDataSourceFactory(); - } - }); - } - - @Override - public void run(CatalogAppConfiguration configuration, Environment environment) { - LOGGER.info("Start to initialize catalogue."); - MsbAddrConfig.setMsbAddress(configuration.getMsbServerAddr()); - HttpServerAddrConfig.setHttpServerAddress(configuration.getHttpServerAddr()); - HttpServerPathConfig.setHttpServerPath(configuration.getHttpServerPath()); - initDao(); - final ConsoleHealthCheck healthCheck = new ConsoleHealthCheck(configuration.getTemplate()); - environment.healthChecks().register("template", healthCheck); - - environment.jersey().register(new PackageResource()); - environment.jersey().register(new TemplateResource()); - // environment.jersey().register(new VNFHostImageResource()); - // environment.jersey().register(new VNFSoftwareVersionResource()); - - // register rest interface - environment.jersey().packages("org.openo.commontosca.catalog.resources"); - // upload file by inputstream need to register MultiPartFeature - environment.jersey().register(MultiPartFeature.class); - - initSwaggerConfig(environment, configuration); - initCometd(environment); - Config.setConfigration(configuration); - initService(); - LOGGER.info("Initialize catalogue finished."); - } - - /** - * initialize swagger configuration. - * - * @param environment environment information - * @param configuration catalogue configuration - */ - private void initSwaggerConfig(Environment environment, CatalogAppConfiguration configuration) { - environment.jersey().register(new ApiListingResource()); - environment.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL); - - BeanConfig config = new BeanConfig(); - config.setTitle("Open-o Catalog Service rest API"); - config.setVersion("1.0.0"); - config.setResourcePackage("org.openo.commontosca.catalog.resources"); - // set rest api basepath in swagger - SimpleServerFactory simpleServerFactory = - (SimpleServerFactory) configuration.getServerFactory(); - String basePath = simpleServerFactory.getApplicationContextPath(); - String rootPath = simpleServerFactory.getJerseyRootPath(); - rootPath = rootPath.substring(0, rootPath.indexOf("/*")); - basePath = - basePath.equals("/") ? rootPath : (new StringBuilder()).append(basePath) - .append(rootPath).toString(); - config.setBasePath(basePath); - config.setScan(true); - } - private void initService() - { - Thread registerCatalogService=new Thread(new ServiceRegistrer()); - registerCatalogService.setName("register catalog service to Microservice Bus"); - registerCatalogService.start(); - } - /** - * initialize cometd server. - * - * @param environment environment information - */ - private void initCometd(Environment environment) { - environment.getApplicationContext().addFilter(CrossOriginFilter.class, - "/api/nsoccataloguenotification/v1/*", - EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR));// add - // filter - environment - .getApplicationContext() - .addServlet("org.cometd.server.CometDServlet", - "/api/nsoccataloguenotification/v1/*").setInitOrder(1);// add - // servlet - environment - .getApplicationContext() - .addServlet("CometdServlet", - "/api/nsoccataloguenotification/v1").setInitOrder(2);// add - // servlet - } + private static final Logger LOGGER = LoggerFactory.getLogger(CatalogApp.class); + + public static void main(String[] args) throws Exception { + new CatalogApp().run(args); + } + + @Override + public String getName() { + return "OPENO-Catalog"; + } + + private final HibernateBundle bundle = + new HibernateBundle(ServiceTemplateData.class, PackageData.class, + NodeTemplateData.class, ServiceTemplateMappingData.class) { + @Override + public DataSourceFactory getDataSourceFactory(CatalogAppConfiguration configuration) { + return configuration.getDataSourceFactory(); + } + }; + + @Override + public void initialize(Bootstrap bootstrap) { + bootstrap.addBundle(new AssetsBundle("/api-doc", "/api-doc", "index.html", "api-doc")); + initDb(bootstrap); + } + + private void initDao() { + DaoManager.getInstance().setSessionFactory(bundle.getSessionFactory()); + } + + private void initDb(Bootstrap bootstrap) { + bootstrap.addBundle(bundle); + bootstrap.addBundle(new MigrationsBundle() { + @Override + public DataSourceFactory getDataSourceFactory(CatalogAppConfiguration configuration) { + return configuration.getDataSourceFactory(); + } + }); + } + + @Override + public void run(CatalogAppConfiguration configuration, Environment environment) { + LOGGER.info("Start to initialize catalogue."); + MsbAddrConfig.setMsbAddress(configuration.getMsbServerAddr()); + HttpServerAddrConfig.setHttpServerAddress(configuration.getHttpServerAddr()); + HttpServerPathConfig.setHttpServerPath(configuration.getHttpServerPath()); + initDao(); + final ConsoleHealthCheck healthCheck = new ConsoleHealthCheck(configuration.getTemplate()); + environment.healthChecks().register("template", healthCheck); + + environment.jersey().register(new PackageResource()); + environment.jersey().register(new TemplateResource()); + // environment.jersey().register(new VNFHostImageResource()); + // environment.jersey().register(new VNFSoftwareVersionResource()); + + // register rest interface + environment.jersey().packages("org.openo.commontosca.catalog.resources"); + // upload file by inputstream need to register MultiPartFeature + environment.jersey().register(MultiPartFeature.class); + + initSwaggerConfig(environment, configuration); + initCometd(environment); + Config.setConfigration(configuration); + initService(); + LOGGER.info("Initialize catalogue finished."); + } + + /** + * initialize swagger configuration. + * + * @param environment environment information + * @param configuration catalogue configuration + */ + private void initSwaggerConfig(Environment environment, CatalogAppConfiguration configuration) { + environment.jersey().register(new ApiListingResource()); + environment.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL); + + BeanConfig config = new BeanConfig(); + config.setTitle("Open-o Catalog Service rest API"); + config.setVersion("1.0.0"); + config.setResourcePackage("org.openo.commontosca.catalog.resources"); + // set rest api basepath in swagger + SimpleServerFactory simpleServerFactory = + (SimpleServerFactory) configuration.getServerFactory(); + String basePath = simpleServerFactory.getApplicationContextPath(); + String rootPath = simpleServerFactory.getJerseyRootPath(); + rootPath = rootPath.substring(0, rootPath.indexOf("/*")); + basePath = + basePath.equals("/") ? rootPath : (new StringBuilder()).append(basePath).append(rootPath) + .toString(); + config.setBasePath(basePath); + config.setScan(true); + } + + private void initService() { + Thread registerCatalogService = new Thread(new ServiceRegistrer()); + registerCatalogService.setName("register catalog service to Microservice Bus"); + registerCatalogService.start(); + } + + /** + * initialize cometd server. + * + * @param environment environment information + */ + private void initCometd(Environment environment) { + // add filter + environment.getApplicationContext().addFilter(CrossOriginFilter.class, + "/api/nsoccataloguenotification/v1/*", + EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR)); + // add servlet + environment.getApplicationContext() + .addServlet("org.cometd.server.CometDServlet", "/api/nsoccataloguenotification/v1/*") + .setInitOrder(1); + // add servlet + environment.getApplicationContext() + .addServlet("CometdServlet", "/api/nsoccataloguenotification/v1").setInitOrder(2); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/CatalogAppConfiguration.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/CatalogAppConfiguration.java index 1f74f61b..a951347f 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/CatalogAppConfiguration.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/CatalogAppConfiguration.java @@ -13,198 +13,229 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.dropwizard.Configuration; +import io.dropwizard.db.DataSourceFactory; +import org.hibernate.validator.constraints.NotEmpty; + import javax.validation.Valid; import javax.validation.constraints.NotNull; -import org.hibernate.validator.constraints.NotEmpty; - -import com.fasterxml.jackson.annotation.JsonProperty; -import io.dropwizard.Configuration; -import io.dropwizard.db.DataSourceFactory; public class CatalogAppConfiguration extends Configuration { - @NotEmpty - private String template; - - @NotEmpty - private String defaultName = "OPENO-Catalog"; - - @NotEmpty - private String msbServerAddr; - - @NotEmpty - private String httpServerAddr; - - @NotEmpty - private String opentoscaServerAddr; - - @NotEmpty - private String yamlParseAddr; - - @NotEmpty - private String cataloguePath; - @NotEmpty - private String httpServerPath; - @NotEmpty - private String ldapServerIp; - - @NotEmpty - private String ldapServerPort; - - @NotEmpty - private String ldapLogindn; - - @NotEmpty - private String ldapPassword; - - @NotEmpty - private String ldapVersion; - @Valid - @NotNull - private DataSourceFactory database = new DataSourceFactory(); - - @JsonProperty("database") - public DataSourceFactory getDataSourceFactory() { - return database; - } - - @JsonProperty("database") - public void setDataSourceFactory(DataSourceFactory dataSourceFactory) { - this.database = dataSourceFactory; - } - - @JsonProperty - public String getTemplate() { - return template; - } - - @JsonProperty - public void setTemplate(String template) { - this.template = template; - } - - @JsonProperty - public String getDefaultName() { - return defaultName; - } - - @JsonProperty - public void setDefaultName(String name) { - this.defaultName = name; - } - - @JsonProperty - public String getMsbServerAddr() { - return msbServerAddr; - } - - @JsonProperty - public void setMsbServerAddr(String msbServerAddr) { - this.msbServerAddr = msbServerAddr; - } - - @JsonProperty - public String getHttpServerAddr() { - return httpServerAddr; - } - - @JsonProperty - public void setHttpServerAddr(String httpServerAddr) { - this.httpServerAddr = httpServerAddr; - } - - @JsonProperty - public String getOpentoscaServerAddr() { - return opentoscaServerAddr; - } - - @JsonProperty - public void setOpentoscaServerAddr(String opentoscaServerAddr) { - this.opentoscaServerAddr = opentoscaServerAddr; - } - - @JsonProperty - public String getYamlParseAddr() { - return yamlParseAddr; - } - - @JsonProperty - public void setYamlParseAddr(String yamlParseAddr) { - this.yamlParseAddr = yamlParseAddr; - } - - @JsonProperty - public String getCataloguePath() { - return cataloguePath; - } - - @JsonProperty - public void setCataloguePath(String cataloguePath) { - this.cataloguePath = cataloguePath; - } - - @JsonProperty - public String getLdapServerIp() { - return ldapServerIp; - } - - @JsonProperty - public void setLdapServerIp(String ldapServerIp) { - this.ldapServerIp = ldapServerIp; - } - - @JsonProperty - public String getLdapServerPort() { - return ldapServerPort; - } - - @JsonProperty - public void setLdapServerPort(String ldapServerPort) { - this.ldapServerPort = ldapServerPort; - } - - @JsonProperty - public String getLdapLogindn() { - return ldapLogindn; - } - - @JsonProperty - public void setLdapLogindn(String ldapLogindn) { - this.ldapLogindn = ldapLogindn; - } - - @JsonProperty - public String getLdapPassword() { - return ldapPassword; - } - - @JsonProperty - public void setLdapPassword(String ldapPassword) { - this.ldapPassword = ldapPassword; - } - - @JsonProperty - public String getLdapVersion() { - return ldapVersion; - } - - @JsonProperty - public void setLdapVersion(String ldapVersion) { - this.ldapVersion = ldapVersion; - } - - @JsonProperty - public String getHttpServerPath() { - return httpServerPath; - } - - @JsonProperty - public void setHttpServerPath(String httpServerPath) { - this.httpServerPath = httpServerPath; - } + @NotEmpty + private String template; + + @NotEmpty + private String defaultName = "OPENO-Catalog"; + + @NotEmpty + private String msbServerAddr; + + @NotEmpty + private String httpServerAddr; + + @NotEmpty + private String opentoscaServerAddr; + + @NotEmpty + private String yamlParseAddr; + + @NotEmpty + private String wso2HostIp; + + @NotEmpty + private String wso2HostPort; + + @NotEmpty + private String cataloguePath; + @NotEmpty + private String httpServerPath; + @NotEmpty + private String ldapServerIp; + + @NotEmpty + private String ldapServerPort; + + @NotEmpty + private String ldapLogindn; + + @NotEmpty + private String ldapPassword; + + @NotEmpty + private String ldapVersion; + @Valid + @NotNull + private DataSourceFactory database = new DataSourceFactory(); + + @JsonProperty("database") + public DataSourceFactory getDataSourceFactory() { + return database; + } + + @JsonProperty("database") + public void setDataSourceFactory(DataSourceFactory dataSourceFactory) { + this.database = dataSourceFactory; + } + + @JsonProperty + public String getTemplate() { + return template; + } + + @JsonProperty + public void setTemplate(String template) { + this.template = template; + } + + @JsonProperty + public String getDefaultName() { + return defaultName; + } + + @JsonProperty + public void setDefaultName(String name) { + this.defaultName = name; + } + + @JsonProperty + public String getMsbServerAddr() { + return msbServerAddr; + } + + @JsonProperty + public void setMsbServerAddr(String msbServerAddr) { + this.msbServerAddr = msbServerAddr; + } + + @JsonProperty + public String getHttpServerAddr() { + return httpServerAddr; + } + + @JsonProperty + public void setHttpServerAddr(String httpServerAddr) { + this.httpServerAddr = httpServerAddr; + } + + @JsonProperty + public String getOpentoscaServerAddr() { + return opentoscaServerAddr; + } + + @JsonProperty + public void setOpentoscaServerAddr(String opentoscaServerAddr) { + this.opentoscaServerAddr = opentoscaServerAddr; + } + + @JsonProperty + public String getYamlParseAddr() { + return yamlParseAddr; + } + + @JsonProperty + public void setYamlParseAddr(String yamlParseAddr) { + this.yamlParseAddr = yamlParseAddr; + } + + @JsonProperty + public String getWso2HostIp() { + return wso2HostIp; + } + + @JsonProperty + public void setWso2HostIp(String wso2HostIp) { + this.wso2HostIp = wso2HostIp; + } + + @JsonProperty + public String getWso2HostPort() { + return wso2HostPort; + } + + @JsonProperty + public void setWso2HostPort(String wso2HostPort) { + this.wso2HostPort = wso2HostPort; + } + + public String getWso2BaseUrl() { + return "http://" + this.wso2HostIp + ":" + this.wso2HostPort; + } + + @JsonProperty + public String getCataloguePath() { + return cataloguePath; + } + + @JsonProperty + public void setCataloguePath(String cataloguePath) { + this.cataloguePath = cataloguePath; + } + + @JsonProperty + public String getLdapServerIp() { + return ldapServerIp; + } + + @JsonProperty + public void setLdapServerIp(String ldapServerIp) { + this.ldapServerIp = ldapServerIp; + } + + @JsonProperty + public String getLdapServerPort() { + return ldapServerPort; + } + + @JsonProperty + public void setLdapServerPort(String ldapServerPort) { + this.ldapServerPort = ldapServerPort; + } + + @JsonProperty + public String getLdapLogindn() { + return ldapLogindn; + } + + @JsonProperty + public void setLdapLogindn(String ldapLogindn) { + this.ldapLogindn = ldapLogindn; + } + + @JsonProperty + public String getLdapPassword() { + return ldapPassword; + } + + @JsonProperty + public void setLdapPassword(String ldapPassword) { + this.ldapPassword = ldapPassword; + } + + @JsonProperty + public String getLdapVersion() { + return ldapVersion; + } + + @JsonProperty + public void setLdapVersion(String ldapVersion) { + this.ldapVersion = ldapVersion; + } + + @JsonProperty + public String getHttpServerPath() { + return httpServerPath; + } + + @JsonProperty + public void setHttpServerPath(String httpServerPath) { + this.httpServerPath = httpServerPath; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/cometd/CometdException.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/cometd/CometdException.java index 0a84ce3e..65b1d5ae 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/cometd/CometdException.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/cometd/CometdException.java @@ -13,44 +13,42 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.cometd; -/** - * @author 10189609 - * - */ + public class CometdException extends Exception { - private static final long serialVersionUID = 497640895744777904L; - - public static final int ERROR_CODE_BAYEUX = 0; - public static final int ERROR_CODE_PRARM_ERROR = 1; - public static final int ERROR_CODE_SESSION_ERROR = 2; - public static final int ERROR_CODE_SUBSCRIBE_TIMEOUT = 3; - - private int errorCode = -1; - - public CometdException(String message) { - super(message); - } - - public CometdException(Throwable e) { - super(e); - } - - public CometdException(int code, String message) { - super(message); - this.errorCode = code; - } - - public int getErrorCode() { - return this.errorCode; - } - - @Override - public String toString() { - String s = getClass().getName(); - String message = getLocalizedMessage(); - message = (message != null) ? (s + ": " + message) : s; - return "errorcode: " + this.errorCode + ";" + message; - } + private static final long serialVersionUID = 497640895744777904L; + + public static final int ERROR_CODE_BAYEUX = 0; + public static final int ERROR_CODE_PRARM_ERROR = 1; + public static final int ERROR_CODE_SESSION_ERROR = 2; + public static final int ERROR_CODE_SUBSCRIBE_TIMEOUT = 3; + + private int errorCode = -1; + + public CometdException(String message) { + super(message); + } + + public CometdException(Throwable e1) { + super(e1); + } + + public CometdException(int code, String message) { + super(message); + this.errorCode = code; + } + + public int getErrorCode() { + return this.errorCode; + } + + @Override + public String toString() { + String str = getClass().getName(); + String message = getLocalizedMessage(); + message = (message != null) ? (str + ": " + message) : str; + return "errorcode: " + this.errorCode + ";" + message; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/cometd/CometdService.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/cometd/CometdService.java index 9af11450..823e5d11 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/cometd/CometdService.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/cometd/CometdService.java @@ -13,98 +13,105 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.cometd; -import java.io.IOException; +package org.openo.commontosca.catalog.cometd; import org.cometd.bayeux.server.BayeuxServer; import org.cometd.bayeux.server.ConfigurableServerChannel; import org.cometd.bayeux.server.LocalSession; import org.cometd.bayeux.server.ServerChannel; -/** - * @author 10189609 - * - */ +import java.io.IOException; + public class CometdService { - private BayeuxServer bayeux; - private LocalSession session; + private BayeuxServer bayeux; + private LocalSession session; - /** - * meta channel. - */ - private static final String bayeuxChannel = "/meta/"; + /** + * meta channel. + */ + private static final String bayeuxChannel = "/meta/"; - /** - * service channel. - */ - private static final String serviceChannel = "/service/"; + /** + * service channel. + */ + private static final String serviceChannel = "/service/"; - private static CometdService cometdService = null; + private static CometdService cometdService = null; - public static CometdService getInstance() { - if (cometdService == null) { - cometdService = new CometdService(); - } - return cometdService; + /** + * get cometd service instance. + * + * @return cometdService + */ + public static CometdService getInstance() { + if (cometdService == null) { + cometdService = new CometdService(); } + return cometdService; + } - public void publish(String channel, Object message) throws CometdException { - if (bayeux == null) { - this.bayeux = CometdUtil.getBayeuxServer(); - checkBayeuxServer(); - this.session = this.bayeux.newLocalSession("openo_catalogue_local_session"); - this.session.handshake(); - } - String jsonMsg; - try { - jsonMsg = CometdUtil.convertBean2Json(message); - } catch (IOException e) { - throw new CometdException(e); - } - - checkAndInit(channel); - ServerChannel serverChannel = this.bayeux.getChannel(channel); - serverChannel.publish(this.session, jsonMsg); + /** + * publish commetd. + * @param channel commetd channel + * @param message message to commet + * @throws CometdException e1 + */ + public void publish(String channel, Object message) throws CometdException { + if (bayeux == null) { + this.bayeux = CometdUtil.getBayeuxServer(); + checkBayeuxServer(); + this.session = this.bayeux.newLocalSession("openo_catalogue_local_session"); + this.session.handshake(); } - - private void checkBayeuxServer() throws CometdException { - if (this.bayeux == null) { - throw new CometdException(CometdException.ERROR_CODE_BAYEUX, "bayeux is null."); - } + String jsonMsg; + try { + jsonMsg = CometdUtil.convertBean2Json(message); + } catch (IOException e1) { + throw new CometdException(e1); } - private void checkAndInit(String channel) throws CometdException { - checkBayeuxServer(); - checkSession(); - checkChannel(channel); - bayeux.createChannelIfAbsent(channel, new ConfigurableServerChannel.Initializer() { - @Override - public void configureChannel(ConfigurableServerChannel channel) { - channel.setPersistent(true); - channel.setLazy(true); - } - }); + checkAndInit(channel); + ServerChannel serverChannel = this.bayeux.getChannel(channel); + serverChannel.publish(this.session, jsonMsg); + } + + private void checkBayeuxServer() throws CometdException { + if (this.bayeux == null) { + throw new CometdException(CometdException.ERROR_CODE_BAYEUX, "bayeux is null."); } + } - private void checkSession() throws CometdException { - if (session == null || !session.isConnected()) { - throw new CometdException(CometdException.ERROR_CODE_SESSION_ERROR, - "session is invalid."); - } + private void checkAndInit(String channel) throws CometdException { + checkBayeuxServer(); + checkSession(); + checkChannel(channel); + bayeux.createChannelIfAbsent(channel, new ConfigurableServerChannel.Initializer() { + @Override + public void configureChannel(ConfigurableServerChannel channel) { + channel.setPersistent(true); + channel.setLazy(true); + } + }); + } + + private void checkSession() throws CometdException { + if (session == null || !session.isConnected()) { + throw new CometdException(CometdException.ERROR_CODE_SESSION_ERROR, "session is invalid."); } + } - private void checkChannel(String channel) throws CometdException { - if (channel == null || "".equals(channel)) { - throw new CometdException(CometdException.ERROR_CODE_PRARM_ERROR, "channel is null."); - } - if (channel.startsWith(bayeuxChannel)) { - throw new CometdException(CometdException.ERROR_CODE_PRARM_ERROR, "channel [" + channel - + "] is bayeuxChannel."); - } - if (channel.startsWith(serviceChannel)) { - throw new CometdException(CometdException.ERROR_CODE_PRARM_ERROR, "channel [" + channel - + "] is serviceChannel."); - } + private void checkChannel(String channel) throws CometdException { + if (channel == null || "".equals(channel)) { + throw new CometdException(CometdException.ERROR_CODE_PRARM_ERROR, "channel is null."); + } + if (channel.startsWith(bayeuxChannel)) { + throw new CometdException(CometdException.ERROR_CODE_PRARM_ERROR, "channel [" + channel + + "] is bayeuxChannel."); + } + if (channel.startsWith(serviceChannel)) { + throw new CometdException(CometdException.ERROR_CODE_PRARM_ERROR, "channel [" + channel + + "] is serviceChannel."); } + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/cometd/CometdServlet.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/cometd/CometdServlet.java index 6b69542a..d44c330b 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/cometd/CometdServlet.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/cometd/CometdServlet.java @@ -13,16 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.cometd; - -import java.io.IOException; -import javax.servlet.GenericServlet; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.UnavailableException; -import javax.servlet.http.HttpServletResponse; +package org.openo.commontosca.catalog.cometd; import org.cometd.annotation.Listener; import org.cometd.annotation.ServerAnnotationProcessor; @@ -36,60 +28,66 @@ import org.cometd.server.authorizer.GrantAuthorizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * @author 10189609 - * - */ +import java.io.IOException; + +import javax.servlet.GenericServlet; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.UnavailableException; +import javax.servlet.http.HttpServletResponse; + + + public class CometdServlet extends GenericServlet { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private static final Logger logger = LoggerFactory.getLogger(CometdServlet.class); + private static final Logger logger = LoggerFactory.getLogger(CometdServlet.class); + + @Override + public void init() throws ServletException { + super.init(); + + final BayeuxServer bayeux = + (BayeuxServer) getServletContext().getAttribute(BayeuxServer.ATTRIBUTE); + if (bayeux == null) { + throw new UnavailableException("No BayeuxServer!"); + } - @Override - public void init() throws ServletException { - super.init(); + // Allow anybody to handshake + bayeux.getChannel(ServerChannel.META_HANDSHAKE).addAuthorizer(GrantAuthorizer.GRANT_PUBLISH); - final BayeuxServer bayeux = - (BayeuxServer) getServletContext().getAttribute(BayeuxServer.ATTRIBUTE); - if (bayeux == null) { - throw new UnavailableException("No BayeuxServer!"); - } + // start server processor + ServerAnnotationProcessor processor = new ServerAnnotationProcessor(bayeux); + processor.process(new Monitor()); - // Allow anybody to handshake - bayeux.getChannel(ServerChannel.META_HANDSHAKE) - .addAuthorizer(GrantAuthorizer.GRANT_PUBLISH); + CometdUtil.setBayeuxServer(bayeux); + } - // start server processor - ServerAnnotationProcessor processor = new ServerAnnotationProcessor(bayeux); - processor.process(new Monitor()); + @Override + public void service(ServletRequest paramServletRequest, ServletResponse paramServletResponse) + throws ServletException, IOException { + ((HttpServletResponse) paramServletResponse).sendError(503); + } - CometdUtil.setBayeuxServer(bayeux); + @Service("monitor") + public static class Monitor { + @Listener("/meta/subscribe") + public void monitorSubscribe(ServerSession session, ServerMessage message) { + logger.info("Monitored subscribe from " + session + " for " + + message.get(Message.SUBSCRIPTION_FIELD)); } - @Override - public void service(ServletRequest paramServletRequest, ServletResponse paramServletResponse) - throws ServletException, IOException { - ((HttpServletResponse) paramServletResponse).sendError(503); + @Listener("/meta/unsubscribe") + public void monitorUnsubscribe(ServerSession session, ServerMessage message) { + logger.info("Monitored unsubscribe from " + session + " for " + + message.get(Message.SUBSCRIPTION_FIELD)); } - @Service("monitor") - public static class Monitor { - @Listener("/meta/subscribe") - public void monitorSubscribe(ServerSession session, ServerMessage message) { - logger.info("Monitored subscribe from " + session + " for " - + message.get(Message.SUBSCRIPTION_FIELD)); - } - - @Listener("/meta/unsubscribe") - public void monitorUnsubscribe(ServerSession session, ServerMessage message) { - logger.info("Monitored unsubscribe from " + session + " for " - + message.get(Message.SUBSCRIPTION_FIELD)); - } - - @Listener("/meta/*") - public void monitorMeta(ServerSession session, ServerMessage message) { - logger.debug(message.toString()); - } + @Listener("/meta/*") + public void monitorMeta(ServerSession session, ServerMessage message) { + logger.debug(message.toString()); } + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/cometd/CometdUtil.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/cometd/CometdUtil.java index 6955451c..400fcc31 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/cometd/CometdUtil.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/cometd/CometdUtil.java @@ -13,53 +13,36 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/** -* Copyright (C) 2016 ZTE, Inc. and others. All rights reserved. (ZTE) -* -* Licensed 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.openo.commontosca.catalog.cometd; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.cometd.bayeux.server.BayeuxServer; + import java.io.IOException; import java.util.Map; -import org.cometd.bayeux.server.BayeuxServer; -import com.fasterxml.jackson.databind.ObjectMapper; -/** - * @author 10189609 - * - */ public class CometdUtil { - private static BayeuxServer bayeuxServer; + private static BayeuxServer bayeuxServer; + + public static BayeuxServer getBayeuxServer() { + return bayeuxServer; + } + + public static void setBayeuxServer(BayeuxServer bayeuxServer) { + CometdUtil.bayeuxServer = bayeuxServer; + } - public static BayeuxServer getBayeuxServer() { - return bayeuxServer; - } + public static String convertBean2Json(Object object) throws IOException { + ObjectMapper mapper = new ObjectMapper(); + return mapper.writeValueAsString(object); + } - public static void setBayeuxServer(BayeuxServer bayeuxServer) { - CometdUtil.bayeuxServer = bayeuxServer; - } - - public static String convertBean2Json(Object object) throws IOException { - ObjectMapper mapper = new ObjectMapper(); - return mapper.writeValueAsString(object); - } - - @SuppressWarnings("rawtypes") - public static Map convertJson2Map(String json) throws IOException { - ObjectMapper mapper = new ObjectMapper(); - return mapper.readValue(json, Map.class); - } + @SuppressWarnings("rawtypes") + public static Map convertJson2Map(String json) throws IOException { + ObjectMapper mapper = new ObjectMapper(); + return mapper.readValue(json, Map.class); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/CommonConstant.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/CommonConstant.java index 08741619..e6992264 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/CommonConstant.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/CommonConstant.java @@ -13,38 +13,37 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.common; public class CommonConstant { + // Package Status + public static final String PACKAGE_STATUS_DELETING = "deleting"; + public static final String PACKAGE_STATUS_DELETE_FAIL = "deletefail"; - public final static String HTTP_HEADER_CONTENT_RANGE = "Content-Range"; - - // Package Status - public static final String PACKAGE_STATUS_DELETING = "deleting"; - - public static final String PACKAGE_STATUS_DELETE_FAIL = "deletefail"; - - public static final String PACKAGE_XML_FORMAT = "xml"; + public static final String PACKAGE_XML_FORMAT = "xml"; - public final static String CATALOG_CSAR_DIR_NAME = "/csar"; - public static final String PACKAGE_YAML_FORMAT = "yaml"; + public static final String PACKAGE_YAML_FORMAT = "yaml"; - // host image progress + // host image progress - public static final String TOSCA_METADATA = "TOSCA-Metadata"; + public static final String TOSCA_METADATA = "TOSCA-Metadata"; - public static final String CSAR_VERSION_META = "version"; + public static final String CSAR_VERSION_META = "version"; - public static final String CSAR_TYPE_META = "type"; + public static final String CSAR_TYPE_META = "type"; - public static final String CSAR_PROVIDER_META = "provider"; + public static final String CSAR_PROVIDER_META = "provider"; - public static final String DEFINITIONS = "Definitions"; + public static final String DEFINITIONS = "Definitions"; - public static final String CSAR_META = "csar.meta"; + public static final String CSAR_META = "csar.meta"; - public static final String CSAR_SUFFIX = ".csar"; + public static final String CSAR_SUFFIX = ".csar"; + public static final String HTTP_HEADER_CONTENT_RANGE = "Content-Range"; + + public static final String CATALOG_CSAR_DIR_NAME = "/csar"; } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/CommonErrorResponse.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/CommonErrorResponse.java index c260b923..3d85ee31 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/CommonErrorResponse.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/CommonErrorResponse.java @@ -13,37 +13,30 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.common; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -/** - * @author 00164331 - * - */ - @Data @NoArgsConstructor @AllArgsConstructor public class CommonErrorResponse { - private String code; + private String code; + + private String message; - private String message; - /** - * @param message2 - * @return - */ - public static Object failure(String message) { - return message; - } + public static Object failure(String message) { + return message; + } - public CommonErrorResponse(String message) { - super(); - this.message = message; - } + public CommonErrorResponse(String message) { + super(); + this.message = message; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/Config.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/Config.java index b0799017..d9076715 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/Config.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/Config.java @@ -13,19 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.common; import org.openo.commontosca.catalog.CatalogAppConfiguration; public class Config { - private static CatalogAppConfiguration configration; + private static CatalogAppConfiguration configration; - public static CatalogAppConfiguration getConfigration() { - return configration; - } + public static CatalogAppConfiguration getConfigration() { + return configration; + } - public static void setConfigration(CatalogAppConfiguration config) { - configration = config; - } + public static void setConfigration(CatalogAppConfiguration config) { + configration = config; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/DateTimeUtil.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/DateTimeUtil.java index 41c38672..039aa25b 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/DateTimeUtil.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/DateTimeUtil.java @@ -13,21 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.common; import java.text.SimpleDateFormat; import java.util.Date; public class DateTimeUtil { - public static String getCurrentTime() { - return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()); - } + public static String getCurrentTime() { + return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()); + } - public static String getFormatTime(Date date) { - return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date); - } + public static String getFormatTime(Date date) { + return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date); + } - public static String getFormatTime(Date date, String format) { - return new SimpleDateFormat(format).format(date); - } + public static String getFormatTime(Date date, String format) { + return new SimpleDateFormat(format).format(date); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/EnumUploadStatus.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/EnumUploadStatus.java index 0c811bde..ab748253 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/EnumUploadStatus.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/EnumUploadStatus.java @@ -13,8 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.common; public enum EnumUploadStatus { - Create_Directory_Success, Create_Directory_Fail, File_Exist, Upload_From_Break_Success, Upload_From_Break_Failed, Upload_New_File_Success, Upload_New_File_Failed + Create_Directory_Success, Create_Directory_Fail, File_Exist, + Upload_From_Break_Success, Upload_From_Break_Failed, Upload_New_File_Success, + Upload_New_File_Failed } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/FileUtil.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/FileUtil.java index ce90f34c..a3370062 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/FileUtil.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/FileUtil.java @@ -13,8 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.common; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; @@ -26,152 +30,157 @@ import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; public final class FileUtil { - public static final Logger LOG = LoggerFactory.getLogger(FileUtil.class); + public static final Logger LOG = LoggerFactory.getLogger(FileUtil.class); - private static final int BUFFER_SIZE = 2 * 1024 * 1024; + private static final int BUFFER_SIZE = 2 * 1024 * 1024; - private static final int TRY_COUNT = 3; + private static final int TRY_COUNT = 3; - private FileUtil() { + private FileUtil() { - } + } - /** - * create dir - * - * @param dir - */ - public static boolean createDirectory(String dir) { - File folder = new File(dir); - int tryCount = 0; - while (tryCount < TRY_COUNT) { - tryCount++; - if (!folder.exists() && !folder.mkdirs()) { - continue; - } else { - return true; - } - } - return folder.exists(); + /** + * create dir. + * @param dir dir to create + * @return boolean + */ + public static boolean createDirectory(String dir) { + File folder = new File(dir); + int tryCount = 0; + while (tryCount < TRY_COUNT) { + tryCount++; + if (!folder.exists() && !folder.mkdirs()) { + continue; + } else { + return true; + } } - public static boolean deleteFile(File file) { - String hintInfo = file.isDirectory() ? "dir " : "file "; - boolean isFileDeleted = file.delete(); - boolean isFileExist = file.exists(); - if (!isFileExist) { - if (isFileDeleted) { - LOG.info("delete " + hintInfo + file.getAbsolutePath()); - } else { - isFileDeleted = true; - LOG.info("file not exist. no need delete " + hintInfo + file.getAbsolutePath()); - } - } else { - LOG.info("fail to delete " + hintInfo + file.getAbsolutePath()); - } - return isFileDeleted; + return folder.exists(); + } + + /** + * delete file. + * @param file the file to delete + * @return boolean + */ + public static boolean deleteFile(File file) { + String hintInfo = file.isDirectory() ? "dir " : "file "; + boolean isFileDeleted = file.delete(); + boolean isFileExist = file.exists(); + if (!isFileExist) { + if (isFileDeleted) { + LOG.info("delete " + hintInfo + file.getAbsolutePath()); + } else { + isFileDeleted = true; + LOG.info("file not exist. no need delete " + hintInfo + file.getAbsolutePath()); + } + } else { + LOG.info("fail to delete " + hintInfo + file.getAbsolutePath()); } - - /** - * unzip zip file - * - * @param zipFileName - * @param unzip dir - * @throws IOException - */ - public static ArrayList unzip(String zipFileName, String extPlace) throws IOException { - ZipFile zipFile = null; - ArrayList unzipFileNams = new ArrayList(); - + return isFileDeleted; + } + + + /** + * unzip zip file. + * @param zipFileName file name to zip + * @param extPlace extPlace + * @return unzip file name + * @throws IOException e1 + */ + public static ArrayList unzip(String zipFileName, String extPlace) throws IOException { + ZipFile zipFile = null; + ArrayList unzipFileNams = new ArrayList(); + + try { + zipFile = new ZipFile(zipFileName); + Enumeration fileEn = zipFile.entries(); + byte[] buffer = new byte[BUFFER_SIZE]; + + while (fileEn.hasMoreElements()) { + InputStream input = null; + BufferedOutputStream bos = null; try { - zipFile = new ZipFile(zipFileName); - Enumeration fileEn = zipFile.entries(); - byte[] buffer = new byte[BUFFER_SIZE]; - - while (fileEn.hasMoreElements()) { - InputStream input = null; - BufferedOutputStream bos = null; - try { - ZipEntry entry = (ZipEntry) fileEn.nextElement(); - if (entry.isDirectory()) { - continue; - } - - input = zipFile.getInputStream(entry); - File file = new File(extPlace, entry.getName()); - if (!file.getParentFile().exists()) { - createDirectory(file.getParentFile().getAbsolutePath()); - } - - bos = new BufferedOutputStream(new FileOutputStream(file)); - while (true) { - int length = input.read(buffer); - if (length == -1) { - break; - } - bos.write(buffer, 0, length); - } - unzipFileNams.add(file.getAbsolutePath()); - } finally { - closeOutputStream(bos); - closeInputStream(input); - } + ZipEntry entry = (ZipEntry) fileEn.nextElement(); + if (entry.isDirectory()) { + continue; + } + + input = zipFile.getInputStream(entry); + File file = new File(extPlace, entry.getName()); + if (!file.getParentFile().exists()) { + createDirectory(file.getParentFile().getAbsolutePath()); + } + + bos = new BufferedOutputStream(new FileOutputStream(file)); + while (true) { + int length = input.read(buffer); + if (length == -1) { + break; } + bos.write(buffer, 0, length); + } + unzipFileNams.add(file.getAbsolutePath()); } finally { - closeZipFile(zipFile); + closeOutputStream(bos); + closeInputStream(input); } - return unzipFileNams; + } + } finally { + closeZipFile(zipFile); } - - /** - * close InputStream - * - * @param inputStream - */ - private static void closeInputStream(InputStream inputStream) { - try { - if (inputStream != null) { - inputStream.close(); - } - } catch (Exception e) { - LOG.info("close InputStream error!"); - } + return unzipFileNams; + } + + /** + * close InputStream. + * + * @param inputStream the inputstream to close + */ + private static void closeInputStream(InputStream inputStream) { + try { + if (inputStream != null) { + inputStream.close(); + } + } catch (Exception e1) { + LOG.info("close InputStream error!"); } - - /** - * close OutputStream - * - * @param outputStream - */ - private static void closeOutputStream(OutputStream outputStream) { - try { - if (outputStream != null) { - outputStream.close(); - } - } catch (Exception e) { - LOG.info("close OutputStream error!"); - } + } + + /** + * close OutputStream. + * + * @param outputStream the output stream to close + */ + private static void closeOutputStream(OutputStream outputStream) { + try { + if (outputStream != null) { + outputStream.close(); + } + } catch (Exception e1) { + LOG.info("close OutputStream error!"); } - - /** - * close zipFile - * - * @param zipFile - */ - private static void closeZipFile(ZipFile zipFile) { - try { - if (zipFile != null) { - zipFile.close(); - zipFile = null; - } - } catch (IOException e) { - LOG.info("close ZipFile error!"); - } + } + + /** + * close zipFile. + * + * @param zipFile the zipFile to close + */ + private static void closeZipFile(ZipFile zipFile) { + try { + if (zipFile != null) { + zipFile.close(); + zipFile = null; + } + } catch (IOException e1) { + LOG.info("close ZipFile error!"); } + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/FtpClient.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/FtpClient.java index a7a9e37b..589009fe 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/FtpClient.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/FtpClient.java @@ -13,178 +13,200 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.common; +import org.apache.commons.net.ftp.FTP; +import org.apache.commons.net.ftp.FTPClient; +import org.apache.commons.net.ftp.FTPFile; +import org.apache.commons.net.ftp.FTPReply; + import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import org.apache.commons.net.ftp.FTP; -import org.apache.commons.net.ftp.FTPClient; -import org.apache.commons.net.ftp.FTPFile; -import org.apache.commons.net.ftp.FTPReply; + /** - * FTP client user for upload or delete files in ftp client + * FTP client user for upload or delete files in ftp client. */ public class FtpClient { - private FTPClient ftpClient; + private FTPClient ftpClient; - public static final String ZIP = ".zip"; + public static final String ZIP = ".zip"; - public FtpClient(String host, String username, String password, int port) throws Exception { - ftpClient = new FTPClient(); - connect(host, username, password, port); - } + public FtpClient(String host, String username, String password, int port) throws Exception { + ftpClient = new FTPClient(); + connect(host, username, password, port); + } - private void connect(String host, String user, String pwd, int port) throws Exception { - ftpClient.connect(host, port); - if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { - ftpClient.disconnect(); - throw new Exception("Exception in connecting to FTP Server"); - } - ftpClient.login(user, pwd); - ftpClient.setFileType(FTP.BINARY_FILE_TYPE); - ftpClient.enterLocalPassiveMode(); + private void connect(String host, String user, String pwd, int port) throws Exception { + ftpClient.connect(host, port); + if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { + ftpClient.disconnect(); + throw new Exception("Exception in connecting to FTP Server"); } - - public void disconnect() throws Exception { - if (this.ftpClient.isConnected()) { - this.ftpClient.logout(); - this.ftpClient.disconnect(); - } + ftpClient.login(user, pwd); + ftpClient.setFileType(FTP.BINARY_FILE_TYPE); + ftpClient.enterLocalPassiveMode(); + } + + /** + * disconnect to ftp. + * @throws Exception e + */ + public void disconnect() throws Exception { + if (this.ftpClient.isConnected()) { + this.ftpClient.logout(); + this.ftpClient.disconnect(); } - - public void get(String remoteFilePath, String localFilePath) throws IOException { - FileOutputStream fos = new FileOutputStream(localFilePath); - this.ftpClient.retrieveFile(remoteFilePath, fos); - fos.close(); + } + + /** + * get remote file. + * @param remoteFilePath remote file path + * @param localFilePath local file path + * @throws IOException e + */ + public void get(String remoteFilePath, String localFilePath) throws IOException { + FileOutputStream fos = new FileOutputStream(localFilePath); + this.ftpClient.retrieveFile(remoteFilePath, fos); + fos.close(); + } + + public void delete(String filePath) throws IOException { + ftpClient.dele(filePath); + } + + + /** + * upload a file to FTP client. support resuming. + * @param startPosition start position to upload + * @param endPosition end position of upload + * @param inputstream upload inputstream + * @param remote remote path + * @return enum + * @throws IOException e + */ + public EnumUploadStatus upload(int startPosition, int endPosition, InputStream inputstream, + String remote) throws IOException { + // set transfer mode: PassiveMode + ftpClient.enterLocalPassiveMode(); + // set transfer file type: binary + ftpClient.setFileType(FTP.BINARY_FILE_TYPE); + ftpClient.setControlEncoding("GBK"); + String remoteFileName = remote; + if (remote.contains("/")) { + remoteFileName = remote.substring(remote.lastIndexOf("/") + 1); + if (createDirecroty(remote, ftpClient) == EnumUploadStatus.Create_Directory_Fail) { + return EnumUploadStatus.Create_Directory_Fail; + } } - public void delete(String filePath) throws IOException { - ftpClient.dele(filePath); + long lstartPos = 0; + FTPFile[] files = ftpClient.listFiles(new String(remoteFileName.getBytes("GBK"), "iso-8859-1")); + if (files.length == 1) { + lstartPos = files[0].getSize(); + } + if (lstartPos > endPosition) { + return EnumUploadStatus.File_Exist; + } + if (lstartPos < startPosition) { + lstartPos = startPosition; + } else if (lstartPos > startPosition && lstartPos < endPosition) { + lstartPos = startPosition; } - /** - * upload a file to FTP client. support resuming - * - * @param local - * @param remote - * @return - * @throws IOException - */ - public EnumUploadStatus upload(int startPosition, int endPosition, InputStream inputstream, - String remote) throws IOException { - // set transfer mode: PassiveMode - ftpClient.enterLocalPassiveMode(); - // set transfer file type: binary - ftpClient.setFileType(FTP.BINARY_FILE_TYPE); - ftpClient.setControlEncoding("GBK"); - String remoteFileName = remote; - if (remote.contains("/")) { - remoteFileName = remote.substring(remote.lastIndexOf("/") + 1); - if (CreateDirecroty(remote, ftpClient) == EnumUploadStatus.Create_Directory_Fail) { - return EnumUploadStatus.Create_Directory_Fail; - } - } - - long lStartPos = 0; - FTPFile[] files = - ftpClient.listFiles(new String(remoteFileName.getBytes("GBK"), "iso-8859-1")); - if (files.length == 1) { - lStartPos = files[0].getSize(); - } - if (lStartPos > endPosition) { - return EnumUploadStatus.File_Exist; - } - if (lStartPos < startPosition) { - lStartPos = startPosition; - } else if (lStartPos > startPosition && lStartPos < endPosition) { - lStartPos = startPosition; + return uploadFile(remoteFileName, inputstream, ftpClient, lstartPos); + } + + /** + * Create a remote server directory recursively. + * + * @param remote remote directory + * @param ftpClient ftpclient + * @return enum + * @throws IOException e + */ + public EnumUploadStatus createDirecroty(String remote, FTPClient ftpClient) throws IOException { + String directory = remote.substring(0, remote.lastIndexOf("/") + 1); + if (!directory.equalsIgnoreCase("/") + && !ftpClient.changeWorkingDirectory(new String(directory.getBytes("GBK"), "iso-8859-1"))) { + int start = 0; + int end = 0; + if (directory.startsWith("/")) { + start = 1; + } else { + start = 0; + } + end = directory.indexOf("/", start); + while (true) { + String subDirectory = + new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1"); + if (!ftpClient.changeWorkingDirectory(subDirectory)) { + if (ftpClient.makeDirectory(subDirectory)) { + ftpClient.changeWorkingDirectory(subDirectory); + } else { + return EnumUploadStatus.Create_Directory_Fail; + } } - return uploadFile(remoteFileName, inputstream, ftpClient, lStartPos); - } + start = end + 1; + end = directory.indexOf("/", start); - /** - * Create a remote server directory recursively - * - * @param remote - * @param ftpClient - * @return - * @throws IOException - */ - public EnumUploadStatus CreateDirecroty(String remote, FTPClient ftpClient) throws IOException { - String directory = remote.substring(0, remote.lastIndexOf("/") + 1); - if (!directory.equalsIgnoreCase("/") - && !ftpClient.changeWorkingDirectory(new String(directory.getBytes("GBK"), - "iso-8859-1"))) { - int start = 0; - int end = 0; - if (directory.startsWith("/")) { - start = 1; - } else { - start = 0; - } - end = directory.indexOf("/", start); - while (true) { - String subDirectory = - new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1"); - if (!ftpClient.changeWorkingDirectory(subDirectory)) { - if (ftpClient.makeDirectory(subDirectory)) { - ftpClient.changeWorkingDirectory(subDirectory); - } else { - return EnumUploadStatus.Create_Directory_Fail; - } - } - - start = end + 1; - end = directory.indexOf("/", start); - - // check whether all directories are created or not - if (end <= start) { - break; - } - } + // check whether all directories are created or not + if (end <= start) { + break; } - return EnumUploadStatus.Create_Directory_Success; + } } - - /** - * upload file to client - * - * @param remoteFile remote file name - * @param localFile local file name, including absolute path - * @param ftpClient FTPClient class - * @param lStartPos starting position - * @return - * @throws IOException - */ - public EnumUploadStatus uploadFile(String remoteFile, InputStream inputstream, - FTPClient ftpClient, long lStartPos) throws IOException { - OutputStream out = - ftpClient.appendFileStream(new String(remoteFile.getBytes("GBK"), "iso-8859-1")); - if (out == null) { - out = ftpClient.storeFileStream(new String(remoteFile.getBytes("GBK"), "iso-8859-1")); - } - if (lStartPos > 0) { - ftpClient.setRestartOffset(lStartPos); - } - byte[] bytes = new byte[512]; - int c; - while ((c = inputstream.read(bytes, 0, 512)) > 0) { - out.write(bytes, 0, c); - } - out.flush(); - out.close(); - boolean result = ftpClient.completePendingCommand(); - if (lStartPos > 0) { - return result ? EnumUploadStatus.Upload_From_Break_Success - : EnumUploadStatus.Upload_From_Break_Failed; - } else { - return result ? EnumUploadStatus.Upload_New_File_Success - : EnumUploadStatus.Upload_New_File_Failed; - } + return EnumUploadStatus.Create_Directory_Success; + } + + /** + * upload file to client. + * + * @param remoteFile remote file name + * @param localFile local file name including absolute path + * @param ftpClient FTPClient class + * @param lStartPos starting position + * @return enum + * @throws IOException e + */ + /** + * upload file to client. + * @param remoteFile remote file name + * @param inputstream inputstream to upload file + * @param ftpClient ftp client + * @param lstartPos start position + * @return enum + * @throws IOException e + */ + public EnumUploadStatus uploadFile(String remoteFile, InputStream inputstream, + FTPClient ftpClient, long lstartPos) throws IOException { + OutputStream out = + ftpClient.appendFileStream(new String(remoteFile.getBytes("GBK"), "iso-8859-1")); + if (out == null) { + out = ftpClient.storeFileStream(new String(remoteFile.getBytes("GBK"), "iso-8859-1")); + } + if (lstartPos > 0) { + ftpClient.setRestartOffset(lstartPos); + } + byte[] bytes = new byte[512]; + int count; + while ((count = inputstream.read(bytes, 0, 512)) > 0) { + out.write(bytes, 0, count); + } + out.flush(); + out.close(); + boolean result = ftpClient.completePendingCommand(); + if (lstartPos > 0) { + return result ? EnumUploadStatus.Upload_From_Break_Success + : EnumUploadStatus.Upload_From_Break_Failed; + } else { + return result ? EnumUploadStatus.Upload_New_File_Success + : EnumUploadStatus.Upload_New_File_Failed; } + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/HttpServerAddrConfig.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/HttpServerAddrConfig.java index e8f27b56..ccae9adf 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/HttpServerAddrConfig.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/HttpServerAddrConfig.java @@ -13,22 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.common; -/** - * @author 00164331 - * - */ + public class HttpServerAddrConfig { - protected static String httpServerAddress; + protected static String httpServerAddress; - public static String getHttpServerAddress() { - return httpServerAddress; - } + public static String getHttpServerAddress() { + return httpServerAddress; + } - public static void setHttpServerAddress(String httpServerAddress) { - HttpServerAddrConfig.httpServerAddress = httpServerAddress; - } + public static void setHttpServerAddress(String httpServerAddress) { + HttpServerAddrConfig.httpServerAddress = httpServerAddress; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/HttpServerPathConfig.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/HttpServerPathConfig.java index 6a538713..db66f935 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/HttpServerPathConfig.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/HttpServerPathConfig.java @@ -13,20 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.common; -/** - * @author 00164331 - * - */ + public class HttpServerPathConfig { - protected static String httpServerPath; + protected static String httpServerPath; - public static String getHttpServerPath() { - return httpServerPath; - } + public static String getHttpServerPath() { + return httpServerPath; + } - public static void setHttpServerPath(String httpServerPath) { - HttpServerPathConfig.httpServerPath = httpServerPath; - } + public static void setHttpServerPath(String httpServerPath) { + HttpServerPathConfig.httpServerPath = httpServerPath; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/MSBUtil.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/MSBUtil.java deleted file mode 100644 index 357d1943..00000000 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/MSBUtil.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright 2016 [ZTE] and others. - * - * Licensed 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.openo.commontosca.catalog.common; - -/** - * micro-service bus utility class; - * - * @author 10186401 - * - */ -public class MSBUtil { - - public static String getRocBaseUrl() { - return Config.getConfigration().getMsbServerAddr() + getRocApiRootDomain(); - } - - private static String getRocApiRootDomain() { - return "/api/roc/v1"; - } - - public static String getNsocLifecycleBaseUrl() { - return Config.getConfigration().getMsbServerAddr() + getNsocLifeCycleRootDomain(); - } - - private static String getNsocLifeCycleRootDomain() { - return "/api/nsoc/v1"; - } - - public static String getVimBaseUrl() { - return Config.getConfigration().getMsbServerAddr() + getVimRootDomain(); - } - - private static String getVimRootDomain() { - return "/api/vim/v1"; - } - - public static String getPackageUrl() { - return Config.getConfigration().getMsbServerAddr() + "/api/nsoc/v1/csar/"; - } - - public static String getYamlParseBaseUrl() { - return Config.getConfigration().getYamlParseAddr() + "/api/yamlparser/v1"; - } -} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/MsbAddrConfig.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/MsbAddrConfig.java index 5fcf6849..caecbc09 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/MsbAddrConfig.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/MsbAddrConfig.java @@ -13,22 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.common; -/** - * @author 00164331 - * - */ public class MsbAddrConfig { - protected static String msbAddress; + protected static String msbAddress; - public static String getMsbAddress() { - return msbAddress; - } + public static String getMsbAddress() { + return msbAddress; + } - public static void setMsbAddress(String msbAddress) { - MsbAddrConfig.msbAddress = msbAddress; - } + public static void setMsbAddress(String msbAddress) { + MsbAddrConfig.msbAddress = msbAddress; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/MsbUtil.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/MsbUtil.java new file mode 100644 index 00000000..ac2c2c07 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/MsbUtil.java @@ -0,0 +1,56 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.common; + +/** + * micro-service bus utility class. + * + */ +public class MsbUtil { + + public static String getRocBaseUrl() { + return Config.getConfigration().getMsbServerAddr() + getRocApiRootDomain(); + } + + private static String getRocApiRootDomain() { + return "/api/roc/v1"; + } + + public static String getNsocLifecycleBaseUrl() { + return Config.getConfigration().getMsbServerAddr() + getNsocLifeCycleRootDomain(); + } + + private static String getNsocLifeCycleRootDomain() { + return "/api/nsoc/v1"; + } + + public static String getVimBaseUrl() { + return Config.getConfigration().getMsbServerAddr() + getVimRootDomain(); + } + + private static String getVimRootDomain() { + return "/api/vim/v1"; + } + + public static String getPackageUrl() { + return Config.getConfigration().getMsbServerAddr() + "/api/nsoc/v1/csar/"; + } + + public static String getYamlParseBaseUrl() { + return Config.getConfigration().getYamlParseAddr() + "/api/yamlparser/v1"; + } +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/RestUtil.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/RestUtil.java index f754974e..70a53f1f 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/RestUtil.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/RestUtil.java @@ -13,23 +13,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.common; import javax.ws.rs.core.Response; -/** - * @author 00164331 - * - */ + public class RestUtil { - /** - * @param e - * @return - */ - public static Response getRestException(String errorMsg) { - String code = "001"; - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(new CommonErrorResponse(code, errorMsg)).build(); - } + + /** + * get rest exception. + * @param errorMsg error message + * @return Response + */ + public static Response getRestException(String errorMsg) { + String code = "001"; + return Response.status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(new CommonErrorResponse(code, errorMsg)).build(); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/ServiceRegistrer.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/ServiceRegistrer.java index ac85a39d..b83985f2 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/ServiceRegistrer.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/ServiceRegistrer.java @@ -13,86 +13,85 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.common; - - -import java.util.ArrayList; -import java.util.Iterator; +package org.openo.commontosca.catalog.common; import org.openo.commontosca.catalog.externalservice.msb.MicroserviceBusConsumer; import org.openo.commontosca.catalog.externalservice.msb.ServiceRegisterEntity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * @author 10159474 - * - */ -public class ServiceRegistrer implements Runnable { - private final ArrayList serviceEntityList = - new ArrayList(); - private static final Logger LOG = LoggerFactory.getLogger(ServiceRegistrer.class); +import java.util.ArrayList; +import java.util.Iterator; - public ServiceRegistrer() { - initServiceEntity(); - } +public class ServiceRegistrer implements Runnable { + private final ArrayList serviceEntityList = + new ArrayList(); + private static final Logger LOG = LoggerFactory.getLogger(ServiceRegistrer.class); - @Override - public void run() { - LOG.info("start microservice register"); - boolean flag = false; - ServiceRegisterEntity entity = new ServiceRegisterEntity(); - int retry = 0; - while (retry < 1000 && serviceEntityList.size() > 0) { - Iterator it = serviceEntityList.iterator(); - while (it.hasNext()) { - entity = it.next(); - LOG.info("start" + entity.getServiceName() + " catalog microservice register.retry:" - + retry); - flag = MicroserviceBusConsumer.registerService(entity); - if (flag == false) { - LOG.warn(entity.getServiceName() - + " microservice register failed, sleep 30S and try again."); - ThreadSleep(30000); - } else { - LOG.info(entity.getServiceName() + " microservice register success!"); - it.remove(); - } - } - retry++; + public ServiceRegistrer() { + initServiceEntity(); + } + @Override + public void run() { + LOG.info("start microservice register"); + boolean flag = false; + ServiceRegisterEntity entity = new ServiceRegisterEntity(); + int retry = 0; + while (retry < 1000 && serviceEntityList.size() > 0) { + Iterator it = serviceEntityList.iterator(); + while (it.hasNext()) { + entity = it.next(); + LOG.info("start" + entity.getServiceName() + " catalog microservice register.retry:" + + retry); + flag = MicroserviceBusConsumer.registerService(entity); + if (flag == false) { + LOG.warn(entity.getServiceName() + + " microservice register failed, sleep 30S and try again."); + threadSleep(30000); + } else { + LOG.info(entity.getServiceName() + " microservice register success!"); + it.remove(); } - LOG.info("catalog microservice register end."); + } + retry++; } + LOG.info("catalog microservice register end."); - private void ThreadSleep(int second) { - LOG.info("start sleep ...."); - try { - Thread.sleep(second); - } catch (InterruptedException e) { - LOG.error("thread sleep error.errorMsg:" + e.getMessage()); - } - LOG.info("sleep end ."); - } + } - private void initServiceEntity() { - ServiceRegisterEntity catalogEntity = new ServiceRegisterEntity(); - catalogEntity.setServiceName("catalog"); - catalogEntity.setProtocol("REST"); - catalogEntity.setVersion("v1"); - catalogEntity.setUrl("/openoapi/catalog/v1"); - catalogEntity.setSingleNode(null, "8200", 0); - catalogEntity.setVisualRange("1"); - serviceEntityList.add(catalogEntity); - ServiceRegisterEntity httpServiceEntity = new ServiceRegisterEntity(); - httpServiceEntity.setServiceName("/files/catalog-http"); - httpServiceEntity.setProtocol("REST"); - httpServiceEntity.setVersion("v1"); - httpServiceEntity.setUrl("/"); - httpServiceEntity.setSingleNode(null, "8201", 0); - httpServiceEntity.setVisualRange("1"); - serviceEntityList.add(httpServiceEntity); + /** + * sleep thread. + * @param second sleep second + */ + private void threadSleep(int seconds) { + LOG.info("start sleep ...."); + try { + Thread.sleep(seconds); + } catch (InterruptedException e1) { + LOG.error("thread sleep error.errorMsg:" + e1.getMessage()); } + LOG.info("sleep end ."); + } + + private void initServiceEntity() { + ServiceRegisterEntity catalogEntity = new ServiceRegisterEntity(); + catalogEntity.setServiceName("catalog"); + catalogEntity.setProtocol("REST"); + catalogEntity.setVersion("v1"); + catalogEntity.setUrl("/openoapi/catalog/v1"); + catalogEntity.setSingleNode(null, "8200", 0); + catalogEntity.setVisualRange("1"); + serviceEntityList.add(catalogEntity); + ServiceRegisterEntity httpServiceEntity = new ServiceRegisterEntity(); + httpServiceEntity.setServiceName("/files/catalog-http"); + httpServiceEntity.setProtocol("REST"); + httpServiceEntity.setVersion("v1"); + httpServiceEntity.setUrl("/"); + httpServiceEntity.setSingleNode(null, "8201", 0); + httpServiceEntity.setVisualRange("1"); + serviceEntityList.add(httpServiceEntity); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/ToolUtil.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/ToolUtil.java index 34159585..57e04baf 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/ToolUtil.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/ToolUtil.java @@ -13,8 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.common; +import com.google.gson.Gson; + +import org.openo.commontosca.catalog.model.common.EnumToscaNodeTypeDefinition; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -25,269 +32,360 @@ import java.util.ArrayList; import java.util.Collection; import java.util.UUID; -import org.openo.commontosca.catalog.model.common.EnumToscaNodeTypeDefinition; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.google.gson.Gson; /** - * common utility class - * - * @author 10186401 + * common utility class. * */ public class ToolUtil { - private static final Logger LOG = LoggerFactory.getLogger(ToolUtil.class); + private static final Logger LOG = LoggerFactory.getLogger(ToolUtil.class); - public final static String CATALOGUE_CSAR_DIR_NAME = "csar"; + public static final String CATALOGUE_CSAR_DIR_NAME = "csar"; - public final static String CATALOGUE_IMAGE_DIR_NAME = "image"; + public static final String CATALOGUE_IMAGE_DIR_NAME = "image"; - public static final int FILE_PERCENT = 1024 * 1024; // 1M - - public static boolean isEmptyString(String val) { - return val == null || "".equals(val); - } - - public static boolean isTrimedEmptyString(String val) { - return val == null || "".equals(val.trim()); - } + public static final int FILE_PERCENT = 1024 * 1024; // 1M - public static boolean isTrimedEmptyArray(String[] val) { - return val == null || val.length == 0; - } + public static boolean isEmptyString(String val) { + return val == null || "".equals(val); + } - public static String[] TrimedStringArray(String[] val) { - if (isTrimedEmptyArray(val)) { - return val; - } + public static boolean isTrimedEmptyString(String val) { + return val == null || "".equals(val.trim()); + } - String[] rets = new String[val.length]; - for (int i = 0; i < val.length; i++) { - rets[i] = val[i].trim(); - } - return rets; - } + public static boolean isTrimedEmptyArray(String[] val) { + return val == null || val.length == 0; + } - public static boolean isEmptyCollection(Collection coll) { - return null == coll || coll.isEmpty(); + /** + * trimed string. + * + * @param val string array to trim + * @return String[] + */ + public static String[] trimedStringArray(String[] val) { + if (isTrimedEmptyArray(val)) { + return val; } - /** - * store chunk file to local temp directory - * - * @param dirName - * @param fileName - * @param uploadedInputStream - * @return - * @throws IOException - */ - public static String storeChunkFileInLocal(String dirName, String fileName, - InputStream uploadedInputStream) throws IOException { - File tmpDir = new File(dirName); - LOG.info("tmpdir = " + File.separator + dirName); - if (!tmpDir.exists()) { - tmpDir.mkdirs(); - } - File file = new File(tmpDir + File.separator + fileName); - OutputStream os = null; - try { - int read = 0; - byte[] bytes = new byte[1024]; - os = new FileOutputStream(file, true); - while ((read = uploadedInputStream.read(bytes)) != -1) { - os.write(bytes, 0, read); - } - os.flush(); - return file.getAbsolutePath(); - } finally { - if (os != null) { - os.close(); - } - } + String[] rets = new String[val.length]; + for (int i = 0; i < val.length; i++) { + rets[i] = val[i].trim(); } - - public static String getTempDir(String dirName, String fileName) { - // File tmpDir = new File(File.separator + dirName); - return Class.class.getClass().getResource("/").getPath() + dirName + File.separator + fileName.replace(".csar", ""); + return rets; + } + + public static boolean isEmptyCollection(Collection coll) { + return null == coll || coll.isEmpty(); + } + + /** + * store chunk file to local temp directory. + * + * @param dirName directory name + * @param fileName file name + * @param uploadedInputStream upload input stream + * @return String + * @throws IOException e + */ + public static String storeChunkFileInLocal(String dirName, String fileName, + InputStream uploadedInputStream) throws IOException { + File tmpDir = new File(dirName); + LOG.info("tmpdir = " + File.separator + dirName); + if (!tmpDir.exists()) { + tmpDir.mkdirs(); } - - public static String getUnzipDir(String dirName) { - File tmpDir = new File(File.separator + dirName); - return tmpDir.getAbsolutePath().replace(".csar", ""); + File file = new File(tmpDir + File.separator + fileName); + OutputStream os = null; + try { + int read = 0; + byte[] bytes = new byte[1024]; + os = new FileOutputStream(file, true); + while ((read = uploadedInputStream.read(bytes)) != -1) { + os.write(bytes, 0, read); + } + os.flush(); + return file.getAbsolutePath(); + } finally { + if (os != null) { + os.close(); + } } - - public static boolean deleteFile(String dirName, String fileName) { - File tmpDir = new File(getCataloguePath() + File.separator + dirName); - if (!tmpDir.exists()) { - return true; - } - File file = new File(tmpDir.getAbsolutePath() + File.separator + fileName); - if (file.exists()) { - return file.delete(); - } - return true; + } + + /** + * get temp dirctory when upload package. + * + * @param dirName temp directory name + * @param fileName package name + * @return String + */ + public static String getTempDir(String dirName, String fileName) { + // File tmpDir = new File(File.separator + dirName); + return Class.class.getClass().getResource("/").getPath() + dirName + File.separator + + fileName.replace(".csar", ""); + } + + public static String getUnzipDir(String dirName) { + File tmpDir = new File(File.separator + dirName); + return tmpDir.getAbsolutePath().replace(".csar", ""); + } + + /** + * delete file. + * + * @param dirName the directory of file + * @param fileName file name + * @return boolean + */ + public static boolean deleteFile(String dirName, String fileName) { + File tmpDir = new File(getCataloguePath() + File.separator + dirName); + if (!tmpDir.exists()) { + return true; } - - public static String getCataloguePath() { - return Config.getConfigration().getCataloguePath(); + File file = new File(tmpDir.getAbsolutePath() + File.separator + fileName); + if (file.exists()) { + return file.delete(); } - - public static String getCatalogueCsarPath() { - return getCataloguePath() + File.separator + CATALOGUE_CSAR_DIR_NAME; + return true; + } + + public static String getCataloguePath() { + return Config.getConfigration().getCataloguePath(); + } + + public static String getCatalogueCsarPath() { + return getCataloguePath() + File.separator + CATALOGUE_CSAR_DIR_NAME; + } + + public static String getCatalogueImagePath() { + return getCataloguePath() + File.separator + CATALOGUE_IMAGE_DIR_NAME; + } + + /** + * get file size. + * + * @param file file which to get the size + * @param fileUnit file unit + * @return String file size + */ + public static String getFileSize(File file, int fileUnit) { + String fileSize = ""; + DecimalFormat format = new DecimalFormat("#0.00"); + if (file.exists()) { + fileSize = format.format((double) file.length() / fileUnit) + "M"; } - - public static String getCatalogueImagePath() { - return getCataloguePath() + File.separator + CATALOGUE_IMAGE_DIR_NAME; + return fileSize; + } + + public static String formatFileSize(double fileLength, int fileUnit) { + DecimalFormat format = new DecimalFormat("#0.00"); + return format.format(fileLength / fileUnit) + "M"; + } + + /** + * get file size by content. + * + * @param contentRange content range + * @return String + */ + public static String getFileSizeByContent(String contentRange) { + String size = + contentRange.substring(contentRange.indexOf("/") + 1, contentRange.length()).trim(); + return formatFileSize(Double.parseDouble(size), FILE_PERCENT); + } + + /** + * fix package format. + * + * @param csarId package ID + * @return String + */ + public static String formatCsar(String csarId) { + String result = csarId; + if (csarId.indexOf(".csar") < 0) { + result += ".csar"; } - - public static String getFileSize(File file, int fileUnit) { - String fileSize = ""; - DecimalFormat format = new DecimalFormat("#0.00"); - if (file.exists()) { - fileSize = format.format((double) file.length() / fileUnit) + "M"; - } - return fileSize; + return result; + } + + /** + * judge the package format is xml or not. + * + * @param fileLocation package location + * @param unzipDir the directory where the package unzip to + * @return boolean + * @throws IOException e + */ + public static boolean isXmlCsar(String fileLocation, String unzipDir) throws IOException { + String tempfolder = unzipDir; + ArrayList unzipFiles = FileUtil.unzip(fileLocation, tempfolder); + if (unzipFiles.isEmpty()) { + return true; } - - public static String formatFileSize(double fileLength, int fileUnit) { - DecimalFormat format = new DecimalFormat("#0.00"); - return format.format(fileLength / fileUnit) + "M"; - } - - public static String getFileSizeByContent(String contentRange) { - String size = - contentRange.substring(contentRange.indexOf("/") + 1, contentRange.length()).trim(); - return formatFileSize(Double.parseDouble(size), FILE_PERCENT); - } - - public static String formatCsar(String csarId) { - String result = csarId; - if (csarId.indexOf(".csar") < 0) { - result += ".csar"; - } - return result; - } - - public static boolean isXMLCsar(String fileLocation, String unzipDir) throws IOException { - String tempfolder = unzipDir; - ArrayList unzipFiles = FileUtil.unzip(fileLocation, tempfolder); - if (unzipFiles.isEmpty()) { - return true; - } - for (String unzipFile : unzipFiles) { - if (isYamlFile(new File(unzipFile))) { - return false; - } - } - return true; - } - - - public static boolean deleteDir(File dir) { - if (dir.isDirectory()) { - String[] children = dir.list(); - for (int i = 0; i < children.length; i++) { - boolean success = deleteDir(new File(dir, children[i])); - if (!success) { - return false; - } - } - } - return dir.delete(); - } - - // public static boolean unZipCsar(String fileLocation) throws IOException { - // String tempfolder=System.getProperty("java.io.tmpdir"); - // ArrayList unzipFiles = FileUtil.unzip(fileLocation, tempfolder); - // if(unzipFiles.isEmpty()){ - // return true; - // } - // } - - public static boolean isYamlFile(File file) { - if (!file.isDirectory() && file.getName().indexOf(".yaml") != -1) { - return true; - } + for (String unzipFile : unzipFiles) { + if (isYamlFile(new File(unzipFile))) { return false; + } } - - public static String removeCSARSuffix(String csarName) { - return csarName.replaceAll(".csar", ""); - } - - public static String addCSARSuffix(String csarName) { - if (csarName.indexOf(".csar") == -1) { - return csarName + ".csar"; + return true; + } + + + /** + * delete the file and file directory. + * + * @param dir file + * @return boolean + */ + public static boolean deleteDir(File dir) { + if (dir.isDirectory()) { + String[] children = dir.list(); + for (int i = 0; i < children.length; i++) { + boolean success = deleteDir(new File(dir, children[i])); + if (!success) { + return false; } - return csarName; + } } - - public static boolean isVnfNodetype(String type) { - if (type.toLowerCase().contains(EnumToscaNodeTypeDefinition.VNFC.getName().toLowerCase())) { - return false; - } - return type.toLowerCase().contains(EnumToscaNodeTypeDefinition.VNF.getName().toLowerCase()); + return dir.delete(); + } + + // public static boolean unZipCsar(String fileLocation) throws IOException { + // String tempfolder=System.getProperty("java.io.tmpdir"); + // ArrayList unzipFiles = FileUtil.unzip(fileLocation, tempfolder); + // if(unzipFiles.isEmpty()){ + // return true; + // } + // } + + /** + * judge the file's format is yaml or not. + * + * @param file file to judge + * @return boolean + */ + public static boolean isYamlFile(File file) { + if (!file.isDirectory() && file.getName().indexOf(".yaml") != -1) { + return true; } - - public static String processFileName(String fileName) { - int index = fileName.indexOf(".zip"); - if (index == -1) { - return fileName; - } - - return addCSARSuffix(fileName.replaceAll(".zip", "")); + return false; + } + + /** + * remove the csar suffix. + * + * @param csarName package name + * @return String + */ + public static String removeCsarSuffix(String csarName) { + return csarName.replaceAll(".csar", ""); + } + + /** + * add the csar fuffix. + * + * @param csarName package name + * @return String + */ + public static String addCsarSuffix(String csarName) { + if (csarName.indexOf(".csar") == -1) { + return csarName + ".csar"; } - - public static String objectToString(Object o) { - if (o == null) - return ""; - Gson gson = new Gson(); - String str = gson.toJson(o); - return str; + return csarName; + } + + /** + * judge whether the type is vnf node type. + * + * @param type type + * @return boolean + */ + public static boolean isVnfNodetype(String type) { + if (type.toLowerCase().contains(EnumToscaNodeTypeDefinition.VNFC.getName().toLowerCase())) { + return false; } - - public static String generateId() { - return UUID.randomUUID().toString(); + return type.toLowerCase().contains(EnumToscaNodeTypeDefinition.VNF.getName().toLowerCase()); + } + + /** + * process file name. + * + * @param fileName file's name + * @return String + */ + public static String processFileName(String fileName) { + int index = fileName.indexOf(".zip"); + if (index == -1) { + return fileName; } - public static String formatFileSize(long fileSize) { - long kb = 1024; - long mb = kb * 1024; - long gb = mb * 1024; - - if (fileSize >= gb) { - return String.format("%.1f GB", (float) fileSize / gb); - } else if (fileSize >= mb) { - float f = (float) fileSize / mb; - return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f); - } else if (fileSize >= kb) { - float f = (float) fileSize / kb; - return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f); - } else - return String.format("%d B", fileSize); + return addCsarSuffix(fileName.replaceAll(".zip", "")); + } + + /** + * exchange object to string. + * + * @param obj object + * @return String + */ + public static String objectToString(Object obj) { + if (obj == null) { + return ""; } - - - /** - * - * @param jsonString - * @param tClass - * @return - */ - public static T fromJson(String jsonString, Class tClass) { - Gson gson = new Gson(); - return gson.fromJson(jsonString, tClass); - } - - /** - * - * @param t - * @return - */ - public static String toJson(T t) { - Gson gson = new Gson(); - return gson.toJson(t); + Gson gson = new Gson(); + String str = gson.toJson(obj); + return str; + } + + public static String generateId() { + return UUID.randomUUID().toString(); + } + + /** + * get the size format according file size. + * + * @param fileSize file size + * @return size format + */ + public static String getFormatFileSize(long fileSize) { + long kb = 1024; + long mb = kb * 1024; + long gb = mb * 1024; + + if (fileSize >= gb) { + return String.format("%.1f GB", (float) fileSize / gb); + } else if (fileSize >= mb) { + float fi = (float) fileSize / mb; + return String.format(fi > 100 ? "%.0f MB" : "%.1f MB", fi); + } else if (fileSize >= kb) { + float fi = (float) fileSize / kb; + return String.format(fi > 100 ? "%.0f KB" : "%.1f KB", fi); + } else { + return String.format("%d B", fileSize); } + } + + /** + * get gson from json. + * @param jsonString json string + * @param templateClass template class + * @return Template + */ + public static T fromJson(String jsonString, Class templateClass) { + Gson gson = new Gson(); + return gson.fromJson(jsonString, templateClass); + } + + /** + * gson to json. + * @param template class name + * @return String + */ + public static String toJson(T template) { + Gson gson = new Gson(); + return gson.toJson(template); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/ZipCompressor.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/ZipCompressor.java index 8d24eac9..e202e706 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/ZipCompressor.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/ZipCompressor.java @@ -13,8 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.common; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; @@ -24,96 +28,96 @@ import java.util.zip.CheckedOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -/** - * @author 00164331 - * - */ public class ZipCompressor { - public static final Logger LOG = LoggerFactory.getLogger(ZipCompressor.class); - static final int BUFFER = 8192; + public static final Logger LOG = LoggerFactory.getLogger(ZipCompressor.class); + static final int BUFFER = 8192; - private File zipFile; + private File zipFile; - public ZipCompressor(String pathName) { - zipFile = new File(pathName); - } + public ZipCompressor(String pathName) { + zipFile = new File(pathName); + } - public void compress(String... pathName) { - ZipOutputStream out = null; - try { - FileOutputStream fileOutputStream = new FileOutputStream(zipFile); - CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, new CRC32()); - out = new ZipOutputStream(cos); - String basedir = ""; - for (int i = 0; i < pathName.length; i++) { - compress(new File(pathName[i]), out, basedir); - } - out.close(); - } catch (Exception e) { - throw new RuntimeException(e); - } + /** + * compress file according several path. + * @param pathName file path name + */ + public void compress(String... pathName) { + ZipOutputStream out = null; + try { + FileOutputStream fileOutputStream = new FileOutputStream(zipFile); + CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, new CRC32()); + out = new ZipOutputStream(cos); + String basedir = ""; + for (int i = 0; i < pathName.length; i++) { + compress(new File(pathName[i]), out, basedir); + } + out.close(); + } catch (Exception e1) { + throw new RuntimeException(e1); } + } - public void compress(String srcPathName) { - File file = new File(srcPathName); - if (!file.exists()) - throw new RuntimeException(srcPathName + "不存在!"); - try { - FileOutputStream fileOutputStream = new FileOutputStream(zipFile); - CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, new CRC32()); - ZipOutputStream out = new ZipOutputStream(cos); - String basedir = ""; - compress(file, out, basedir); - out.close(); - } catch (Exception e) { - throw new RuntimeException(e); - } + /** + * compress file according file path. + * @param srcPathName file path name + */ + public void compress(String srcPathName) { + File file = new File(srcPathName); + if (!file.exists()) { + throw new RuntimeException(srcPathName + "not exist!"); } + try { + FileOutputStream fileOutputStream = new FileOutputStream(zipFile); + CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, new CRC32()); + ZipOutputStream out = new ZipOutputStream(cos); + String basedir = ""; + compress(file, out, basedir); + out.close(); + } catch (Exception e1) { + throw new RuntimeException(e1); + } + } - private void compress(File file, ZipOutputStream out, String basedir) { - /* 判断是目录还是文件 */ - if (file.isDirectory()) { - System.out.println("压缩:" + basedir + file.getName()); - this.compressDirectory(file, out, basedir); - } else { - System.out.println("压缩:" + basedir + file.getName()); - this.compressFile(file, out, basedir); - } + private void compress(File file, ZipOutputStream out, String basedir) { + if (file.isDirectory()) { + System.out.println("compress:" + basedir + file.getName()); + this.compressDirectory(file, out, basedir); + } else { + System.out.println("compress:" + basedir + file.getName()); + this.compressFile(file, out, basedir); } + } - /** 压缩一个目录 */ - private void compressDirectory(File dir, ZipOutputStream out, String basedir) { - if (!dir.exists()) - return; + private void compressDirectory(File dir, ZipOutputStream out, String basedir) { + if (!dir.exists()) { + return; + } - File[] files = dir.listFiles(); - for (int i = 0; i < files.length; i++) { - /* 递归 */ - compress(files[i], out, basedir + dir.getName() + "/"); - } + File[] files = dir.listFiles(); + for (int i = 0; i < files.length; i++) { + compress(files[i], out, basedir + dir.getName() + "/"); } + } - /** 压缩一个文件 */ - private void compressFile(File file, ZipOutputStream out, String basedir) { - if (!file.exists()) { - return; - } - try { - BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); - ZipEntry entry = new ZipEntry(basedir + file.getName()); - out.putNextEntry(entry); - int count; - byte data[] = new byte[BUFFER]; - while ((count = bis.read(data, 0, BUFFER)) != -1) { - out.write(data, 0, count); - } - bis.close(); - } catch (Exception e) { - throw new RuntimeException(e); - } + private void compressFile(File file, ZipOutputStream out, String basedir) { + if (!file.exists()) { + return; + } + try { + byte data[] = new byte[BUFFER]; + BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); + ZipEntry entry = new ZipEntry(basedir + file.getName()); + out.putNextEntry(entry); + int count; + while ((count = bis.read(data, 0, BUFFER)) != -1) { + out.write(data, 0, count); + } + bis.close(); + } catch (Exception e1) { + throw new RuntimeException(e1); } + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/common/CatalogResuorceType.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/common/CatalogResuorceType.java index 6a12ffef..1f1c47e5 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/common/CatalogResuorceType.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/common/CatalogResuorceType.java @@ -13,15 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.common; -/** - ** @author 10159474 - */ + public enum CatalogResuorceType { - SERVICETEMPLATE, PACKAGE, NODETEMPLATE, TEMPLATE, SERVICETEMPLATEMAPPING; + SERVICETEMPLATE, PACKAGE, NODETEMPLATE, TEMPLATE, SERVICETEMPLATEMAPPING; - public static CatalogResuorceType getType(String type) { - return valueOf(type); - } + public static CatalogResuorceType getType(String type) { + return valueOf(type); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/common/Parameters.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/common/Parameters.java index ddd414b8..271f9f48 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/common/Parameters.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/common/Parameters.java @@ -13,12 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.common; -/** - * *@author 10159474 - * - */ public enum Parameters { - oid, name, provider, version, deletionPending, type, status, csarId, vendor, serviceTemplateId, nodeTemplateId, mappingId, nodeType; + oid, name, provider, version, deletionPending, + type, status, csarId, vendor, serviceTemplateId, + nodeTemplateId, mappingId, nodeType; } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/BaseDao.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/BaseDao.java index f6b4d48b..455e9ddd 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/BaseDao.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/BaseDao.java @@ -13,10 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.dao; -import java.util.List; -import java.util.Map; +import io.dropwizard.hibernate.AbstractDAO; +import io.dropwizard.util.Generics; import org.hibernate.Criteria; import org.hibernate.HibernateException; @@ -27,168 +28,192 @@ import org.hibernate.criterion.Restrictions; import org.openo.commontosca.catalog.db.exception.CatalogResourceException; import org.openo.commontosca.catalog.db.util.HqlFactory; -import io.dropwizard.hibernate.AbstractDAO; -import io.dropwizard.util.Generics; +import java.util.List; +import java.util.Map; + /** - * a base class for Hibernate DAO classes + * a base class for Hibernate DAO classes. provide the common methods to create,delete,update and + * query data. * - * provide the common methods to create,delete,update and query data - * - * *@author 10159474 - * - * @param */ public class BaseDao extends AbstractDAO { - public BaseDao(SessionFactory sessionFactory) { - super(sessionFactory); - this.sessionFactory = sessionFactory; - this.entityClass = Generics.getTypeParameter(getClass()); - } - - public String[] excludeProperties; - private SessionFactory sessionFactory; - protected Session session; - private final Class entityClass; - - @Override - protected Session currentSession() { - return this.session; + /** + * base dao constructor. + * + * @param sessionFactory session factory + */ + public BaseDao(SessionFactory sessionFactory) { + super(sessionFactory); + this.sessionFactory = sessionFactory; + this.entityClass = Generics.getTypeParameter(getClass()); + } + + public String[] excludeProperties; + private SessionFactory sessionFactory; + protected Session session; + private final Class entityClass; + + @Override + protected Session currentSession() { + return this.session; + } + + /** + * update data. + * + * @param data the object to update + * @throws CatalogResourceException e1 + */ + public void update(T data, String filter) throws CatalogResourceException { + try { + String hql = HqlFactory.getUpdateHql(data, excludeProperties, filter); + beginTransaction(); + Query query = this.session.createQuery(hql); + query.executeUpdate(); + closeTransaction(); + } catch (Exception e1) { + transactionRollBack(); + throw new CatalogResourceException("error while updating data.errorMsg:" + e1.getMessage(), + e1); + } finally { + closeSession(); } - - /** - * @param data the object to update - * @throws CatalogResourceException - */ - public void update(T data, String filter) throws CatalogResourceException { - try { - String hql = HqlFactory.getUpdateHql(data, excludeProperties, filter); - beginTransaction(); - Query query = this.session.createQuery(hql); - query.executeUpdate(); - closeTransaction(); - } catch (Exception e) { - transactionRollBack(); - throw new CatalogResourceException("error while updating data.errorMsg:" - + e.getMessage(), e); - } finally { - closeSession(); - } + } + + /** + * delete data. + * + * @param data the object to delete + * @throws CatalogResourceException e1 + */ + public void delete(T data) throws CatalogResourceException { + try { + beginTransaction(); + this.session.delete(data); + closeTransaction(); + } catch (Exception e1) { + transactionRollBack(); + throw new CatalogResourceException("error while deleting data.errorMsg:" + e1.getMessage(), + e1); + } finally { + closeSession(); } - - /** - * @param data the object to delete - * @throws CatalogResourceException - */ - public void delete(T data) throws CatalogResourceException { - try { - beginTransaction(); - this.session.delete(data); - closeTransaction(); - } catch (Exception e) { - transactionRollBack(); - throw new CatalogResourceException("error while deleting data.errorMsg:" - + e.getMessage(), e); - } finally { - closeSession(); - } + } + + /** + * create data. + * + * @param data the object to create + * @return data + * @throws CatalogResourceException e1 + */ + public T create(T data) throws CatalogResourceException { + try { + beginTransaction(); + session.save(data); + closeTransaction(); + } catch (HibernateException e1) { + transactionRollBack(); + throw new CatalogResourceException("error while creating data.errorMsg:" + e1.getMessage(), + e1); + } finally { + closeSession(); } - - /** - * @param data the object to create - * @return - * @throws CatalogResourceException - */ - public T create(T data) throws CatalogResourceException { - try { - beginTransaction(); - session.save(data); - closeTransaction(); - } catch (HibernateException e) { - transactionRollBack(); - throw new CatalogResourceException("error while creating data.errorMsg:" - + e.getMessage(), e); - } finally { - closeSession(); - } - return data; + return data; + } + + /** + * union query. + * + * @param unionHql union hql + * @return list + * @throws CatalogResourceException e1 + */ + public List unionQuery(String unionHql) throws CatalogResourceException { + List data; + try { + beginTransaction(); + Query query = this.session.createQuery(unionHql); + data = query.list(); + closeTransaction(); + } catch (Exception e1) { + transactionRollBack(); + throw new CatalogResourceException("error while union query data.errorMsg:" + e1.getMessage(), + e1); + } finally { + closeSession(); } - - public List unionQuery(String unionHql) throws CatalogResourceException { - List data; - try { - beginTransaction(); - Query query = this.session.createQuery(unionHql); - data = query.list(); - closeTransaction(); - } catch (Exception e) { - transactionRollBack(); - throw new CatalogResourceException("error while union query data.errorMsg:" - + e.getMessage(), e); - } finally { - closeSession(); - } - return data; + return data; + } + + /** + * union delete. + * + * @param unionHql union hql + * @return int + * @throws CatalogResourceException e1 + */ + public int unionDelete(String unionHql) throws CatalogResourceException { + int num = 0; + try { + beginTransaction(); + Query query = this.session.createQuery(unionHql); + num = query.executeUpdate(); + closeTransaction(); + } catch (Exception e1) { + transactionRollBack(); + throw new CatalogResourceException("error while union query data.errorMsg:" + e1.getMessage(), + e1); + } finally { + closeSession(); } - - public int unionDelete(String unionHql) throws CatalogResourceException { - int num = 0; - try { - beginTransaction(); - Query query = this.session.createQuery(unionHql); - num = query.executeUpdate(); - closeTransaction(); - } catch (Exception e) { - transactionRollBack(); - throw new CatalogResourceException("error while union query data.errorMsg:" - + e.getMessage(), e); - } finally { - closeSession(); - } - return num; + return num; + } + + /** + * query data. + * + * @param queryParams the condition map used to query objects + * @return data list + * @throws CatalogResourceException e1 + */ + @SuppressWarnings("unchecked") + public List query(Map queryParams) throws CatalogResourceException { + List result = null; + try { + beginTransaction(); + Criteria criteria = this.session.createCriteria(entityClass); + for (String key : queryParams.keySet()) { + criteria.add(Restrictions.eq(key, queryParams.get(key))); + } + result = (List) criteria.list(); + closeTransaction(); + } catch (HibernateException e1) { + throw new CatalogResourceException("error while querying data.errorMsg:" + e1.getMessage(), + e1); + } finally { + closeSession(); } + return result; + } - /** - * @param queryParams the condition map used to query objects - * @return - * @throws CatalogResourceException - */ - @SuppressWarnings("unchecked") - public List query(Map queryParams) throws CatalogResourceException { - List result = null; - try { - beginTransaction(); - Criteria criteria = this.session.createCriteria(entityClass); - for (String key : queryParams.keySet()) { - criteria.add(Restrictions.eq(key, queryParams.get(key))); - } - result = (List) criteria.list(); - closeTransaction(); - } catch (HibernateException e) { - throw new CatalogResourceException("error while querying data.errorMsg:" - + e.getMessage(), e); - } finally { - closeSession(); - } - return result; - } - - protected void beginTransaction() { - this.session = this.sessionFactory.openSession(); - this.session.beginTransaction(); - } + protected void beginTransaction() { + this.session = this.sessionFactory.openSession(); + this.session.beginTransaction(); + } - protected void closeTransaction() { - this.session.getTransaction().commit(); - } + protected void closeTransaction() { + this.session.getTransaction().commit(); + } - protected void closeSession() { - this.session.close(); - } + protected void closeSession() { + this.session.close(); + } - protected void transactionRollBack() { - this.session.getTransaction().rollback(); - } + protected void transactionRollBack() { + this.session.getTransaction().rollback(); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/DaoManager.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/DaoManager.java index 6c9a5333..d108474a 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/DaoManager.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/DaoManager.java @@ -13,113 +13,146 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.dao; import org.hibernate.SessionFactory; import org.openo.commontosca.catalog.db.common.CatalogResuorceType; /** - * DAO manager class - * - * a class to store DAO instances and provide methods to get these instances - * + * DAO manager class. + * a class to store DAO instances and provide methods to get these instances. * */ public class DaoManager { - private static DaoManager instance = new DaoManager(); - - private ServiceTemplateDao serviceTemplateDao; - private PackageDao packageDao; - private NodeTemplateDao nodeTemplateDao; - private TemplateDao templateDao; - private ServiceTemplateMappingDao templateMappingDao; - private SessionFactory sessionFactory; - - private DaoManager() {} - - public synchronized static DaoManager getInstance() { - return instance; - } - - public BaseDao getDao(String type) { - switch (CatalogResuorceType.getType(type)) { - case SERVICETEMPLATE: - return getServiceTemplateDao(); - case PACKAGE: - return getPackageDao(); - case NODETEMPLATE: - return getNodeTemplateDao(); - case TEMPLATE: - return getTemplateDao(); - case SERVICETEMPLATEMAPPING: - return getTemplateMappingDao(); - default: - return null; - } + private static DaoManager instance = new DaoManager(); + + private ServiceTemplateDao serviceTemplateDao; + private PackageDao packageDao; + private NodeTemplateDao nodeTemplateDao; + private TemplateDao templateDao; + private ServiceTemplateMappingDao templateMappingDao; + private SessionFactory sessionFactory; + + private DaoManager() {} + + public static synchronized DaoManager getInstance() { + return instance; + } + + /** + * get dao. + * @param type data type + * @return BaseDao + */ + public BaseDao getDao(String type) { + switch (CatalogResuorceType.getType(type)) { + case SERVICETEMPLATE: + return getServiceTemplateDao(); + case PACKAGE: + return getPackageDao(); + case NODETEMPLATE: + return getNodeTemplateDao(); + case TEMPLATE: + return getTemplateDao(); + case SERVICETEMPLATEMAPPING: + return getTemplateMappingDao(); + default: + return null; } - - public void setSessionFactory(SessionFactory sessionFactory) { - this.sessionFactory = sessionFactory; + } + + public void setSessionFactory(SessionFactory sessionFactory) { + this.sessionFactory = sessionFactory; + } + + public SessionFactory getSessionFactory() { + return sessionFactory; + } + + /** + * get service template dao. + * @return ServiceTemplateDao + */ + public ServiceTemplateDao getServiceTemplateDao() { + if (serviceTemplateDao == null) { + serviceTemplateDao = new ServiceTemplateDao(sessionFactory); } - - public SessionFactory getSessionFactory() { - return sessionFactory; + return serviceTemplateDao; + } + + public void setServiceTemplateDao(ServiceTemplateDao serviceTemplateDao) { + this.serviceTemplateDao = serviceTemplateDao; + } + + /** + * get package dao. + * @return PackageDao + */ + public PackageDao getPackageDao() { + if (packageDao == null) { + packageDao = new PackageDao(sessionFactory); } - - public ServiceTemplateDao getServiceTemplateDao() { - if (serviceTemplateDao == null) - serviceTemplateDao = new ServiceTemplateDao(sessionFactory); - return serviceTemplateDao; + return packageDao; + } + + public void setPackageDao(PackageDao packageDao) { + this.packageDao = packageDao; + } + + /** + * get node templage dao. + * @return NodeTemplateDao + */ + public NodeTemplateDao getNodeTemplateDao() { + if (nodeTemplateDao == null) { + nodeTemplateDao = new NodeTemplateDao(sessionFactory); } - - public void setServiceTemplateDao(ServiceTemplateDao serviceTemplateDao) { - this.serviceTemplateDao = serviceTemplateDao; - } - - public PackageDao getPackageDao() { - if (packageDao == null) - packageDao = new PackageDao(sessionFactory); - return packageDao; + return nodeTemplateDao; + } + + public void setTemplateDao(TemplateDao templateDao) { + this.templateDao = templateDao; + } + + /** + * get template dao. + * @return TemplateDao + */ + public TemplateDao getTemplateDao() { + if (templateDao == null) { + templateDao = new TemplateDao(sessionFactory); } - - public void setPackageDao(PackageDao packageDao) { - this.packageDao = packageDao; - } - - public NodeTemplateDao getNodeTemplateDao() { - if (nodeTemplateDao == null) - nodeTemplateDao = new NodeTemplateDao(sessionFactory); - return nodeTemplateDao; - } - - public void setTemplateDao(TemplateDao templateDao) { - this.templateDao = templateDao; - } - - public TemplateDao getTemplateDao() { - if (templateDao == null) - templateDao = new TemplateDao(sessionFactory); - return templateDao; - } - - public void setNodeTemplateDao(NodeTemplateDao nodeTemplateDao) { - this.nodeTemplateDao = nodeTemplateDao; - } - - public ServiceTemplateMappingDao getTemplateMappingDao() { - if (templateMappingDao == null) - templateMappingDao = new ServiceTemplateMappingDao(sessionFactory); - return templateMappingDao; - } - - public void setTemplateMappingDao(ServiceTemplateMappingDao templateMappingDao) { - this.templateMappingDao = templateMappingDao; + return templateDao; + } + + public void setNodeTemplateDao(NodeTemplateDao nodeTemplateDao) { + this.nodeTemplateDao = nodeTemplateDao; + } + + /** + * get template mapping dao. + * @return ServiceTemplateMappingDao + */ + public ServiceTemplateMappingDao getTemplateMappingDao() { + if (templateMappingDao == null) { + templateMappingDao = new ServiceTemplateMappingDao(sessionFactory); } - public void setDaoNull() - { - this.nodeTemplateDao=null; - this.templateDao=null; - this.serviceTemplateDao=null; - this.packageDao=null; - this.templateMappingDao=null; -}} + return templateMappingDao; + } + + public void setTemplateMappingDao(ServiceTemplateMappingDao templateMappingDao) { + this.templateMappingDao = templateMappingDao; + } + + /** + * set dao null. + */ + public void setDaoNull() { + this.nodeTemplateDao = null; + this.templateDao = null; + this.serviceTemplateDao = null; + this.packageDao = null; + this.templateMappingDao = null; + } +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/NodeTemplateDao.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/NodeTemplateDao.java index 41253d96..176edf2d 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/NodeTemplateDao.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/NodeTemplateDao.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.dao; import org.hibernate.SessionFactory; @@ -20,16 +21,14 @@ import org.openo.commontosca.catalog.db.entity.NodeTemplateData; /** - * host DAO class - * - * *@author 10159474 + * host DAO class. * */ public class NodeTemplateDao extends BaseDao { - public NodeTemplateDao(SessionFactory sessionFactory) { - super(sessionFactory); - } + public NodeTemplateDao(SessionFactory sessionFactory) { + super(sessionFactory); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/PackageDao.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/PackageDao.java index 7f8a5036..e86814e7 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/PackageDao.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/PackageDao.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.dao; import org.hibernate.SessionFactory; @@ -20,16 +21,14 @@ import org.openo.commontosca.catalog.db.entity.PackageData; /** - * host DAO class - * - * *@author 10159474 + * host DAO class. * */ public class PackageDao extends BaseDao { - public PackageDao(SessionFactory sessionFactory) { - super(sessionFactory); - } + public PackageDao(SessionFactory sessionFactory) { + super(sessionFactory); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/ServiceTemplateDao.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/ServiceTemplateDao.java index e2a5f3c2..b2bba583 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/ServiceTemplateDao.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/ServiceTemplateDao.java @@ -13,25 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.dao; import org.hibernate.SessionFactory; import org.openo.commontosca.catalog.db.entity.ServiceTemplateData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** - * DAO class - * - * *@author 10159474 + * DAO class. * */ public class ServiceTemplateDao extends BaseDao { - private static final Logger logger = LoggerFactory.getLogger(ServiceTemplateDao.class); - public ServiceTemplateDao(SessionFactory sessionFactory) { - super(sessionFactory); - } + public ServiceTemplateDao(SessionFactory sessionFactory) { + super(sessionFactory); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/ServiceTemplateMappingDao.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/ServiceTemplateMappingDao.java index 558ce13a..1bb2b516 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/ServiceTemplateMappingDao.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/ServiceTemplateMappingDao.java @@ -13,25 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.dao; import org.hibernate.SessionFactory; import org.openo.commontosca.catalog.db.entity.ServiceTemplateMappingData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** - * DAO class - * - * *@author 10159474 + * DAO class. * */ public class ServiceTemplateMappingDao extends BaseDao { - private static final Logger logger = LoggerFactory.getLogger(ServiceTemplateMappingDao.class); - public ServiceTemplateMappingDao(SessionFactory sessionFactory) { - super(sessionFactory); - } + public ServiceTemplateMappingDao(SessionFactory sessionFactory) { + super(sessionFactory); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/TemplateDao.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/TemplateDao.java index 5c39a9e8..fc90bef2 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/TemplateDao.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/TemplateDao.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.dao; import org.hibernate.HibernateException; @@ -25,53 +26,56 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * DAO class - * - * *@author 10159474 + * DAO class. * */ public class TemplateDao extends BaseDao { - private static final Logger logger = LoggerFactory.getLogger(TemplateDao.class); + private static final Logger logger = LoggerFactory.getLogger(TemplateDao.class); - public TemplateDao(SessionFactory sessionFactory) { - super(sessionFactory); - } + public TemplateDao(SessionFactory sessionFactory) { + super(sessionFactory); + } - public TemplateData create(TemplateData data) throws CatalogResourceException { - logger.info("TemplateDao:start add template.info:" + CatalogDbUtil.objectToString(data)); - beginTransaction(); - try { - this.session.persist(data.getServiceTemplate()); - for (NodeTemplateData nodeData : data.getNodeTemplates()) { - this.session.persist(nodeData); - } - closeTransaction(); - } catch (HibernateException e) { - logger.error("TemplateDao:error while add template data.errorMsg:" + e.getMessage()); - throw new CatalogResourceException("error while add template data" + e.getMessage(), e); - } finally { - closeSession(); - } - logger.info("TemplateDao: add template end ."); - return data; + /** + * create template data. + */ + public TemplateData create(TemplateData data) throws CatalogResourceException { + logger.info("TemplateDao:start add template.info:" + CatalogDbUtil.objectToString(data)); + beginTransaction(); + try { + this.session.persist(data.getServiceTemplate()); + for (NodeTemplateData nodeData : data.getNodeTemplates()) { + this.session.persist(nodeData); + } + closeTransaction(); + } catch (HibernateException e1) { + logger.error("TemplateDao:error while add template data.errorMsg:" + e1.getMessage()); + throw new CatalogResourceException("error while add template data" + e1.getMessage(), e1); + } finally { + closeSession(); } + logger.info("TemplateDao: add template end ."); + return data; + } - public void delete(TemplateData data) throws CatalogResourceException { - logger.info("TemplateDao:start delete template.info:" + CatalogDbUtil.objectToString(data)); - beginTransaction(); - try { - for (NodeTemplateData nodeData : data.getNodeTemplates()) { - this.session.delete(nodeData); - } - this.session.delete(data.getServiceTemplate()); - closeTransaction(); - } catch (HibernateException e) { - logger.error("TemplateDao:error while delete template data.errorMsg:" + e.getMessage()); - throw new CatalogResourceException("error while delete template data" + e.getMessage(), - e); - } finally { - closeSession(); - } - logger.info("TemplateDao: delete template end ."); + /** + * delete template data. + */ + public void delete(TemplateData data) throws CatalogResourceException { + logger.info("TemplateDao:start delete template.info:" + CatalogDbUtil.objectToString(data)); + beginTransaction(); + try { + for (NodeTemplateData nodeData : data.getNodeTemplates()) { + this.session.delete(nodeData); + } + this.session.delete(data.getServiceTemplate()); + closeTransaction(); + } catch (HibernateException e1) { + logger.error("TemplateDao:error while delete template data.errorMsg:" + e1.getMessage()); + throw new CatalogResourceException("error while delete template data" + e1.getMessage(), e1); + } finally { + closeSession(); } + logger.info("TemplateDao: delete template end ."); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/BaseData.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/BaseData.java index 99fe14ec..2d1f7fe4 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/BaseData.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/BaseData.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.entity; public class BaseData { diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/NodeTemplateData.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/NodeTemplateData.java index aeef00b9..3630a135 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/NodeTemplateData.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/NodeTemplateData.java @@ -13,86 +13,86 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.entity; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - - @Entity @Table(name = "catalog_node_template_table") @JsonIgnoreProperties(ignoreUnknown = true) public class NodeTemplateData extends BaseData { - @Id - @Column(name = "NODETEMPLATEID") - private String nodeTemplateId; - @Column(name = "NAME") - private String name; + @Id + @Column(name = "NODETEMPLATEID") + private String nodeTemplateId; + @Column(name = "NAME") + private String name; - @Column(name = "SERVICETEMPLATEID") - private String serviceTemplateId; + @Column(name = "SERVICETEMPLATEID") + private String serviceTemplateId; - @Column(name = "TYPE") - private String type; + @Column(name = "TYPE") + private String type; - @Column(name = "PROPERTIES") - private String properties; + @Column(name = "PROPERTIES") + private String properties; - @Column(name = "RELATIONSHIPS") - private String relationShips; + @Column(name = "RELATIONSHIPS") + private String relationShips; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getServiceTemplateId() { - return serviceTemplateId; - } + public String getServiceTemplateId() { + return serviceTemplateId; + } - public void setServiceTemplateId(String serviceTemplateId) { - this.serviceTemplateId = serviceTemplateId; - } + public void setServiceTemplateId(String serviceTemplateId) { + this.serviceTemplateId = serviceTemplateId; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public String getProperties() { - return properties; - } + public String getProperties() { + return properties; + } - public void setProperties(String properties) { - this.properties = properties; - } + public void setProperties(String properties) { + this.properties = properties; + } - public String getRelationShips() { - return relationShips; - } + public String getRelationShips() { + return relationShips; + } - public void setRelationShips(String relationShips) { - this.relationShips = relationShips; - } + public void setRelationShips(String relationShips) { + this.relationShips = relationShips; + } - public void setNodeTemplateId(String nodeTemplateId) { - this.nodeTemplateId = nodeTemplateId; - } + public void setNodeTemplateId(String nodeTemplateId) { + this.nodeTemplateId = nodeTemplateId; + } - public String getNodeTemplateId() { - return nodeTemplateId; - } + public String getNodeTemplateId() { + return nodeTemplateId; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/PackageData.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/PackageData.java index 6c4a8110..d8dd84e1 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/PackageData.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/PackageData.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -27,161 +28,161 @@ import javax.persistence.Table; @JsonIgnoreProperties(ignoreUnknown = true) public class PackageData extends BaseData { - @Id - @Column(name = "CSARID") - private String csarId; - @Column(name = "DOWNLOADURi") - private String downloadUri; - - @Column(name = "NAME") - private String name; - - @Column(name = "SIZE") - private String size; - @Column(name = "VERSION") - private String version; - - @Column(name = "PROVIDER") - private String provider; - @Column(name = "TYPE") - private String type; - @Column(name = "FORMAT") - private String format; - - @Column(name = "DELETIONPENDING") - private String deletionPending; - - @Column(name = "MODIFYTIME") - private String modifyTime; - @Column(name = "OPERATIONALSTATE") - private String operationalState; - @Column(name = "USAGESTATE") - private String usageState; - @Column(name = "CREATETIME") - private String createTime; - @Column(name = "ONBOARDSTATE") - private String onBoardState; - @Column(name = "PROCESSSTATE") - private String processState; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getOnBoardState() { - return onBoardState; - } - - public void setOnBoardState(String onBoardState) { - this.onBoardState = onBoardState; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getProvider() { - return provider; - } - - public void setProvider(String provider) { - this.provider = provider; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getDownloadUri() { - return downloadUri; - } - - public void setDownloadUri(String downloadUri) { - this.downloadUri = downloadUri; - } - - public String getSize() { - return size; - } - - public void setSize(String size) { - this.size = size; - } - - public String getFormat() { - return format; - } - - public void setFormat(String format) { - this.format = format; - } - - public String getDeletionPending() { - return deletionPending; - } - - public void setDeletionPending(String deletionPending) { - this.deletionPending = deletionPending; - } - - public String getModifyTime() { - return modifyTime; - } - - public void setModifyTime(String modifyTime) { - this.modifyTime = modifyTime; - } - - public String getOperationalState() { - return operationalState; - } - - public void setOperationalState(String operationalState) { - this.operationalState = operationalState; - } - - public String getUsageState() { - return usageState; - } - - public void setUsageState(String usageState) { - this.usageState = usageState; - } - - public String getCreateTime() { - return createTime; - } + @Id + @Column(name = "CSARID") + private String csarId; + @Column(name = "DOWNLOADURi") + private String downloadUri; + + @Column(name = "NAME") + private String name; + + @Column(name = "SIZE") + private String size; + @Column(name = "VERSION") + private String version; + + @Column(name = "PROVIDER") + private String provider; + @Column(name = "TYPE") + private String type; + @Column(name = "FORMAT") + private String format; + + @Column(name = "DELETIONPENDING") + private String deletionPending; + + @Column(name = "MODIFYTIME") + private String modifyTime; + @Column(name = "OPERATIONALSTATE") + private String operationalState; + @Column(name = "USAGESTATE") + private String usageState; + @Column(name = "CREATETIME") + private String createTime; + @Column(name = "ONBOARDSTATE") + private String onBoardState; + @Column(name = "PROCESSSTATE") + private String processState; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getOnBoardState() { + return onBoardState; + } + + public void setOnBoardState(String onBoardState) { + this.onBoardState = onBoardState; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getProvider() { + return provider; + } + + public void setProvider(String provider) { + this.provider = provider; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getDownloadUri() { + return downloadUri; + } + + public void setDownloadUri(String downloadUri) { + this.downloadUri = downloadUri; + } + + public String getSize() { + return size; + } + + public void setSize(String size) { + this.size = size; + } + + public String getFormat() { + return format; + } + + public void setFormat(String format) { + this.format = format; + } + + public String getDeletionPending() { + return deletionPending; + } + + public void setDeletionPending(String deletionPending) { + this.deletionPending = deletionPending; + } + + public String getModifyTime() { + return modifyTime; + } + + public void setModifyTime(String modifyTime) { + this.modifyTime = modifyTime; + } + + public String getOperationalState() { + return operationalState; + } + + public void setOperationalState(String operationalState) { + this.operationalState = operationalState; + } + + public String getUsageState() { + return usageState; + } + + public void setUsageState(String usageState) { + this.usageState = usageState; + } + + public String getCreateTime() { + return createTime; + } - public void setCreateTime(String createTime) { - this.createTime = createTime; - } + public void setCreateTime(String createTime) { + this.createTime = createTime; + } - public void setCsarId(String csarId) { - this.csarId = csarId; - } + public void setCsarId(String csarId) { + this.csarId = csarId; + } - public String getCsarId() { - return csarId; - } + public String getCsarId() { + return csarId; + } - public String getProcessState() { - return processState; - } + public String getProcessState() { + return processState; + } - public void setProcessState(String processState) { - this.processState = processState; - } + public void setProcessState(String processState) { + this.processState = processState; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/ServiceTemplateData.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/ServiceTemplateData.java index 6e5963aa..21f084b2 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/ServiceTemplateData.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/ServiceTemplateData.java @@ -13,126 +13,128 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.entity; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @Entity @Table(name = "catalog_service_template_table") @JsonIgnoreProperties(ignoreUnknown = true) public class ServiceTemplateData extends BaseData { - @Id - @Column(name = "SERVICETEMPLATEID") - private String serviceTemplateId; - @Column(name = "TEMPLATENAME") - private String templateName; + @Id + @Column(name = "SERVICETEMPLATEID") + private String serviceTemplateId; + @Column(name = "TEMPLATENAME") + private String templateName; - @Column(name = "TYPE") - private String type; + @Column(name = "TYPE") + private String type; - @Column(name = "VENDOR") - private String vendor; + @Column(name = "VENDOR") + private String vendor; - @Column(name = "VERSION") - private String version; + @Column(name = "VERSION") + private String version; - @Column(name = "CSARID") - private String csarId; + @Column(name = "CSARID") + private String csarId; - @Column(name = "INPUTS") - private String inputs; + @Column(name = "INPUTS") + private String inputs; - @Column(name = "DOWNLOADURI") - private String downloadUri; + @Column(name = "DOWNLOADURI") + private String downloadUri; - @Column(name = "ROWDATA") - private String rowData; - @Column(name = "OPERATIONS") - private String operations; + @Column(name = "ROWDATA") + private String rowData; + @Column(name = "OPERATIONS") + private String operations; - public String getRowData() { - return rowData; - } + public String getRowData() { + return rowData; + } - public void setRowData(String rowData) { - this.rowData = rowData; - } + public void setRowData(String rowData) { + this.rowData = rowData; + } - public String getOperations() { - return operations; - } + public String getOperations() { + return operations; + } - public void setOperations(String operations) { - this.operations = operations; - } + public void setOperations(String operations) { + this.operations = operations; + } - public String getTemplateName() { - return templateName; - } + public String getTemplateName() { + return templateName; + } - public void setTemplateName(String templateName) { - this.templateName = templateName; - } + public void setTemplateName(String templateName) { + this.templateName = templateName; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public String getVendor() { - return vendor; - } + public String getVendor() { + return vendor; + } - public void setVendor(String vendor) { - this.vendor = vendor; - } + public void setVendor(String vendor) { + this.vendor = vendor; + } - public String getVersion() { - return version; - } + public String getVersion() { + return version; + } - public void setVersion(String version) { - this.version = version; - } + public void setVersion(String version) { + this.version = version; + } - public String getCsarId() { - return csarId; - } + public String getCsarId() { + return csarId; + } - public void setCsarId(String csarId) { - this.csarId = csarId; - } + public void setCsarId(String csarId) { + this.csarId = csarId; + } - public String getInputs() { - return inputs; - } + public String getInputs() { + return inputs; + } - public void setInputs(String inputs) { - this.inputs = inputs; - } + public void setInputs(String inputs) { + this.inputs = inputs; + } - public String getDownloadUri() { - return downloadUri; - } + public String getDownloadUri() { + return downloadUri; + } - public void setDownloadUri(String downloadUri) { - this.downloadUri = downloadUri; - } + public void setDownloadUri(String downloadUri) { + this.downloadUri = downloadUri; + } - public void setServiceTemplateId(String serviceTemplateId) { - this.serviceTemplateId = serviceTemplateId; - } + public void setServiceTemplateId(String serviceTemplateId) { + this.serviceTemplateId = serviceTemplateId; + } - public String getServiceTemplateId() { - return serviceTemplateId; - } + public String getServiceTemplateId() { + return serviceTemplateId; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/ServiceTemplateMappingData.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/ServiceTemplateMappingData.java index a0a632c5..f9fa0768 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/ServiceTemplateMappingData.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/ServiceTemplateMappingData.java @@ -13,74 +13,75 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.entity; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - @Entity @Table(name = "catalog_model_substitution_mapping_table") @JsonIgnoreProperties(ignoreUnknown = true) public class ServiceTemplateMappingData extends BaseData { - @Id - @Column(name = "MAPPINGID") - private String mappingId; + @Id + @Column(name = "MAPPINGID") + private String mappingId; - @Column(name = "NODETYPE") - private String nodeType; + @Column(name = "NODETYPE") + private String nodeType; - @Column(name = "SERVICETEMPLATEID") - private String serviceTemplateId; + @Column(name = "SERVICETEMPLATEID") + private String serviceTemplateId; - @Column(name = "REQUIREMENTS") - private String requirements; + @Column(name = "REQUIREMENTS") + private String requirements; - @Column(name = "CAPABILITIES") - private String capabilities; + @Column(name = "CAPABILITIES") + private String capabilities; - public String getMappingId() { - return mappingId; - } + public String getMappingId() { + return mappingId; + } - public void setMappingId(String mappingId) { - this.mappingId = mappingId; - } + public void setMappingId(String mappingId) { + this.mappingId = mappingId; + } - public String getNodeType() { - return nodeType; - } + public String getNodeType() { + return nodeType; + } - public void setNodeType(String nodeType) { - this.nodeType = nodeType; - } + public void setNodeType(String nodeType) { + this.nodeType = nodeType; + } - public String getServiceTemplateId() { - return serviceTemplateId; - } + public String getServiceTemplateId() { + return serviceTemplateId; + } - public void setServiceTemplateId(String serviceTemplateId) { - this.serviceTemplateId = serviceTemplateId; - } + public void setServiceTemplateId(String serviceTemplateId) { + this.serviceTemplateId = serviceTemplateId; + } - public String getRequirements() { - return requirements; - } + public String getRequirements() { + return requirements; + } - public void setRequirements(String requirements) { - this.requirements = requirements; - } + public void setRequirements(String requirements) { + this.requirements = requirements; + } - public String getCapabilities() { - return capabilities; - } + public String getCapabilities() { + return capabilities; + } - public void setCapabilities(String capabilities) { - this.capabilities = capabilities; - } + public void setCapabilities(String capabilities) { + this.capabilities = capabilities; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/TemplateData.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/TemplateData.java index ff139b1e..073c706e 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/TemplateData.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/TemplateData.java @@ -13,29 +13,30 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.entity; import java.util.ArrayList; public class TemplateData extends BaseData { - private ServiceTemplateData serviceTemplate; - private ArrayList nodeTemplates = new ArrayList(); + private ServiceTemplateData serviceTemplate; + private ArrayList nodeTemplates = new ArrayList(); - public ServiceTemplateData getServiceTemplate() { - return serviceTemplate; - } + public ServiceTemplateData getServiceTemplate() { + return serviceTemplate; + } - public void setServiceTemplate(ServiceTemplateData serviceTemplate) { - this.serviceTemplate = serviceTemplate; - } + public void setServiceTemplate(ServiceTemplateData serviceTemplate) { + this.serviceTemplate = serviceTemplate; + } - public ArrayList getNodeTemplates() { - return nodeTemplates; - } + public ArrayList getNodeTemplates() { + return nodeTemplates; + } - public void setNodeTemplates(ArrayList nodeTemplates) { - this.nodeTemplates = nodeTemplates; - } + public void setNodeTemplates(ArrayList nodeTemplates) { + this.nodeTemplates = nodeTemplates; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/exception/CatalogResourceException.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/exception/CatalogResourceException.java index 5a858d31..e632d890 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/exception/CatalogResourceException.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/exception/CatalogResourceException.java @@ -13,61 +13,66 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.exception; -/** - * - */ public class CatalogResourceException extends ErrorCodeException { - private static final long serialVersionUID = 5699508780537383310L; + private static final long serialVersionUID = 5699508780537383310L; - public CatalogResourceException(int errcode) { - super(errcode, ""); - } + public CatalogResourceException(int errcode) { + super(errcode, ""); + } - public CatalogResourceException(int errcode, Throwable cause) { - super(cause, errcode); - } + public CatalogResourceException(int errcode, Throwable cause) { + super(cause, errcode); + } - public CatalogResourceException(int errcode, String message, Throwable cause) { - super(cause, errcode, message); - } + public CatalogResourceException(int errcode, String message, Throwable cause) { + super(cause, errcode, message); + } - public CatalogResourceException() { - super(9999999, null); - } + public CatalogResourceException() { + super(9999999, null); + } - public CatalogResourceException(String message) { - super(9999999, message); - } + public CatalogResourceException(String message) { + super(9999999, message); + } - public CatalogResourceException(Throwable cause) { - super(cause, 9999999); - } + public CatalogResourceException(Throwable cause) { + super(cause, 9999999); + } - public CatalogResourceException(String message, Throwable cause) { - super(cause, 9999999, message); - } + public CatalogResourceException(String message, Throwable cause) { + super(cause, 9999999, message); + } - public CatalogResourceException(Throwable source, int errID, String debugMessage, - String[] arguments) { - super(source, errID, debugMessage, arguments); - } + /** + * catalog resource exception. + * @param source throwable source + * @param errId error Id + * @param debugMessage debug message + * @param arguments arguments + */ + public CatalogResourceException(Throwable source, int errId, String debugMessage, + String[] arguments) { + super(source, errId, debugMessage, arguments); + } - public CatalogResourceException(Throwable source, int category, int code, String debugMessage, - String[] arguments) { - super(source, category, code, debugMessage, arguments); - } + public CatalogResourceException(Throwable source, int category, int code, String debugMessage, + String[] arguments) { + super(source, category, code, debugMessage, arguments); + } - public int getErrcode() { - return super.getErrorCode(); - } + public int getErrcode() { + return super.getErrorCode(); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/exception/ErrorCodeException.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/exception/ErrorCodeException.java index 33e6d9fa..3a850a5d 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/exception/ErrorCodeException.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/exception/ErrorCodeException.java @@ -13,120 +13,133 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.exception; -/** - * *@author 10159474 - * - */ public class ErrorCodeException extends Exception { - private static final long serialVersionUID = 3220072444842529499L; - private int categoryCode = 0; - private int errorCode = 1; - private String[] arguments = null; - - private static String defaultText = null; - - - public static void setDefaultText(String text) { - defaultText = text; - } - - - public static String getDefaultText() { - return defaultText; - } - + private static final long serialVersionUID = 3220072444842529499L; + private int categoryCode = 0; + private int errorCode = 1; + private String[] arguments = null; - public ErrorCodeException(int code, String debugMessage) { - this(code, debugMessage, null); - } + private static String defaultText = null; - public ErrorCodeException(int code, String debugMessage, String[] arguments) { - super(debugMessage); - this.errorCode = code; - this.arguments = arguments; - } + public static void setDefaultText(String text) { + defaultText = text; + } - public ErrorCodeException(Throwable source, int code) { - this(source, code, (String[]) null); - } + public static String getDefaultText() { + return defaultText; + } - public ErrorCodeException(Throwable source, int code, String[] arguments) { - super(source); - this.errorCode = code; - this.arguments = arguments; - } + public ErrorCodeException(int code, String debugMessage) { + this(code, debugMessage, null); + } + /** + * error code exception. + * @param code error code + * @param debugMessage debug message + * @param arguments arguments + */ + public ErrorCodeException(int code, String debugMessage, String[] arguments) { + super(debugMessage); + this.errorCode = code; + this.arguments = arguments; + } - public ErrorCodeException(Throwable source, int code, String debugMessage) { - this(source, code, debugMessage, null); - } + public ErrorCodeException(Throwable source, int code) { + this(source, code, (String[]) null); + } - public ErrorCodeException(Throwable source, int code, String debugMessage, String[] arguments) { - super(debugMessage, source); - this.errorCode = code; - this.arguments = arguments; - } + /** + * error code exception. + * @param source Throwable + * @param code error code + * @param arguments arguments + */ + public ErrorCodeException(Throwable source, int code, String[] arguments) { + super(source); + this.errorCode = code; + this.arguments = arguments; + } - public ErrorCodeException(int category, int code, String debugMessage) { - this(category, code, debugMessage, null); - } + public ErrorCodeException(Throwable source, int code, String debugMessage) { + this(source, code, debugMessage, null); + } + /** + * error code exception. + * @param source Throwable + * @param code error code + * @param debugMessage debug message + * @param arguments arguments + */ + public ErrorCodeException(Throwable source, int code, String debugMessage, String[] arguments) { + super(debugMessage, source); + this.errorCode = code; + this.arguments = arguments; + } - public ErrorCodeException(int category, int code, String debugMessage, String[] arguments) { - super(debugMessage); - this.categoryCode = category; - this.errorCode = code; - this.arguments = arguments; - } + public ErrorCodeException(int category, int code, String debugMessage) { + this(category, code, debugMessage, null); + } - public ErrorCodeException(Throwable source, int category, int code) { - this(source, category, code, (String[]) null); - } + public ErrorCodeException(int category, int code, String debugMessage, String[] arguments) { + super(debugMessage); + this.categoryCode = category; + this.errorCode = code; + this.arguments = arguments; + } - public ErrorCodeException(Throwable source, int category, int code, String[] arguments) { - super(source); - this.categoryCode = category; - this.errorCode = code; - this.arguments = arguments; - } + public ErrorCodeException(Throwable source, int category, int code) { + this(source, category, code, (String[]) null); + } - public ErrorCodeException(Throwable source, int category, int code, String debugMessage) { - this(source, category, code, debugMessage, null); - } + public ErrorCodeException(Throwable source, int category, int code, String[] arguments) { + super(source); + this.categoryCode = category; + this.errorCode = code; + this.arguments = arguments; + } - public ErrorCodeException(Throwable source, int category, int code, String debugMessage, - String[] arguments) { - super(debugMessage, source); - this.categoryCode = category; - this.errorCode = code; - this.arguments = arguments; - } + public ErrorCodeException(Throwable source, int category, int code, String debugMessage) { + this(source, category, code, debugMessage, null); + } - public int getCategory() { - return categoryCode; - } - public int getErrorCode() { - return errorCode; - } + public ErrorCodeException(Throwable source, int category, int code, String debugMessage, + String[] arguments) { + super(debugMessage, source); + this.categoryCode = category; + this.errorCode = code; + this.arguments = arguments; + } - public String[] getArguments() { - return arguments; - } + public int getCategory() { + return categoryCode; + } + + public int getErrorCode() { + return errorCode; + } + + + public String[] getArguments() { + return arguments; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/resource/PackageManager.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/resource/PackageManager.java index 124fc358..3d8e234f 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/resource/PackageManager.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/resource/PackageManager.java @@ -13,115 +13,170 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.db.resource; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; +package org.openo.commontosca.catalog.db.resource; import org.openo.commontosca.catalog.db.common.Parameters; +import org.openo.commontosca.catalog.db.entity.PackageData; +import org.openo.commontosca.catalog.db.entity.ServiceTemplateData; + import org.openo.commontosca.catalog.db.exception.CatalogResourceException; import org.openo.commontosca.catalog.db.util.CatalogDbUtil; import org.openo.commontosca.catalog.db.util.HqlFactory; -import org.openo.commontosca.catalog.db.entity.PackageData; -import org.openo.commontosca.catalog.db.entity.ServiceTemplateData; import org.openo.commontosca.catalog.db.wrapper.PackageHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + public class PackageManager { - private static final Logger LOGGER = LoggerFactory.getLogger(PackageManager.class); - private static PackageManager manager; - PackageHandler handler = new PackageHandler(); - - public synchronized static PackageManager getInstance() { - if (manager == null) { - manager = new PackageManager(); - } - return manager; + private static final Logger LOGGER = LoggerFactory.getLogger(PackageManager.class); + private static PackageManager manager; + PackageHandler handler = new PackageHandler(); + + /** + * get PackageManager instance. + * @return PackageManager instance + */ + public static synchronized PackageManager getInstance() { + if (manager == null) { + manager = new PackageManager(); } + return manager; + } - private PackageManager() {} + private PackageManager() {} - public PackageData addPackage(PackageData packageData) throws CatalogResourceException { - LOGGER.info("start add package info to db.info:" - + CatalogDbUtil.objectToString(packageData)); - PackageData data = handler.create(packageData); - LOGGER.info(" package info to db end.info:" + CatalogDbUtil.objectToString(data)); - return data; - } + /** + * add package. + * @param packageData package data + * @return PackageData + * @throws CatalogResourceException e + */ + public PackageData addPackage(PackageData packageData) throws CatalogResourceException { + LOGGER.info("start add package info to db.info:" + CatalogDbUtil.objectToString(packageData)); + PackageData data = handler.create(packageData); + LOGGER.info(" package info to db end.info:" + CatalogDbUtil.objectToString(data)); + return data; + } - public ArrayList queryPackageByCsarId(String package_csarId) - throws CatalogResourceException { - Map queryParam = new HashMap(); - queryParam.put(Parameters.csarId.name(), package_csarId); - LOGGER.info("start query package info by csarid." + package_csarId); - ArrayList data = handler.query(queryParam); - LOGGER.info("query package info end.size:" + data.size() + "detail:" - + CatalogDbUtil.objectToString(data)); - return data; - } + /** + * query package by package id. + * @param csarId package id + * @return package data list + * @throws CatalogResourceException e + */ + public ArrayList queryPackageByCsarId(String csarId) + throws CatalogResourceException { + Map queryParam = new HashMap(); + queryParam.put(Parameters.csarId.name(), csarId); + LOGGER.info("start query package info by csarid." + csarId); + ArrayList data = handler.query(queryParam); + LOGGER.info("query package info end.size:" + data.size() + "detail:" + + CatalogDbUtil.objectToString(data)); + return data; + } - public ArrayList queryPackage(String name, String provider, String version, - String deletionPending, String type) throws CatalogResourceException { - LOGGER.info("start query package info.name:" + name + " provider:" + provider + " version:" - + version + " type:" + type); - Map queryParam = new HashMap(); - if (CatalogDbUtil.isNotEmpty(name)) - queryParam.put(Parameters.name.name(), name); - if (CatalogDbUtil.isNotEmpty(version)) - queryParam.put(Parameters.version.name(), version); - if (CatalogDbUtil.isNotEmpty(deletionPending)) - queryParam.put(Parameters.deletionPending.name(), deletionPending); - if (CatalogDbUtil.isNotEmpty(type)) - queryParam.put(Parameters.type.name(), type); - if (CatalogDbUtil.isNotEmpty(provider)) - queryParam.put(Parameters.provider.name(), provider); - ArrayList data = handler.query(queryParam); - LOGGER.info("query package info end.size:" + data.size() + "detail:" - + CatalogDbUtil.objectToString(data)); - return data; + /** + * query package by condition. + * @param name package name + * @param provider package provider + * @param version package version + * @param deletionPending deletionPending + * @param type package type + * @return package data list + * @throws CatalogResourceException e + */ + public ArrayList queryPackage(String name, String provider, String version, + String deletionPending, String type) throws CatalogResourceException { + LOGGER.info("start query package info.name:" + name + " provider:" + provider + " version:" + + version + " type:" + type); + Map queryParam = new HashMap(); + if (CatalogDbUtil.isNotEmpty(name)) { + queryParam.put(Parameters.name.name(), name); } - - public void deletePackage(String package_oid) throws CatalogResourceException { - LOGGER.info("start delete package info by id." + package_oid); - handler.delete(package_oid); - LOGGER.info(" delete package info end id." + package_oid); + if (CatalogDbUtil.isNotEmpty(version)) { + queryParam.put(Parameters.version.name(), version); } - - public void deletePackageByServiceTemplateId(String serviceTemplateId) - throws CatalogResourceException { - LOGGER.info("start delete package info by serviceTemplateid." + serviceTemplateId); - ServiceTemplateData serviceTemplate = new ServiceTemplateData(); - serviceTemplate.setServiceTemplateId(serviceTemplateId); - String filter = - HqlFactory.getDeleteHqlByFilter(PackageData.class, serviceTemplate, - Parameters.csarId.name()); - int data = handler.unionDelete(filter); - - LOGGER.info("delete serviceTemplate info end.num:" + data); + if (CatalogDbUtil.isNotEmpty(deletionPending)) { + queryParam.put(Parameters.deletionPending.name(), deletionPending); } - - public ArrayList queryPackageByServiceTemplateId(String serviceTemplateId) - throws CatalogResourceException { - LOGGER.info("start query package info by serviceTemplateid." + serviceTemplateId); - ServiceTemplateData serviceTemplate = new ServiceTemplateData(); - serviceTemplate.setServiceTemplateId(serviceTemplateId); - String filter = - HqlFactory.getQueryHqlByFilter(PackageData.class, serviceTemplate, - Parameters.csarId.name()); - ArrayList data = handler.unionQuery(filter); - LOGGER.info("query package info end.size:" + data.size() + "detail:" - + CatalogDbUtil.objectToString(data)); - return data; + if (CatalogDbUtil.isNotEmpty(type)) { + queryParam.put(Parameters.type.name(), type); } - - public void updatePackage(PackageData packageData, String csarId) - throws CatalogResourceException { - LOGGER.info("start update package info by id." + csarId + " info:" - + CatalogDbUtil.objectToString(packageData)); - handler.update(packageData, csarId); - LOGGER.info(" update package end id." + csarId); + if (CatalogDbUtil.isNotEmpty(provider)) { + queryParam.put(Parameters.provider.name(), provider); } + ArrayList data = handler.query(queryParam); + LOGGER.info("query package info end.size:" + data.size() + "detail:" + + CatalogDbUtil.objectToString(data)); + return data; + } + + /** + * delete package according package id. + * @param packageId package id + * @throws CatalogResourceException e + */ + public void deletePackage(String packageId) throws CatalogResourceException { + LOGGER.info("start delete package info by id." + packageId); + handler.delete(packageId); + LOGGER.info(" delete package info end id." + packageId); + } + + /** + * delete package by service template id. + * @param serviceTemplateId service template id + * @throws CatalogResourceException e + */ + public void deletePackageByServiceTemplateId(String serviceTemplateId) + throws CatalogResourceException { + LOGGER.info("start delete package info by serviceTemplateid." + serviceTemplateId); + ServiceTemplateData serviceTemplate = new ServiceTemplateData(); + serviceTemplate.setServiceTemplateId(serviceTemplateId); + String filter = + HqlFactory.getDeleteHqlByFilter(PackageData.class, serviceTemplate, + Parameters.csarId.name()); + int data = handler.unionDelete(filter); + + LOGGER.info("delete serviceTemplate info end.num:" + data); + } + + /** + * query package by service template id. + * @param serviceTemplateId service template id + * @return package data list + * @throws CatalogResourceException e + */ + public ArrayList queryPackageByServiceTemplateId(String serviceTemplateId) + throws CatalogResourceException { + LOGGER.info("start query package info by serviceTemplateid." + serviceTemplateId); + ServiceTemplateData serviceTemplate = new ServiceTemplateData(); + serviceTemplate.setServiceTemplateId(serviceTemplateId); + String filter = + HqlFactory + .getQueryHqlByFilter(PackageData.class, serviceTemplate, Parameters.csarId.name()); + ArrayList data = handler.unionQuery(filter); + LOGGER.info("query package info end.size:" + data.size() + "detail:" + + CatalogDbUtil.objectToString(data)); + return data; + } + + /** + * update package data. + * + * @param packageData package data + * @param csarId package id + * @throws CatalogResourceException e + */ + public void updatePackage(PackageData packageData, String csarId) + throws CatalogResourceException { + LOGGER.info("start update package info by id." + csarId + " info:" + + CatalogDbUtil.objectToString(packageData)); + handler.update(packageData, csarId); + LOGGER.info(" update package end id." + csarId); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/resource/TemplateManager.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/resource/TemplateManager.java index 564116d8..8229e832 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/resource/TemplateManager.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/resource/TemplateManager.java @@ -13,195 +13,290 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.db.resource; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; +package org.openo.commontosca.catalog.db.resource; import org.openo.commontosca.catalog.db.common.Parameters; +import org.openo.commontosca.catalog.db.entity.NodeTemplateData; +import org.openo.commontosca.catalog.db.entity.PackageData; +import org.openo.commontosca.catalog.db.entity.ServiceTemplateData; import org.openo.commontosca.catalog.db.entity.ServiceTemplateMappingData; import org.openo.commontosca.catalog.db.entity.TemplateData; import org.openo.commontosca.catalog.db.exception.CatalogResourceException; import org.openo.commontosca.catalog.db.util.CatalogDbUtil; import org.openo.commontosca.catalog.db.util.HqlFactory; +import org.openo.commontosca.catalog.db.wrapper.NodeTemplateHandler; import org.openo.commontosca.catalog.db.wrapper.ServiceTemplateHandler; import org.openo.commontosca.catalog.db.wrapper.ServiceTemplateMappingHandler; import org.openo.commontosca.catalog.db.wrapper.TemplateHandler; -import org.openo.commontosca.catalog.db.entity.NodeTemplateData; -import org.openo.commontosca.catalog.db.entity.PackageData; -import org.openo.commontosca.catalog.db.entity.ServiceTemplateData; -import org.openo.commontosca.catalog.db.wrapper.NodeTemplateHandler; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + public class TemplateManager { - private static final Logger LOGGER = LoggerFactory.getLogger(TemplateManager.class); - private static TemplateManager manager; - ServiceTemplateHandler handler = new ServiceTemplateHandler(); - NodeTemplateHandler nodeTemplateHandler = new NodeTemplateHandler(); - TemplateHandler templateHandler = new TemplateHandler(); - ServiceTemplateMappingHandler mappingHandler = new ServiceTemplateMappingHandler(); - - public synchronized static TemplateManager getInstance() { - if (manager == null) { - manager = new TemplateManager(); - } - return manager; + private static final Logger LOGGER = LoggerFactory.getLogger(TemplateManager.class); + private static TemplateManager manager; + ServiceTemplateHandler handler = new ServiceTemplateHandler(); + NodeTemplateHandler nodeTemplateHandler = new NodeTemplateHandler(); + TemplateHandler templateHandler = new TemplateHandler(); + ServiceTemplateMappingHandler mappingHandler = new ServiceTemplateMappingHandler(); + + /** + * get TemplateManager instance. + * @return TemplateManager instance + */ + public static synchronized TemplateManager getInstance() { + if (manager == null) { + manager = new TemplateManager(); } + return manager; + } - private TemplateManager() {} + private TemplateManager() {} - public TemplateData addServiceTemplate(TemplateData templateData) - throws CatalogResourceException { - LOGGER.info("start add template info to db.info:" - + CatalogDbUtil.objectToString(templateData)); - TemplateData data = templateHandler.create(templateData); - LOGGER.info(" template info to db end.info:" + CatalogDbUtil.objectToString(data)); - return data; - } + /** + * add service template. + * + * @param templateData TemplateData + * @return TemplateData + * @throws CatalogResourceException e + */ + public TemplateData addServiceTemplate(TemplateData templateData) + throws CatalogResourceException { + LOGGER + .info("start add template info to db.info:" + CatalogDbUtil.objectToString(templateData)); + TemplateData data = templateHandler.create(templateData); + LOGGER.info(" template info to db end.info:" + CatalogDbUtil.objectToString(data)); + return data; + } - public ServiceTemplateMappingData addServiceTemplateMapping( - ServiceTemplateMappingData templateMappingData) throws CatalogResourceException { - LOGGER.info("start add servicetemplate Mapping info to db.info:" - + CatalogDbUtil.objectToString(templateMappingData)); - ServiceTemplateMappingData data = mappingHandler.create(templateMappingData); - LOGGER.info(" template mapping info to db end.info:" + CatalogDbUtil.objectToString(data)); - return data; - } + /** + * add service template mapping. + * @param templateMappingData mapping data + * @return ServiceTemplateMappingData + * @throws CatalogResourceException e + */ + public ServiceTemplateMappingData addServiceTemplateMapping( + ServiceTemplateMappingData templateMappingData) throws CatalogResourceException { + LOGGER.info("start add servicetemplate Mapping info to db.info:" + + CatalogDbUtil.objectToString(templateMappingData)); + ServiceTemplateMappingData data = mappingHandler.create(templateMappingData); + LOGGER.info(" template mapping info to db end.info:" + CatalogDbUtil.objectToString(data)); + return data; + } - public ArrayList queryServiceTemplateMappingById(String id) - throws CatalogResourceException { - Map queryParam = new HashMap(); - queryParam.put(Parameters.mappingId.name(), id); - LOGGER.info("start query serviceTemplateMapping info by id." + id); - ArrayList data = mappingHandler.query(queryParam); - LOGGER.info("query serviceTemplateMapping info end.size:" + data.size() + "detail:" - + CatalogDbUtil.objectToString(data)); - return data; - } + /** + * query service template mapping by id. + * @param id id + * @return ServiceTemplateMappingData list + * @throws CatalogResourceException e + */ + public ArrayList queryServiceTemplateMappingById(String id) + throws CatalogResourceException { + Map queryParam = new HashMap(); + queryParam.put(Parameters.mappingId.name(), id); + LOGGER.info("start query serviceTemplateMapping info by id." + id); + ArrayList data = mappingHandler.query(queryParam); + LOGGER.info("query serviceTemplateMapping info end.size:" + data.size() + "detail:" + + CatalogDbUtil.objectToString(data)); + return data; + } - public void deleteServiceTemplateMappingById(String id) throws CatalogResourceException { + /** + * delete service template mapping by id. + * @param id id + * @throws CatalogResourceException e + */ + public void deleteServiceTemplateMappingById(String id) throws CatalogResourceException { - LOGGER.info("start delete serviceTemplateMapping info by id." + id); - mappingHandler.delete(id); - LOGGER.info("delete serviceTemplateMapping info end"); - } + LOGGER.info("start delete serviceTemplateMapping info by id." + id); + mappingHandler.delete(id); + LOGGER.info("delete serviceTemplateMapping info end"); + } - public void deleteServiceTemplateMapping(String nodeType, String serviceTemplateId) - throws CatalogResourceException { - Map delParam = new HashMap(); - if (CatalogDbUtil.isNotEmpty(nodeType)) - delParam.put(Parameters.nodeType.name(), nodeType); - if (CatalogDbUtil.isNotEmpty(serviceTemplateId)) - delParam.put(Parameters.serviceTemplateId.name(), serviceTemplateId); - LOGGER.info("start delete serviceTemplateMapping info.nodeType:" + nodeType - + " serviceTemplateId:" + serviceTemplateId); - mappingHandler.delete(delParam); - LOGGER.info("delete serviceTemplateMapping info "); + /** + * delete service template mapping. + * @param nodeType node type + * @param serviceTemplateId service template id + * @throws CatalogResourceException e + */ + public void deleteServiceTemplateMapping(String nodeType, String serviceTemplateId) + throws CatalogResourceException { + Map delParam = new HashMap(); + if (CatalogDbUtil.isNotEmpty(nodeType)) { + delParam.put(Parameters.nodeType.name(), nodeType); } - - public ArrayList queryServiceTemplateMapping(String nodeType, - String serviceTemplateId) throws CatalogResourceException { - Map queryParam = new HashMap(); - if (CatalogDbUtil.isNotEmpty(nodeType)) - queryParam.put(Parameters.nodeType.name(), nodeType); - if (CatalogDbUtil.isNotEmpty(serviceTemplateId)) - queryParam.put(Parameters.serviceTemplateId.name(), serviceTemplateId); - LOGGER.info("start query serviceTemplateMapping info.nodeType:" + nodeType - + " serviceTemplateId:" + serviceTemplateId); - ArrayList data = mappingHandler.query(queryParam); - LOGGER.info("query serviceTemplateMapping info end.size:" + data.size() + "detail:" - + CatalogDbUtil.objectToString(data)); - return data; + if (CatalogDbUtil.isNotEmpty(serviceTemplateId)) { + delParam.put(Parameters.serviceTemplateId.name(), serviceTemplateId); } + LOGGER.info("start delete serviceTemplateMapping info.nodeType:" + nodeType + + " serviceTemplateId:" + serviceTemplateId); + mappingHandler.delete(delParam); + LOGGER.info("delete serviceTemplateMapping info "); + } - public ArrayList queryServiceTemplateById(String id) - throws CatalogResourceException { - Map queryParam = new HashMap(); - queryParam.put(Parameters.serviceTemplateId.name(), id); - LOGGER.info("start query serviceTemplate info by id." + id); - ArrayList data = handler.query(queryParam); - LOGGER.info("query serviceTemplate info end.size:" + data.size() + "detail:" - + CatalogDbUtil.objectToString(data)); - return data; + /** + * query service template mapping. + * @param nodeType nodeType + * @param serviceTemplateId serviceTemplateId + * @return ServiceTemplateMappingData list + * @throws CatalogResourceException e + */ + public ArrayList queryServiceTemplateMapping(String nodeType, + String serviceTemplateId) throws CatalogResourceException { + Map queryParam = new HashMap(); + if (CatalogDbUtil.isNotEmpty(nodeType)) { + queryParam.put(Parameters.nodeType.name(), nodeType); } - - public ArrayList queryServiceTemplate(String type, String version, - String vendor) throws CatalogResourceException { - LOGGER.info("start query serviceTemplate info.type:" + type + " vendor:" + vendor - + " version:" + version); - Map queryParam = new HashMap(); - if (CatalogDbUtil.isNotEmpty(type)) - queryParam.put(Parameters.type.name(), type); - if (CatalogDbUtil.isNotEmpty(vendor)) - queryParam.put(Parameters.vendor.name(), vendor); - if (CatalogDbUtil.isNotEmpty(version)) - queryParam.put(Parameters.version.name(), version); - ArrayList data = handler.query(queryParam); - LOGGER.info("query serviceTemplate info end.size:" + data.size() + "detail:" - + CatalogDbUtil.objectToString(data)); - return data; + if (CatalogDbUtil.isNotEmpty(serviceTemplateId)) { + queryParam.put(Parameters.serviceTemplateId.name(), serviceTemplateId); } + LOGGER.info("start query serviceTemplateMapping info.nodeType:" + nodeType + + " serviceTemplateId:" + serviceTemplateId); + ArrayList data = mappingHandler.query(queryParam); + LOGGER.info("query serviceTemplateMapping info end.size:" + data.size() + "detail:" + + CatalogDbUtil.objectToString(data)); + return data; + } - public ArrayList queryNodeTemplateBySeriviceTemplateId( - String serviceTemplateId) throws CatalogResourceException { - LOGGER.info("start query NodeTemplate info.serviceTemplateId:" + serviceTemplateId); - Map queryParam = new HashMap(); - queryParam.put(Parameters.serviceTemplateId.name(), serviceTemplateId); - ArrayList data = nodeTemplateHandler.query(queryParam); - LOGGER.info("query NodeTemplate info end.size:" + data.size() + "detail:" - + CatalogDbUtil.objectToString(data)); - return data; - } + /** + * query service template by id. + * @param id service template id + * @return ServiceTemplateData list + * @throws CatalogResourceException e + */ + public ArrayList queryServiceTemplateById(String id) + throws CatalogResourceException { + Map queryParam = new HashMap(); + queryParam.put(Parameters.serviceTemplateId.name(), id); + LOGGER.info("start query serviceTemplate info by id." + id); + ArrayList data = handler.query(queryParam); + LOGGER.info("query serviceTemplate info end.size:" + data.size() + "detail:" + + CatalogDbUtil.objectToString(data)); + return data; + } - public ArrayList queryNodeTemplateById(String serviceTemplateId, - String nodeTemplateId) throws CatalogResourceException { - LOGGER.info("start query NodeTemplate info.serviceTemplateId:" + serviceTemplateId - + "nodeTemplateId:" + nodeTemplateId); - Map queryParam = new HashMap(); - if (CatalogDbUtil.isNotEmpty(serviceTemplateId)) - queryParam.put(Parameters.serviceTemplateId.name(), serviceTemplateId); - if (CatalogDbUtil.isNotEmpty(nodeTemplateId)) - queryParam.put(Parameters.nodeTemplateId.name(), nodeTemplateId); - ArrayList data = nodeTemplateHandler.query(queryParam); - LOGGER.info("query NodeTemplate info end.size:" + data.size() + "detail:" - + CatalogDbUtil.objectToString(data)); - return data; + /** + * query service template according to condition. + * @param type template type + * @param version template version + * @param vendor template vendor + * @return ServiceTemplateData list + * @throws CatalogResourceException e + */ + public ArrayList queryServiceTemplate(String type, String version, + String vendor) throws CatalogResourceException { + LOGGER.info("start query serviceTemplate info.type:" + type + " vendor:" + vendor + " version:" + + version); + Map queryParam = new HashMap(); + if (CatalogDbUtil.isNotEmpty(type)) { + queryParam.put(Parameters.type.name(), type); } - - public ArrayList queryServiceTemplateByCsarPackageInfo( - PackageData packageInfo) throws CatalogResourceException { - LOGGER.info("start query serviceTemplate info by package.package:" - + CatalogDbUtil.objectToString(packageInfo)); - String filter = - HqlFactory.getQueryHqlByFilter(ServiceTemplateData.class, packageInfo, - Parameters.csarId.name()); - ArrayList data = handler.unionQuery(filter); - LOGGER.info("query serviceTemplate info end.size:" + data.size() + "detail:" - + CatalogDbUtil.objectToString(data)); - return data; + if (CatalogDbUtil.isNotEmpty(vendor)) { + queryParam.put(Parameters.vendor.name(), vendor); + } + if (CatalogDbUtil.isNotEmpty(version)) { + queryParam.put(Parameters.version.name(), version); } + ArrayList data = handler.query(queryParam); + LOGGER.info("query serviceTemplate info end.size:" + data.size() + "detail:" + + CatalogDbUtil.objectToString(data)); + return data; + } - public void deleteServiceTemplateById(String serviceTemplateId) throws CatalogResourceException { - LOGGER.info("start delete serviceTemplate info.id:" + serviceTemplateId); - ArrayList nodeTemplateList = - queryNodeTemplateBySeriviceTemplateId(serviceTemplateId); - templateHandler.delete(serviceTemplateId, nodeTemplateList); - LOGGER.info(" delete serviceTemplate info end id." + serviceTemplateId); + /** + * query node template service template id. + * @param serviceTemplateId service template id + * @return NodeTemplateData list + * @throws CatalogResourceException e + */ + public ArrayList queryNodeTemplateBySeriviceTemplateId(String serviceTemplateId) + throws CatalogResourceException { + LOGGER.info("start query NodeTemplate info.serviceTemplateId:" + serviceTemplateId); + Map queryParam = new HashMap(); + queryParam.put(Parameters.serviceTemplateId.name(), serviceTemplateId); + ArrayList data = nodeTemplateHandler.query(queryParam); + LOGGER.info("query NodeTemplate info end.size:" + data.size() + "detail:" + + CatalogDbUtil.objectToString(data)); + return data; + } + + /** + * query node template by id. + * @param serviceTemplateId service template id + * @param nodeTemplateId nodetemplate id + * @return NodeTemplateData list + * @throws CatalogResourceException e + */ + public ArrayList queryNodeTemplateById(String serviceTemplateId, + String nodeTemplateId) throws CatalogResourceException { + LOGGER.info("start query NodeTemplate info.serviceTemplateId:" + serviceTemplateId + + "nodeTemplateId:" + nodeTemplateId); + Map queryParam = new HashMap(); + if (CatalogDbUtil.isNotEmpty(serviceTemplateId)) { + queryParam.put(Parameters.serviceTemplateId.name(), serviceTemplateId); + } + if (CatalogDbUtil.isNotEmpty(nodeTemplateId)) { + queryParam.put(Parameters.nodeTemplateId.name(), nodeTemplateId); } + ArrayList data = nodeTemplateHandler.query(queryParam); + LOGGER.info("query NodeTemplate info end.size:" + data.size() + "detail:" + + CatalogDbUtil.objectToString(data)); + return data; + } - public void deleteServiceTemplateByCsarPackageInfo(PackageData packageInfo) - throws CatalogResourceException { - LOGGER.info("start delete serviceTemplate info by package.package:" - + CatalogDbUtil.objectToString(packageInfo)); + /** + * query service template by package infomation. + * @param packageInfo package information + * @return ServiceTemplateData list + * @throws CatalogResourceException e + */ + public ArrayList queryServiceTemplateByCsarPackageInfo( + PackageData packageInfo) throws CatalogResourceException { + LOGGER.info("start query serviceTemplate info by package.package:" + + CatalogDbUtil.objectToString(packageInfo)); + String filter = + HqlFactory.getQueryHqlByFilter(ServiceTemplateData.class, packageInfo, + Parameters.csarId.name()); + ArrayList data = handler.unionQuery(filter); + LOGGER.info("query serviceTemplate info end.size:" + data.size() + "detail:" + + CatalogDbUtil.objectToString(data)); + return data; + } - ArrayList serviceTemplate = - queryServiceTemplateByCsarPackageInfo(packageInfo); - for (int i = 0; i < serviceTemplate.size(); i++) { - deleteServiceTemplateById(serviceTemplate.get(i).getServiceTemplateId()); - } - LOGGER.info("delete serviceTemplate info end."); + /** + * delete service template by id. + * @param serviceTemplateId service template id + * @throws CatalogResourceException e + */ + public void deleteServiceTemplateById(String serviceTemplateId) throws CatalogResourceException { + LOGGER.info("start delete serviceTemplate info.id:" + serviceTemplateId); + ArrayList nodeTemplateList = + queryNodeTemplateBySeriviceTemplateId(serviceTemplateId); + templateHandler.delete(serviceTemplateId, nodeTemplateList); + LOGGER.info(" delete serviceTemplate info end id." + serviceTemplateId); + } + /** + * delete service template by package info. + * @param packageInfo package information + * @throws CatalogResourceException e + */ + public void deleteServiceTemplateByCsarPackageInfo(PackageData packageInfo) + throws CatalogResourceException { + LOGGER.info("start delete serviceTemplate info by package.package:" + + CatalogDbUtil.objectToString(packageInfo)); + + ArrayList serviceTemplate = + queryServiceTemplateByCsarPackageInfo(packageInfo); + for (int i = 0; i < serviceTemplate.size(); i++) { + deleteServiceTemplateById(serviceTemplate.get(i).getServiceTemplateId()); } + LOGGER.info("delete serviceTemplate info end."); + + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/util/CatalogDbUtil.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/util/CatalogDbUtil.java index 6924a305..e0daf80d 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/util/CatalogDbUtil.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/util/CatalogDbUtil.java @@ -13,32 +13,37 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.db.util; -import java.util.UUID; +package org.openo.commontosca.catalog.db.util; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import com.google.gson.Gson; -public class CatalogDbUtil { - private final static Logger logger = LoggerFactory.getLogger(CatalogDbUtil.class); +import java.util.UUID; - public static String generateId() { - return UUID.randomUUID().toString(); - } - public static boolean isNotEmpty(String s) { - return s != null && !"".equals(s) && s.length() > 0; - } +public class CatalogDbUtil { - public static String objectToString(Object obj) { - Gson gson = new Gson(); - if (obj != null) - return gson.toJson(obj); - else - return null; + public static String generateId() { + return UUID.randomUUID().toString(); + } + + public static boolean isNotEmpty(String str) { + return str != null && !"".equals(str) && str.length() > 0; + } + + /** + * exchange object to string. + * @param obj Object + * @return string + */ + public static String objectToString(Object obj) { + Gson gson = new Gson(); + if (obj != null) { + return gson.toJson(obj); + } else { + return null; } + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/util/HqlFactory.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/util/HqlFactory.java index c7db51bf..8565188f 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/util/HqlFactory.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/util/HqlFactory.java @@ -13,177 +13,197 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.util; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** - * a tool class for creating Hibernate's HQL - * - * *@author 10159474 + * a tool class for creating Hibernate's HQL. * */ public class HqlFactory { - private final static Logger logger = LoggerFactory.getLogger(HqlFactory.class); + private static final Logger logger = LoggerFactory.getLogger(HqlFactory.class); - /** - * @param obj the object that used to be generate the hql - * @param excludeProperties the properties that need not to be used - * @param filter the condition after "where" - * @return hibernate hql - */ - public static String getUpdateHql(Object obj, String[] excludeProperties, String filter) { - StringBuffer hql = new StringBuffer(); - String objName = obj.getClass().getSimpleName(); - hql.append("update "); - hql.append(objName); - hql.append(" set "); - Field[] fields = obj.getClass().getDeclaredFields(); - if (obj.getClass().getGenericSuperclass() != null) { - Field[] parentFields = obj.getClass().getSuperclass().getDeclaredFields(); - fields = concat(fields, parentFields); - } - for (Field field : fields) { - String name = field.getName(); - Method method = null; - Object value = null; - if (!contain(excludeProperties, name)) { - String upperName = name.substring(0, 1).toUpperCase() + name.substring(1); - try { - method = obj.getClass().getMethod("get" + upperName); - value = method.invoke(obj); - if (value != null) { - if (value instanceof String) { - hql.append(name); - hql.append("="); - hql.append("'"); - hql.append(value); - hql.append("'"); - hql.append(","); - } else { - hql.append(name); - hql.append("="); - hql.append(value); - hql.append(","); - } - } - } catch (Exception e) { - logger.error("error while creating update hql", e); - } + /** + * get update hql. + * @param obj the object that used to be generate the hql + * @param excludeProperties the properties that need not to be used + * @param filter the condition after "where" + * @return hibernate hql + */ + public static String getUpdateHql(Object obj, String[] excludeProperties, String filter) { + StringBuffer hql = new StringBuffer(); + String objName = obj.getClass().getSimpleName(); + hql.append("update "); + hql.append(objName); + hql.append(" set "); + Field[] fields = obj.getClass().getDeclaredFields(); + if (obj.getClass().getGenericSuperclass() != null) { + Field[] parentFields = obj.getClass().getSuperclass().getDeclaredFields(); + fields = concat(fields, parentFields); + } + for (Field field : fields) { + String name = field.getName(); + Method method = null; + Object value = null; + if (!contain(excludeProperties, name)) { + String upperName = name.substring(0, 1).toUpperCase() + name.substring(1); + try { + method = obj.getClass().getMethod("get" + upperName); + value = method.invoke(obj); + if (value != null) { + if (value instanceof String) { + hql.append(name); + hql.append("="); + hql.append("'"); + hql.append(value); + hql.append("'"); + hql.append(","); + } else { + hql.append(name); + hql.append("="); + hql.append(value); + hql.append(","); } + } + } catch (Exception e1) { + logger.error("error while creating update hql", e1); } + } + } - String sql = hql.toString(); - sql = sql.substring(0, sql.lastIndexOf(",")); - if (filter != null) - sql = sql + " where " + filter; - logger.info("update hql is : " + sql); - return sql; + String sql = hql.toString(); + sql = sql.substring(0, sql.lastIndexOf(",")); + if (filter != null) { + sql = sql + " where " + filter; } + logger.info("update hql is : " + sql); + return sql; + } - public static boolean contain(String[] src, String target) { - if (src == null || src.length == 0 || target == null) - return false; - else { - for (String str : src) { - if (str.equals(target)) - return true; - } + /** + * judge wether target contains src. + * @param src String[] + * @param target String + * @return boolean + */ + public static boolean contain(String[] src, String target) { + if (src == null || src.length == 0 || target == null) { + return false; + } else { + for (String str : src) { + if(str.equals(target)){ + return true; } - return false; + } } + return false; + } - public static T[] concat(T[] first, T[] second) { - T[] result = Arrays.copyOf(first, first.length + second.length); - System.arraycopy(second, 0, result, first.length, second.length); - return result; - } + /** + * concat two array. + * @param first first array + * @param second second array + * @return T + */ + public static T[] concat(T[] first, T[] second) { + T[] result = Arrays.copyOf(first, first.length + second.length); + System.arraycopy(second, 0, result, first.length, second.length); + return result; + } - public static String getOidFilter(String key, String value) { - return key + "= '" + value + "'"; - } + public static String getOidFilter(String key, String value) { + return key + "= '" + value + "'"; + } - public static String getQueryHql(Object data, String column) { - StringBuffer hql = new StringBuffer(); - String objName = data.getClass().getSimpleName(); - hql.append("select q."); - hql.append(column); - hql.append(" from "); - hql.append(objName); - hql.append(" as q where "); - Field[] fields = data.getClass().getDeclaredFields(); - if (data.getClass().getGenericSuperclass() != null) { - Field[] parentFields = data.getClass().getSuperclass().getDeclaredFields(); - fields = concat(fields, parentFields); - } - for (Field field : fields) { - String name = field.getName(); - Method method = null; - Object value = null; - String upperName = name.substring(0, 1).toUpperCase() + name.substring(1); - try { - method = data.getClass().getMethod("get" + upperName); - value = method.invoke(data); - if (value != null) { - if (value instanceof String) { - hql.append("q." + name); - hql.append("="); - hql.append("'"); - hql.append(value); - hql.append("'"); - hql.append(" and "); - } else { - hql.append("q." + name); - hql.append("="); - hql.append(value); - hql.append("and "); - } - } - } catch (Exception e) { - logger.error("error while creating update hql", e); - } + /** + * get query hql. + * @param data Object + * @param column String + * @return String + */ + public static String getQueryHql(Object data, String column) { + StringBuffer hql = new StringBuffer(); + String objName = data.getClass().getSimpleName(); + hql.append("select q."); + hql.append(column); + hql.append(" from "); + hql.append(objName); + hql.append(" as q where "); + Field[] fields = data.getClass().getDeclaredFields(); + if (data.getClass().getGenericSuperclass() != null) { + Field[] parentFields = data.getClass().getSuperclass().getDeclaredFields(); + fields = concat(fields, parentFields); + } + for (Field field : fields) { + String name = field.getName(); + Method method = null; + Object value = null; + String upperName = name.substring(0, 1).toUpperCase() + name.substring(1); + try { + method = data.getClass().getMethod("get" + upperName); + value = method.invoke(data); + if (value != null) { + if (value instanceof String) { + hql.append("q." + name); + hql.append("="); + hql.append("'"); + hql.append(value); + hql.append("'"); + hql.append(" and "); + } else { + hql.append("q." + name); + hql.append("="); + hql.append(value); + hql.append("and "); + } } - String sql = hql.toString(); - sql = sql.substring(0, sql.lastIndexOf("and")); - - logger.info("query hql is : " + sql); - return sql.trim(); + } catch (Exception e1) { + logger.error("error while creating update hql", e1); + } } + String sql = hql.toString(); + sql = sql.substring(0, sql.lastIndexOf("and")); - public static String getQueryHqlByFilter(Class mainObject, Object filterData, String foreignKey) { - StringBuffer hql = new StringBuffer(); - String objName = mainObject.getSimpleName(); - // hql.append("select queryTable."); - hql.append(" from "); - hql.append(objName); - hql.append(" as a where "); - String filterHql = getQueryHql(filterData, foreignKey); - hql.append("a." + foreignKey); - hql.append(" in("); - hql.append(filterHql); - hql.append(")"); - logger.info("QueryHqlByFilter is : " + hql); - return hql.toString(); - } + logger.info("query hql is : " + sql); + return sql.trim(); + } - public static String getDeleteHqlByFilter(Class mainObject, Object filterData, String foreignKey) { - StringBuffer hql = new StringBuffer(); - String objName = mainObject.getSimpleName(); - hql.append("delete from "); - hql.append(objName); - hql.append(" as b where "); - String filterHql = getQueryHql(filterData, foreignKey); - hql.append("b." + foreignKey); - hql.append(" in("); - hql.append(filterHql); - hql.append(")"); - logger.info("DeleteHqlByFilter is : " + hql); - return hql.toString(); - } + public static String getQueryHqlByFilter(Class mainObject, Object filterData, String foreignKey) { + StringBuffer hql = new StringBuffer(); + String objName = mainObject.getSimpleName(); + // hql.append("select queryTable."); + hql.append(" from "); + hql.append(objName); + hql.append(" as a where "); + String filterHql = getQueryHql(filterData, foreignKey); + hql.append("a." + foreignKey); + hql.append(" in("); + hql.append(filterHql); + hql.append(")"); + logger.info("QueryHqlByFilter is : " + hql); + return hql.toString(); + } + + public static String getDeleteHqlByFilter(Class mainObject, Object filterData, String foreignKey) { + StringBuffer hql = new StringBuffer(); + String objName = mainObject.getSimpleName(); + hql.append("delete from "); + hql.append(objName); + hql.append(" as b where "); + String filterHql = getQueryHql(filterData, foreignKey); + hql.append("b." + foreignKey); + hql.append(" in("); + hql.append(filterHql); + hql.append(")"); + logger.info("DeleteHqlByFilter is : " + hql); + return hql.toString(); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/BaseHandler.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/BaseHandler.java index d5840930..1d19ecf8 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/BaseHandler.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/BaseHandler.java @@ -13,155 +13,201 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.wrapper; -import java.util.List; -import java.util.Map; +import com.google.gson.Gson; +import org.openo.commontosca.catalog.db.dao.BaseDao; +import org.openo.commontosca.catalog.db.dao.DaoManager; import org.openo.commontosca.catalog.db.entity.BaseData; import org.openo.commontosca.catalog.db.exception.CatalogResourceException; import org.openo.commontosca.catalog.db.util.CatalogDbUtil; -import org.openo.commontosca.catalog.db.dao.BaseDao; -import org.openo.commontosca.catalog.db.dao.DaoManager; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.Gson; +import java.util.List; +import java.util.Map; + + /** - * an abstract class for NFV wrapper class - * - * provide the common methods to process the CRUD rest request + * an abstract class for NFV wrapper class. + * provide the common methods to process the CRUD rest request. * - * *@author 10159474 - * - * @param */ public abstract class BaseHandler { - private final static Logger logger = LoggerFactory.getLogger(BaseHandler.class); - - public Gson gson = new Gson(); - - @SuppressWarnings({"unchecked", "rawtypes"}) - public T create(T data, String resouceType) throws CatalogResourceException { - T rtnData = null; - logger.info("BaseHandler:start create data.info:" + CatalogDbUtil.objectToString(data)); - try { - check(data); - BaseDao dao = DaoManager.getInstance().getDao(resouceType); - rtnData = (T) dao.create(data); - } catch (CatalogResourceException e) { - logger.error("BaseHandler:error while creating " + resouceType, e); - throw e; - } - logger.info("BaseHandler:create data end.info:" + CatalogDbUtil.objectToString(data)); - return rtnData; + private static final Logger logger = LoggerFactory.getLogger(BaseHandler.class); + + public Gson gson = new Gson(); + + /** + * create date. + * @param data data to create + * @param resouceType resouce type + * @return T + * @throws CatalogResourceException e1 + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + public T create(T data, String resouceType) throws CatalogResourceException { + T rtnData = null; + logger.info("BaseHandler:start create data.info:" + CatalogDbUtil.objectToString(data)); + try { + check(data); + BaseDao dao = DaoManager.getInstance().getDao(resouceType); + rtnData = (T) dao.create(data); + } catch (CatalogResourceException e1) { + logger.error("BaseHandler:error while creating " + resouceType, e1); + throw e1; } - - @SuppressWarnings({"rawtypes", "unchecked"}) - public void delete(T data, String resouceType) throws CatalogResourceException { - logger.info("BaseHandler:start delete data.info:" + CatalogDbUtil.objectToString(data)); - try { - BaseDao dao = DaoManager.getInstance().getDao(resouceType); - dao.delete(data); - } catch (CatalogResourceException e) { - logger.error("BaseHandler:error while deleting " + resouceType, e); - throw e; - } - logger.info("BaseHandler:delete data end"); + logger.info("BaseHandler:create data end.info:" + CatalogDbUtil.objectToString(data)); + return rtnData; + } + + /** + * delete data. + * @param data data to delete + * @param resouceType resource type + * @throws CatalogResourceException e1 + */ + @SuppressWarnings({"rawtypes", "unchecked"}) + public void delete(T data, String resouceType) throws CatalogResourceException { + logger.info("BaseHandler:start delete data.info:" + CatalogDbUtil.objectToString(data)); + try { + BaseDao dao = DaoManager.getInstance().getDao(resouceType); + dao.delete(data); + } catch (CatalogResourceException e1) { + logger.error("BaseHandler:error while deleting " + resouceType, e1); + throw e1; } - - @SuppressWarnings({"rawtypes", "unchecked"}) - public void delete(Map queryParam, String resouceType) - throws CatalogResourceException { - logger.info("BaseHandler:start delete data by condition.info:" - + CatalogDbUtil.objectToString(queryParam)); - List datas; - try { - BaseDao dao = DaoManager.getInstance().getDao(resouceType); - datas = dao.query(queryParam); - for (T data : datas) { - delete(data, resouceType); - } - } catch (CatalogResourceException e) { - logger.error("BaseHandler:error while deleting " + resouceType, e); - throw e; - } - + logger.info("BaseHandler:delete data end"); + } + + /** + * delete data. + * @param queryParam query param + * @param resouceType String + * @throws CatalogResourceException e1 + */ + @SuppressWarnings({"rawtypes", "unchecked"}) + public void delete(Map queryParam, String resouceType) + throws CatalogResourceException { + logger.info("BaseHandler:start delete data by condition.info:" + + CatalogDbUtil.objectToString(queryParam)); + List datas; + try { + BaseDao dao = DaoManager.getInstance().getDao(resouceType); + datas = dao.query(queryParam); + for (T data : datas) { + delete(data, resouceType); + } + } catch (CatalogResourceException e1) { + logger.error("BaseHandler:error while deleting " + resouceType, e1); + throw e1; } - @SuppressWarnings({"rawtypes", "unchecked"}) - public void update(T data, String filter, String resouceType) throws CatalogResourceException { - logger.info("BaseHandler:start update data .info:" + CatalogDbUtil.objectToString(data) - + " filter:" + filter); - try { - check(data); - BaseDao dao = DaoManager.getInstance().getDao(resouceType); - dao.update(data, filter); - - } catch (CatalogResourceException e) { - logger.error("BaseHandler:error while updating " + resouceType, e); - throw e; - } - logger.info("BaseHandler:update data end "); + } + + /** + * update data. + * @param data data to update + * @param filter filter + * @param resouceType resource type + * @throws CatalogResourceException e1 + */ + @SuppressWarnings({"rawtypes", "unchecked"}) + public void update(T data, String filter, String resouceType) throws CatalogResourceException { + logger.info("BaseHandler:start update data .info:" + CatalogDbUtil.objectToString(data) + + " filter:" + filter); + try { + check(data); + BaseDao dao = DaoManager.getInstance().getDao(resouceType); + dao.update(data, filter); + + } catch (CatalogResourceException e1) { + logger.error("BaseHandler:error while updating " + resouceType, e1); + throw e1; } - - @SuppressWarnings({"rawtypes", "unchecked"}) - public List query(Map queryParam, String resouceType) - throws CatalogResourceException { - logger.info("BaseHandler:start query data .info:" - + CatalogDbUtil.objectToString(queryParam)); - List datas = null; - try { - BaseDao dao = DaoManager.getInstance().getDao(resouceType); - datas = dao.query(queryParam); - - } catch (CatalogResourceException e) { - logger.error("BaseHandler:error while querying " + resouceType, e); - throw e; - } - logger.info("BaseHandler: query data end .info:" + CatalogDbUtil.objectToString(datas)); - return datas; + logger.info("BaseHandler:update data end "); + } + + /** + * query data. + * @param queryParam query parameter + * @param resouceType resource type + * @return T list + * @throws CatalogResourceException e1 + */ + @SuppressWarnings({"rawtypes", "unchecked"}) + public List query(Map queryParam, String resouceType) + throws CatalogResourceException { + logger.info("BaseHandler:start query data .info:" + CatalogDbUtil.objectToString(queryParam)); + List datas = null; + try { + BaseDao dao = DaoManager.getInstance().getDao(resouceType); + datas = dao.query(queryParam); + + } catch (CatalogResourceException e1) { + logger.error("BaseHandler:error while querying " + resouceType, e1); + throw e1; } - - @SuppressWarnings({"rawtypes", "unchecked"}) - public List unionQuery(String filter, String resouceType) throws CatalogResourceException { - logger.info("BaseHandler:start union query data.fliter:" + filter); - List datas = null; - try { - BaseDao dao = DaoManager.getInstance().getDao(resouceType); - datas = dao.unionQuery(filter); - - } catch (CatalogResourceException e) { - logger.error("BaseHandler:error while union querying " + resouceType, e); - throw e; - } - logger.info("BaseHandler:union query data end .info:" + CatalogDbUtil.objectToString(datas)); - return datas; + logger.info("BaseHandler: query data end .info:" + CatalogDbUtil.objectToString(datas)); + return datas; + } + + /** + * union query. + * @param filter filter + * @param resouceType resource type + * @return T list + * @throws CatalogResourceException e1 + */ + @SuppressWarnings({"rawtypes", "unchecked"}) + public List unionQuery(String filter, String resouceType) throws CatalogResourceException { + logger.info("BaseHandler:start union query data.fliter:" + filter); + List datas = null; + try { + BaseDao dao = DaoManager.getInstance().getDao(resouceType); + datas = dao.unionQuery(filter); + + } catch (CatalogResourceException e1) { + logger.error("BaseHandler:error while union querying " + resouceType, e1); + throw e1; } - - @SuppressWarnings({"rawtypes", "unchecked"}) - public int unionDelete(String filter, String resouceType) throws CatalogResourceException { - logger.info("BaseHandler:start delete query data.fliter:" + filter); - int num; - try { - BaseDao dao = DaoManager.getInstance().getDao(resouceType); - num = dao.unionDelete(filter); - - } catch (CatalogResourceException e) { - logger.error("BaseHandler:error while union delete " + resouceType, e); - throw e; - } - logger.info("BaseHandler:union delete data end .num:" + num); - return num; + logger.info("BaseHandler:union query data end .info:" + CatalogDbUtil.objectToString(datas)); + return datas; + } + + /** + * union delete. + * @param filter filter + * @param resouceType resource type + * @return int + * @throws CatalogResourceException e1 + */ + @SuppressWarnings({"rawtypes", "unchecked"}) + public int unionDelete(String filter, String resouceType) throws CatalogResourceException { + logger.info("BaseHandler:start delete query data.fliter:" + filter); + int num; + try { + BaseDao dao = DaoManager.getInstance().getDao(resouceType); + num = dao.unionDelete(filter); + + } catch (CatalogResourceException e1) { + logger.error("BaseHandler:error while union delete " + resouceType, e1); + throw e1; } - - /** - * check if the related object id exists in the system - * - * @param data - * @throws CatalogResourceException - */ - public abstract void check(T data) throws CatalogResourceException; + logger.info("BaseHandler:union delete data end .num:" + num); + return num; + } + + /** + * check if the related object id exists in the system. + * + * @param data data to check + * @throws CatalogResourceException e + */ + public abstract void check(T data) throws CatalogResourceException; } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/NodeTemplateHandler.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/NodeTemplateHandler.java index a96e9371..ebed32f4 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/NodeTemplateHandler.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/NodeTemplateHandler.java @@ -13,41 +13,46 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.db.wrapper; -import java.util.ArrayList; -import java.util.Map; +package org.openo.commontosca.catalog.db.wrapper; import org.openo.commontosca.catalog.db.common.CatalogResuorceType; -import org.openo.commontosca.catalog.db.exception.CatalogResourceException; import org.openo.commontosca.catalog.db.entity.NodeTemplateData; +import org.openo.commontosca.catalog.db.exception.CatalogResourceException; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * - ** @author 10159474 - */ -public class NodeTemplateHandler extends BaseHandler { - private static final Logger logger = LoggerFactory.getLogger(NodeTemplateHandler.class); - - public ArrayList query(Map queryParam) - throws CatalogResourceException { - logger.info("NodeTemplateHandler query nodeTemplate info."); - ArrayList data = new ArrayList(); - Object result = query(queryParam, CatalogResuorceType.NODETEMPLATE.name()); - if (result != null) - data = (ArrayList) result; - else - logger.warn("NodeTemplateHandler: query nodeTemplate info is null."); - logger.info("NodeTemplateHandler: query nodeTemplate info end."); - return data; +import java.util.ArrayList; +import java.util.Map; +public class NodeTemplateHandler extends BaseHandler { + private static final Logger logger = LoggerFactory.getLogger(NodeTemplateHandler.class); + + /** + * query node template. + * @param queryParam query parameter + * @return NodeTemplateData list + * @throws CatalogResourceException e + */ + public ArrayList query(Map queryParam) + throws CatalogResourceException { + logger.info("NodeTemplateHandler query nodeTemplate info."); + ArrayList data = new ArrayList(); + Object result = query(queryParam, CatalogResuorceType.NODETEMPLATE.name()); + if (result != null) { + data = (ArrayList) result; + } else { + logger.warn("NodeTemplateHandler: query nodeTemplate info is null."); } + logger.info("NodeTemplateHandler: query nodeTemplate info end."); + return data; - @Override - public void check(NodeTemplateData nodeTemplateData) throws CatalogResourceException { + } - } + @Override + public void check(NodeTemplateData nodeTemplateData) throws CatalogResourceException { + + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/PackageHandler.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/PackageHandler.java index 8fd4d04c..a358d8ca 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/PackageHandler.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/PackageHandler.java @@ -13,10 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.db.wrapper; -import java.util.ArrayList; -import java.util.Map; +package org.openo.commontosca.catalog.db.wrapper; import org.openo.commontosca.catalog.db.common.CatalogResuorceType; import org.openo.commontosca.catalog.db.common.Parameters; @@ -27,94 +25,136 @@ import org.openo.commontosca.catalog.db.util.HqlFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * - ** @author 10159474 - */ +import java.util.ArrayList; +import java.util.Map; + public class PackageHandler extends BaseHandler { - private static final Logger logger = LoggerFactory.getLogger(PackageHandler.class); + private static final Logger logger = LoggerFactory.getLogger(PackageHandler.class); - public PackageData create(PackageData packageData) throws CatalogResourceException { - logger.info("packageHandler:start create package info."); - PackageData data = null; - if (!CatalogDbUtil.isNotEmpty(packageData.getCsarId())) { + /** + * create package data. + * @param packageData package data to create + * @return PackageData + * @throws CatalogResourceException e1 + */ + public PackageData create(PackageData packageData) throws CatalogResourceException { + logger.info("packageHandler:start create package info."); + PackageData data = null; + if (!CatalogDbUtil.isNotEmpty(packageData.getCsarId())) { - logger.info("packageHandler:package info does not have csarid,generate UUID."); - String id = CatalogDbUtil.generateId(); - packageData.setCsarId(id); - } - Object result = create(packageData, CatalogResuorceType.PACKAGE.name()); - if (result != null) - data = (PackageData) result; - else - logger.info("packageHandler: query package info is null."); - logger.info("packageHandler: create package info end."); - return data; + logger.info("packageHandler:package info does not have csarid,generate UUID."); + String id = CatalogDbUtil.generateId(); + packageData.setCsarId(id); } - - public void delete(String id) throws CatalogResourceException { - logger.info("packageHandler:start delete package info."); - PackageData packageData = new PackageData(); - packageData.setCsarId(id); - delete(packageData, CatalogResuorceType.PACKAGE.name()); - logger.info("packageHandler: delete package info end."); + Object result = create(packageData, CatalogResuorceType.PACKAGE.name()); + if (result != null) { + data = (PackageData) result; + } else { + logger.info("packageHandler: query package info is null."); } + logger.info("packageHandler: create package info end."); + return data; + } - public void delete(Map queryParam) throws CatalogResourceException { - logger.info("packageHandler:start delete package info."); - delete(queryParam, CatalogResuorceType.PACKAGE.name()); - logger.info("packageHandler:delete package info end."); - } + /** + * delete data. + * @param id package id + * @throws CatalogResourceException e + */ + public void delete(String id) throws CatalogResourceException { + logger.info("packageHandler:start delete package info."); + PackageData packageData = new PackageData(); + packageData.setCsarId(id); + delete(packageData, CatalogResuorceType.PACKAGE.name()); + logger.info("packageHandler: delete package info end."); + } - public void update(PackageData packageData, String id) throws CatalogResourceException { - // HostData host = gson.fromJson(hostJson, HostData.class); - logger.info("packageHandler:start update package info."); - update(packageData, HqlFactory.getOidFilter(Parameters.csarId.name(), id), - CatalogResuorceType.PACKAGE.name()); - logger.info("packageHandler:update package info end."); - } + /** + * delete data. + * @param queryParam query parameter + * @throws CatalogResourceException e + */ + public void delete(Map queryParam) throws CatalogResourceException { + logger.info("packageHandler:start delete package info."); + delete(queryParam, CatalogResuorceType.PACKAGE.name()); + logger.info("packageHandler:delete package info end."); + } - public int unionDelete(String filter) throws CatalogResourceException { - logger.info("packageHandler delete package info by union.filter:" + filter); - int num = 0; - Object result = unionDelete(filter, CatalogResuorceType.PACKAGE.name()); - if (result != null) - num = (int) result; - else - logger.warn("packageHandler: delete package info is null."); - logger.info("packageHandler: delete package info end.num:" + num); - return num; - } + /** + * update data. + * @param packageData packate data to update + * @param id package id + * @throws CatalogResourceException e + */ + public void update(PackageData packageData, String id) throws CatalogResourceException { + // HostData host = gson.fromJson(hostJson, HostData.class); + logger.info("packageHandler:start update package info."); + update(packageData, HqlFactory.getOidFilter(Parameters.csarId.name(), id), + CatalogResuorceType.PACKAGE.name()); + logger.info("packageHandler:update package info end."); + } - public ArrayList unionQuery(String filter) throws CatalogResourceException { - logger.info("packageHandler query package info by union.filter:" + filter); - ArrayList data = new ArrayList(); - Object result = unionQuery(filter, CatalogResuorceType.PACKAGE.name()); - if (result != null) - data = data = (ArrayList) result; - else - logger.info("packageHandler: query package info is null."); - logger.info("packageHandler: query package info end"); - return data; + /** + * union delete. + * @param filter delete filter + * @return int + * @throws CatalogResourceException e + */ + public int unionDelete(String filter) throws CatalogResourceException { + logger.info("packageHandler delete package info by union.filter:" + filter); + int num = 0; + Object result = unionDelete(filter, CatalogResuorceType.PACKAGE.name()); + if (result != null) { + num = (int) result; + } else { + logger.warn("packageHandler: delete package info is null."); } + logger.info("packageHandler: delete package info end.num:" + num); + return num; + } - public ArrayList query(Map queryParam) - throws CatalogResourceException { - logger.info("packageHandler:start query package info."); - ArrayList data = new ArrayList(); - Object result = query(queryParam, CatalogResuorceType.PACKAGE.name()); - if (result != null) - data = (ArrayList) result; - else - logger.info("packageHandler: query package info is null."); - logger.info("packageHandler: query package info end."); - return data; + /** + * union query. + * @param filter query filter + * @return PackageData list + * @throws CatalogResourceException e + */ + public ArrayList unionQuery(String filter) throws CatalogResourceException { + logger.info("packageHandler query package info by union.filter:" + filter); + ArrayList data = new ArrayList(); + Object result = unionQuery(filter, CatalogResuorceType.PACKAGE.name()); + if (result != null) { + data = data = (ArrayList) result; + } else { + logger.info("packageHandler: query package info is null."); + } + logger.info("packageHandler: query package info end"); + return data; + } + /** + * query package data by map. + * @param queryParam map data + * @return PackageData list + * @throws CatalogResourceException e + */ + public ArrayList query(Map queryParam) + throws CatalogResourceException { + logger.info("packageHandler:start query package info."); + ArrayList data = new ArrayList(); + Object result = query(queryParam, CatalogResuorceType.PACKAGE.name()); + if (result != null) { + data = (ArrayList) result; + } else { + logger.info("packageHandler: query package info is null."); } + logger.info("packageHandler: query package info end."); + return data; + } - @Override - public void check(PackageData packageData) throws CatalogResourceException { + @Override + public void check(PackageData packageData) throws CatalogResourceException { - } + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/ServiceTemplateHandler.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/ServiceTemplateHandler.java index 4412dee3..d0fc564d 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/ServiceTemplateHandler.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/ServiceTemplateHandler.java @@ -13,10 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.db.wrapper; -import java.util.ArrayList; -import java.util.Map; +package org.openo.commontosca.catalog.db.wrapper; import org.openo.commontosca.catalog.db.common.CatalogResuorceType; import org.openo.commontosca.catalog.db.entity.ServiceTemplateData; @@ -25,54 +23,74 @@ import org.openo.commontosca.catalog.db.exception.CatalogResourceException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * - ** @author 10159474 - */ +import java.util.ArrayList; +import java.util.Map; + public class ServiceTemplateHandler extends BaseHandler { - private static final Logger logger = LoggerFactory.getLogger(ServiceTemplateHandler.class); + private static final Logger logger = LoggerFactory.getLogger(ServiceTemplateHandler.class); - @Override - public void check(TemplateData data) throws CatalogResourceException { - // TODO Auto-generated method stub + @Override + public void check(TemplateData data) throws CatalogResourceException { + // TODO Auto-generated method stub - } + } - public ArrayList query(Map queryParam) - throws CatalogResourceException { - logger.info("ServiceTemplateHandler query serviceTemplate info."); - ArrayList data = new ArrayList(); - Object result = query(queryParam, CatalogResuorceType.SERVICETEMPLATE.name()); - if (result != null) - data = (ArrayList) result; - else - logger.info("ServiceTemplateHandler: query serviceTemplate info is null."); - logger.info("ServiceTemplateHandler: query serviceTemplate info end."); - return data; + /** + * query service template data by map. + * @param queryParam map data + * @return ServiceTemplateData list + * @throws CatalogResourceException e + */ + public ArrayList query(Map queryParam) + throws CatalogResourceException { + logger.info("ServiceTemplateHandler query serviceTemplate info."); + ArrayList data = new ArrayList(); + Object result = query(queryParam, CatalogResuorceType.SERVICETEMPLATE.name()); + if (result != null) { + data = (ArrayList) result; + } else { + logger.info("ServiceTemplateHandler: query serviceTemplate info is null."); } + logger.info("ServiceTemplateHandler: query serviceTemplate info end."); + return data; + } - public ArrayList unionQuery(String filter) throws CatalogResourceException { - logger.info("ServiceTemplateHandler query serviceTemplate info by union.filter:" + filter); - ArrayList data = new ArrayList(); - Object result = unionQuery(filter, CatalogResuorceType.SERVICETEMPLATE.name()); - if (result != null) - data = (ArrayList) result; - else - logger.info("ServiceTemplateHandler: query serviceTemplate info is null."); - logger.info("ServiceTemplateHandler: query serviceTemplate info end."); - return data; + /** + * query service template by union query. + * @param filter query filter + * @return ServiceTemplateData list + * @throws CatalogResourceException e + */ + public ArrayList unionQuery(String filter) throws CatalogResourceException { + logger.info("ServiceTemplateHandler query serviceTemplate info by union.filter:" + filter); + ArrayList data = new ArrayList(); + Object result = unionQuery(filter, CatalogResuorceType.SERVICETEMPLATE.name()); + if (result != null) { + data = (ArrayList) result; + } else { + logger.info("ServiceTemplateHandler: query serviceTemplate info is null."); } + logger.info("ServiceTemplateHandler: query serviceTemplate info end."); + return data; + } - public int unionDelete(String filter) throws CatalogResourceException { - logger.info("ServiceTemplateHandler delete serviceTemplate info by union.filter:" + filter); - int num = 0; - Object result = unionDelete(filter, CatalogResuorceType.SERVICETEMPLATE.name()); - if (result != null) - num = (int) result; - else - logger.info("ServiceTemplateHandler: delete serviceTemplate info is null."); - logger.info("ServiceTemplateHandler: delete serviceTemplate info end.num:" + num); - return num; + /** + * union delete. + * @param filter delete filter + * @return int + * @throws CatalogResourceException e + */ + public int unionDelete(String filter) throws CatalogResourceException { + logger.info("ServiceTemplateHandler delete serviceTemplate info by union.filter:" + filter); + int num = 0; + Object result = unionDelete(filter, CatalogResuorceType.SERVICETEMPLATE.name()); + if (result != null) { + num = (int) result; + } else { + logger.info("ServiceTemplateHandler: delete serviceTemplate info is null."); } + logger.info("ServiceTemplateHandler: delete serviceTemplate info end.num:" + num); + return num; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/ServiceTemplateMappingHandler.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/ServiceTemplateMappingHandler.java index 25f7982e..def8dae5 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/ServiceTemplateMappingHandler.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/ServiceTemplateMappingHandler.java @@ -13,80 +13,101 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.db.wrapper; -import java.util.ArrayList; -import java.util.Map; +package org.openo.commontosca.catalog.db.wrapper; -import org.openo.commontosca.catalog.db.exception.CatalogResourceException; -import org.openo.commontosca.catalog.db.util.CatalogDbUtil; import org.openo.commontosca.catalog.db.common.CatalogResuorceType; import org.openo.commontosca.catalog.db.entity.ServiceTemplateMappingData; +import org.openo.commontosca.catalog.db.exception.CatalogResourceException; +import org.openo.commontosca.catalog.db.util.CatalogDbUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * - ** @author 10159474 - */ +import java.util.ArrayList; +import java.util.Map; + + public class ServiceTemplateMappingHandler extends BaseHandler { - private static final Logger logger = LoggerFactory - .getLogger(ServiceTemplateMappingHandler.class); - - public ServiceTemplateMappingData create(ServiceTemplateMappingData serviceTemplateMappingData) - throws CatalogResourceException { - logger.info("ServiceTemplateMappingHandler:start create serviceTemplateMapping info."); - ServiceTemplateMappingData data = null; - if (!CatalogDbUtil.isNotEmpty(serviceTemplateMappingData.getMappingId())) { - - logger.info("ServiceTemplateMappingHandler:mapping info does not have mappingId,generate UUID."); - String id = CatalogDbUtil.generateId(); - serviceTemplateMappingData.setMappingId(id); - } - Object result = - create(serviceTemplateMappingData, - CatalogResuorceType.SERVICETEMPLATEMAPPING.name()); - if (result != null) - data = (ServiceTemplateMappingData) result; - else - logger.info("ServiceTemplateMappingHandler: query mapping info is null."); - logger.info("ServiceTemplateMappingHandler: create mapping info end."); - return data; - } + private static final Logger logger = LoggerFactory.getLogger(ServiceTemplateMappingHandler.class); - public void delete(String id) throws CatalogResourceException { - logger.info("ServiceTemplateMappingHandler:start delete mapping info."); - ServiceTemplateMappingData ServiceTemplateMappingData = new ServiceTemplateMappingData(); - ServiceTemplateMappingData.setMappingId(id); - delete(ServiceTemplateMappingData, CatalogResuorceType.SERVICETEMPLATEMAPPING.name()); - logger.info("ServiceTemplateMappingHandler: delete mapping info end."); + /** + * create service template data. + * @param serviceTemplateMappingData service template maping data + * @return ServiceTemplateMappingData + * @throws CatalogResourceException e + */ + public ServiceTemplateMappingData create(ServiceTemplateMappingData serviceTemplateMappingData) + throws CatalogResourceException { + logger.info("ServiceTemplateMappingHandler:start create serviceTemplateMapping info."); + ServiceTemplateMappingData data = null; + if (!CatalogDbUtil.isNotEmpty(serviceTemplateMappingData.getMappingId())) { + logger.info( + "ServiceTemplateMappingHandler:mapping info " + "does not have mappingId,generate UUID."); + String id = CatalogDbUtil.generateId(); + serviceTemplateMappingData.setMappingId(id); } - - public void delete(Map delParam) throws CatalogResourceException { - logger.info("ServiceTemplateMappingHandler:start delete mapping info."); - delete(delParam, CatalogResuorceType.SERVICETEMPLATEMAPPING.name()); - logger.info("ServiceTemplateMappingHandler:delete mapping info end."); + Object result = + create(serviceTemplateMappingData, CatalogResuorceType.SERVICETEMPLATEMAPPING.name()); + if (result != null) { + data = (ServiceTemplateMappingData) result; + } else { + logger.info("ServiceTemplateMappingHandler: query mapping info is null."); } + logger.info("ServiceTemplateMappingHandler: create mapping info end."); + return data; + } + + /** + * delete data by id. + * @param id service template id + * @throws CatalogResourceException e + */ + public void delete(String id) throws CatalogResourceException { + logger.info("ServiceTemplateMappingHandler:start delete mapping info."); + ServiceTemplateMappingData serviceTemplateMappingData = new ServiceTemplateMappingData(); + serviceTemplateMappingData.setMappingId(id); + delete(serviceTemplateMappingData, CatalogResuorceType.SERVICETEMPLATEMAPPING.name()); + logger.info("ServiceTemplateMappingHandler: delete mapping info end."); + } - public ArrayList query(Map queryParam) - throws CatalogResourceException { - logger.info("ServiceTemplateMappingHandler:start query mapping info."); - ArrayList data = new ArrayList(); - Object result = query(queryParam, CatalogResuorceType.SERVICETEMPLATEMAPPING.name()); - if (result != null) - data = (ArrayList) result; - else - logger.info("ServiceTemplateMappingHandler: query mapping info is null."); - logger.info("ServiceTemplateMappingHandler: query mapping info end."); - return data; + /** + * delete data. + * @param delParam delete data according to delParam + * @throws CatalogResourceException e + */ + public void delete(Map delParam) throws CatalogResourceException { + logger.info("ServiceTemplateMappingHandler:start delete mapping info."); + delete(delParam, CatalogResuorceType.SERVICETEMPLATEMAPPING.name()); + logger.info("ServiceTemplateMappingHandler:delete mapping info end."); + } + /** + * query service template mapping data. + * @param queryParam query map + * @return ServiceTemplateMappingData list + * @throws CatalogResourceException e + */ + public ArrayList query(Map queryParam) + throws CatalogResourceException { + logger.info("ServiceTemplateMappingHandler:start query mapping info."); + ArrayList data = new ArrayList(); + Object result = query(queryParam, CatalogResuorceType.SERVICETEMPLATEMAPPING.name()); + if (result != null) { + data = (ArrayList) result; + } else { + logger.info("ServiceTemplateMappingHandler: query mapping info is null."); } + logger.info("ServiceTemplateMappingHandler: query mapping info end."); + return data; - @Override - public void check(ServiceTemplateMappingData data) throws CatalogResourceException { - // TODO Auto-generated method stub + } - } + @Override + public void check(ServiceTemplateMappingData data) throws CatalogResourceException { + // TODO Auto-generated method stub + + } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/TemplateHandler.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/TemplateHandler.java index 714dd06b..079f95e2 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/TemplateHandler.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/TemplateHandler.java @@ -13,64 +13,75 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.db.wrapper; -import java.util.ArrayList; +package org.openo.commontosca.catalog.db.wrapper; -import org.openo.commontosca.catalog.db.entity.TemplateData; -import org.openo.commontosca.catalog.db.exception.CatalogResourceException; -import org.openo.commontosca.catalog.db.util.CatalogDbUtil; import org.openo.commontosca.catalog.db.common.CatalogResuorceType; import org.openo.commontosca.catalog.db.entity.NodeTemplateData; import org.openo.commontosca.catalog.db.entity.ServiceTemplateData; +import org.openo.commontosca.catalog.db.entity.TemplateData; +import org.openo.commontosca.catalog.db.exception.CatalogResourceException; +import org.openo.commontosca.catalog.db.util.CatalogDbUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * - ** @author 10159474 - */ +import java.util.ArrayList; + public class TemplateHandler extends BaseHandler { - private static final Logger logger = LoggerFactory.getLogger(TemplateHandler.class); + private static final Logger logger = LoggerFactory.getLogger(TemplateHandler.class); - public TemplateData create(TemplateData templateData) throws CatalogResourceException { - logger.info("TemplateHandler create template info."); - TemplateData data = null; - String serviceTemplateOid = templateData.getServiceTemplate().getServiceTemplateId(); - if (!CatalogDbUtil.isNotEmpty(serviceTemplateOid)) { - logger.info("TemplateHandler:template info does not have oid,generate UUID."); - serviceTemplateOid = CatalogDbUtil.generateId(); - templateData.getServiceTemplate().setServiceTemplateId(serviceTemplateOid); - } - for (NodeTemplateData nodeData : templateData.getNodeTemplates()) { - nodeData.setNodeTemplateId(CatalogDbUtil.generateId()); - nodeData.setServiceTemplateId(serviceTemplateOid); - } - Object result = create(templateData, CatalogResuorceType.TEMPLATE.name()); - if (result != null) - data = (TemplateData) result; - else - logger.info("TemplateHandler: query template info is null."); - logger.info("TemplateHandler: create template info end."); - return data; + /** + * create template data. + * @param templateData template data to create + * @return TemplateData + * @throws CatalogResourceException e + */ + public TemplateData create(TemplateData templateData) throws CatalogResourceException { + logger.info("TemplateHandler create template info."); + TemplateData data = null; + String serviceTemplateOid = templateData.getServiceTemplate().getServiceTemplateId(); + if (!CatalogDbUtil.isNotEmpty(serviceTemplateOid)) { + logger.info("TemplateHandler:template info does not have oid,generate UUID."); + serviceTemplateOid = CatalogDbUtil.generateId(); + templateData.getServiceTemplate().setServiceTemplateId(serviceTemplateOid); } + for (NodeTemplateData nodeData : templateData.getNodeTemplates()) { + nodeData.setNodeTemplateId(CatalogDbUtil.generateId()); + nodeData.setServiceTemplateId(serviceTemplateOid); + } + Object result = create(templateData, CatalogResuorceType.TEMPLATE.name()); + if (result != null) { + data = (TemplateData) result; + } else { + logger.info("TemplateHandler: query template info is null."); + } + logger.info("TemplateHandler: create template info end."); + return data; + } - @Override - public void check(TemplateData data) throws CatalogResourceException { - // TODO Auto-generated method stub + @Override + public void check(TemplateData data) throws CatalogResourceException { + // TODO Auto-generated method stub - } + } - public void delete(String serviceTemplateId, ArrayList nodeTemplateList) - throws CatalogResourceException { - logger.info("TemplateHandler delete Template info."); - TemplateData templateData = new TemplateData(); - ServiceTemplateData serviceTemplateData = new ServiceTemplateData(); - serviceTemplateData.setServiceTemplateId(serviceTemplateId); - templateData.setServiceTemplate(serviceTemplateData); - templateData.setNodeTemplates(nodeTemplateList); - delete(templateData, CatalogResuorceType.TEMPLATE.name()); - logger.info("TemplateHandler: delete Template info end."); - } + /** + * delete node template. + * @param serviceTemplateId service template id + * @param nodeTemplateList node template list + * @throws CatalogResourceException e + */ + public void delete(String serviceTemplateId, ArrayList nodeTemplateList) + throws CatalogResourceException { + logger.info("TemplateHandler delete Template info."); + TemplateData templateData = new TemplateData(); + ServiceTemplateData serviceTemplateData = new ServiceTemplateData(); + serviceTemplateData.setServiceTemplateId(serviceTemplateId); + templateData.setServiceTemplate(serviceTemplateData); + templateData.setNodeTemplates(nodeTemplateList); + delete(templateData, CatalogResuorceType.TEMPLATE.name()); + logger.info("TemplateHandler: delete Template info end."); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/CSARPackage.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/CSARPackage.java deleted file mode 100644 index 671a8514..00000000 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/CSARPackage.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Copyright 2016 [ZTE] and others. - * - * Licensed 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.openo.commontosca.catalog.entity; - -public class CSARPackage { - private String id; - private String name; - private String createTime; - private String size; - private String status; - private String deletionPending; - private String format; - private String url; - private String type; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getFormat() { - return format; - } - - public void setFormat(String format) { - this.format = format; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getDeletionPending() { - return deletionPending; - } - - public void setDeletionPending(String deletionPending) { - this.deletionPending = deletionPending; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getCreateTime() { - return createTime; - } - - public void setCreateTime(String createTime) { - this.createTime = createTime; - } - - public String getSize() { - return size; - } - - public void setSize(String size) { - this.size = size; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - -} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/CSARQueryCondition.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/CSARQueryCondition.java deleted file mode 100644 index a9c43e4c..00000000 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/CSARQueryCondition.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright 2016 [ZTE] and others. - * - * Licensed 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.openo.commontosca.catalog.entity; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@NoArgsConstructor -@AllArgsConstructor -public class CSARQueryCondition { - - private String csarId; - - private String name; - - private String provider; - - private String version; - - private Boolean deletionPending; - - private EnumType type; -} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/CsarPackage.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/CsarPackage.java new file mode 100644 index 00000000..35f2ca54 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/CsarPackage.java @@ -0,0 +1,102 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.entity; + +public class CsarPackage { + private String id; + private String name; + private String createTime; + private String size; + private String status; + private String deletionPending; + private String format; + private String url; + private String type; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getFormat() { + return format; + } + + public void setFormat(String format) { + this.format = format; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getDeletionPending() { + return deletionPending; + } + + public void setDeletionPending(String deletionPending) { + this.deletionPending = deletionPending; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCreateTime() { + return createTime; + } + + public void setCreateTime(String createTime) { + this.createTime = createTime; + } + + public String getSize() { + return size; + } + + public void setSize(String size) { + this.size = size; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/CsarQueryCondition.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/CsarQueryCondition.java new file mode 100644 index 00000000..1b8231ee --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/CsarQueryCondition.java @@ -0,0 +1,39 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class CsarQueryCondition { + + private String csarId; + + private String name; + + private String provider; + + private String version; + + private Boolean deletionPending; + + private EnumType type; +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumOnboardState.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumOnboardState.java index c4cab536..bbd87602 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumOnboardState.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumOnboardState.java @@ -13,22 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.entity; -/** - * @author 00164331 - * - */ public enum EnumOnboardState { - onBoarded("onBoarded"), nonOnBoarded("non-onBoarded"); - - String value; + onBoarded("onBoarded"), nonOnBoarded("non-onBoarded"); + + String value; + + EnumOnboardState(String value) { + this.value = value; + } - EnumOnboardState(String value) { - this.value = value; - } - - public String getValue() { - return value; - } + public String getValue() { + return value; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumOperationalState.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumOperationalState.java index b1f16ec6..1dd4acb5 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumOperationalState.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumOperationalState.java @@ -13,8 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.entity; public enum EnumOperationalState { - Enabled, Disabled + Enabled, Disabled } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumProcessState.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumProcessState.java index 62dab552..2bcbd57e 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumProcessState.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumProcessState.java @@ -13,12 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.entity; -/** - * @author 00164331 - * - */ public enum EnumProcessState { - normal, onBoarding, onBoardFailed, deleting, deleteFailed + normal, onBoarding, onBoardFailed, deleting, deleteFailed } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumType.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumType.java index 7a25d748..28e70fd7 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumType.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumType.java @@ -13,8 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.entity; public enum EnumType { - GSAR, SSAR, NSAR, NFAR + GSAR, SSAR, NSAR, NFAR } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumUsageState.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumUsageState.java index e2ffed13..1f4a61ce 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumUsageState.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumUsageState.java @@ -13,8 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.entity; public enum EnumUsageState { - InUse, NotInUse + InUse, NotInUse } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/VnfPackage.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/VnfPackage.java index 2d3e80c4..520ebe59 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/VnfPackage.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/VnfPackage.java @@ -13,88 +13,89 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.entity; public class VnfPackage { - private String vnfPackageId; - private String name; - private String version; - private String provider; - private String vnfd; - private EnumOperationalState operationalState = EnumOperationalState.Disabled; - private EnumUsageState usageState = EnumUsageState.InUse; - private String deletionPending; - private String vnfPackageUrl; - - public String getVnfPackageId() { - return vnfPackageId; - } - - public void setVnfPackageId(String vnfPackageId) { - this.vnfPackageId = vnfPackageId; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getProvider() { - return provider; - } - - public void setProvider(String provider) { - this.provider = provider; - } - - public String getVnfd() { - return vnfd; - } - - public void setVnfd(String vnfd) { - this.vnfd = vnfd; - } - - public EnumOperationalState getOperationalState() { - return operationalState; - } - - public void setOperationalState(EnumOperationalState operationalState) { - this.operationalState = operationalState; - } - - public EnumUsageState getUsageState() { - return usageState; - } - - public void setUsageState(EnumUsageState usageState) { - this.usageState = usageState; - } - - public String getVnfPackageUrl() { - return vnfPackageUrl; - } - - public void setVnfPackageUrl(String vnfPackageUrl) { - this.vnfPackageUrl = vnfPackageUrl; - } - - public String getDeletionPending() { - return deletionPending; - } - - public void setDeletionPending(String deletionPending) { - this.deletionPending = deletionPending; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } + private String vnfPackageId; + private String name; + private String version; + private String provider; + private String vnfd; + private EnumOperationalState operationalState = EnumOperationalState.Disabled; + private EnumUsageState usageState = EnumUsageState.InUse; + private String deletionPending; + private String vnfPackageUrl; + + public String getVnfPackageId() { + return vnfPackageId; + } + + public void setVnfPackageId(String vnfPackageId) { + this.vnfPackageId = vnfPackageId; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getProvider() { + return provider; + } + + public void setProvider(String provider) { + this.provider = provider; + } + + public String getVnfd() { + return vnfd; + } + + public void setVnfd(String vnfd) { + this.vnfd = vnfd; + } + + public EnumOperationalState getOperationalState() { + return operationalState; + } + + public void setOperationalState(EnumOperationalState operationalState) { + this.operationalState = operationalState; + } + + public EnumUsageState getUsageState() { + return usageState; + } + + public void setUsageState(EnumUsageState usageState) { + this.usageState = usageState; + } + + public String getVnfPackageUrl() { + return vnfPackageUrl; + } + + public void setVnfPackageUrl(String vnfPackageUrl) { + this.vnfPackageUrl = vnfPackageUrl; + } + + public String getDeletionPending() { + return deletionPending; + } + + public void setDeletionPending(String deletionPending) { + this.deletionPending = deletionPending; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/request/PackageBasicInfo.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/request/PackageBasicInfo.java index 998c2121..31924c89 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/request/PackageBasicInfo.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/request/PackageBasicInfo.java @@ -13,26 +13,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.entity.request; -import org.openo.commontosca.catalog.entity.EnumType; +package org.openo.commontosca.catalog.entity.request; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; +import org.openo.commontosca.catalog.entity.EnumType; + @Data @NoArgsConstructor @AllArgsConstructor public class PackageBasicInfo { - private String provider; + private String provider; - private EnumType type; + private EnumType type; - private String version; + private String version; - private String format; + private String format; } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/request/UploadPackageFromFtpRequest.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/request/UploadPackageFromFtpRequest.java index c3a7850b..0bc271fc 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/request/UploadPackageFromFtpRequest.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/request/UploadPackageFromFtpRequest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.entity.request; import lombok.AllArgsConstructor; @@ -21,21 +22,17 @@ import lombok.NoArgsConstructor; import org.openo.commontosca.catalog.entity.EnumType; -/** - * @author 00164331 - * - */ @Data @NoArgsConstructor @AllArgsConstructor public class UploadPackageFromFtpRequest { - private String provider; + private String provider; - private EnumType type; + private EnumType type; - private String version; + private String version; - private String ftpUrl; + private String ftpUrl; } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/response/CsarFileUriResponse.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/response/CsarFileUriResponse.java index a418cc75..158a68a2 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/response/CsarFileUriResponse.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/response/CsarFileUriResponse.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.entity.response; import lombok.AllArgsConstructor; @@ -20,16 +21,12 @@ import lombok.Data; import lombok.NoArgsConstructor; -/** - * @author 00164331 - * - */ @Data @NoArgsConstructor @AllArgsConstructor public class CsarFileUriResponse { - private String downloadUri; + private String downloadUri; - private String localPath; + private String localPath; } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/response/PackageMeta.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/response/PackageMeta.java index e727c3e6..356bc07b 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/response/PackageMeta.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/response/PackageMeta.java @@ -13,49 +13,50 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.entity.response; -import org.openo.commontosca.catalog.entity.EnumProcessState; -import org.openo.commontosca.catalog.entity.EnumOperationalState; -import org.openo.commontosca.catalog.entity.EnumUsageState; +package org.openo.commontosca.catalog.entity.response; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; +import org.openo.commontosca.catalog.entity.EnumOperationalState; +import org.openo.commontosca.catalog.entity.EnumProcessState; +import org.openo.commontosca.catalog.entity.EnumUsageState; + @Data @NoArgsConstructor @AllArgsConstructor public class PackageMeta { - private String csarId; + private String csarId; - private String name; + private String name; - private String downloadUri; + private String downloadUri; - private String size; + private String size; - private String version; + private String version; - private String provider; + private String provider; - private String type; + private String type; - private String format; + private String format; - private boolean deletionPending; + private boolean deletionPending; - private String createTime; + private String createTime; - private String modifyTime; + private String modifyTime; - private EnumOperationalState operationalState; + private EnumOperationalState operationalState; - private EnumUsageState usageState; + private EnumUsageState usageState; - private String onBoardState; + private String onBoardState; - private EnumProcessState processState; + private EnumProcessState processState; } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/response/UpdatePackageResponse.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/response/UpdatePackageResponse.java index 6c7beb73..1713e705 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/response/UpdatePackageResponse.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/response/UpdatePackageResponse.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.entity.response; import lombok.AllArgsConstructor; @@ -24,6 +25,6 @@ import lombok.NoArgsConstructor; @AllArgsConstructor public class UpdatePackageResponse { - private String usageState; + private String usageState; } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/response/UploadPackageResponse.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/response/UploadPackageResponse.java index 3542155f..761bfe3b 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/response/UploadPackageResponse.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/response/UploadPackageResponse.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.entity.response; import lombok.AllArgsConstructor; @@ -25,6 +26,6 @@ import lombok.NoArgsConstructor; @AllArgsConstructor public class UploadPackageResponse { - private String csarId; + private String csarId; } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/externalservice/msb/MicroserviceBusConsumer.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/externalservice/msb/MicroserviceBusConsumer.java index 5e0acf4d..03e45af5 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/externalservice/msb/MicroserviceBusConsumer.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/externalservice/msb/MicroserviceBusConsumer.java @@ -13,33 +13,35 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.externalservice.msb; +package org.openo.commontosca.catalog.externalservice.msb; +import com.eclipsesource.jaxrs.consumer.ConsumerFactory; import org.glassfish.jersey.client.ClientConfig; import org.openo.commontosca.catalog.common.Config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.eclipsesource.jaxrs.consumer.ConsumerFactory; -/** - * @author 10159474 - * - */ public class MicroserviceBusConsumer { - private static final Logger LOG = LoggerFactory.getLogger(MicroserviceBusConsumer.class); + private static final Logger LOG = LoggerFactory.getLogger(MicroserviceBusConsumer.class); - public static boolean registerService(ServiceRegisterEntity entity) { - ClientConfig config = new ClientConfig(); - try { - MicroserviceBusRest resourceserviceproxy = ConsumerFactory.createConsumer( - Config.getConfigration().getMsbServerAddr(),config, MicroserviceBusRest.class); - resourceserviceproxy.registerServce("false", entity); - } catch (Exception e) { - LOG.error("microservice register failed!" + e.getMessage()); - return false; - } - return true; + /** + * register service to MSB. + * @param entity ServiceRegisterEntity + * @return boolean + */ + public static boolean registerService(ServiceRegisterEntity entity) { + ClientConfig config = new ClientConfig(); + try { + MicroserviceBusRest resourceserviceproxy = + ConsumerFactory.createConsumer(Config.getConfigration().getMsbServerAddr(), config, + MicroserviceBusRest.class); + resourceserviceproxy.registerServce("false", entity); + } catch (Exception e1) { + LOG.error("microservice register failed!" + e1.getMessage()); + return false; } + return true; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/externalservice/msb/MicroserviceBusRest.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/externalservice/msb/MicroserviceBusRest.java index 3afe2220..69e9b89f 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/externalservice/msb/MicroserviceBusRest.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/externalservice/msb/MicroserviceBusRest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.externalservice.msb; import javax.ws.rs.Consumes; @@ -22,17 +23,13 @@ import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; - -/** - * @author 10159474 - * - */ @Path("/openoapi/microservices/v1/services") -//@Path("/api/microservices/v1/services") +// @Path("/api/microservices/v1/services") public interface MicroserviceBusRest { - @Path("") - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public ServiceRegisterEntity registerServce(@QueryParam("createOrUpdate") String createOrUpdate,ServiceRegisterEntity entity)throws Exception; + @Path("") + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public ServiceRegisterEntity registerServce(@QueryParam("createOrUpdate") String createOrUpdate, + ServiceRegisterEntity entity) throws Exception; } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/externalservice/msb/ServiceNode.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/externalservice/msb/ServiceNode.java index 90178942..4f251577 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/externalservice/msb/ServiceNode.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/externalservice/msb/ServiceNode.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.externalservice.msb; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -21,17 +22,13 @@ import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -/** - * @author 10159474 - * - */ @Data @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class ServiceNode { - private String ip; - private String port; - private int ttl; + private String ip; + private String port; + private int ttl; } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/externalservice/msb/ServiceRegisterEntity.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/externalservice/msb/ServiceRegisterEntity.java index 95a1d300..30bed2a0 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/externalservice/msb/ServiceRegisterEntity.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/externalservice/msb/ServiceRegisterEntity.java @@ -13,9 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.externalservice.msb; -import java.util.ArrayList; +package org.openo.commontosca.catalog.externalservice.msb; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -23,29 +22,33 @@ import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -/** - * @author 10159474 - * - */ +import java.util.ArrayList; + + @Data @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class ServiceRegisterEntity { - private String serviceName; - private String version; - private String url; - private String protocol; - private String visualRange; - private ArrayList nodes = new ArrayList(); - - public void setSingleNode(String ip, String port, int ttl) { - ServiceNode node = new ServiceNode(); - node.setIp(ip); - node.setPort(port); - node.setTtl(ttl); - nodes.add(node); - } + private String serviceName; + private String version; + private String url; + private String protocol; + private String visualRange; + private ArrayList nodes = new ArrayList(); -} + /** + * set single node. + * @param ip ip + * @param port port + * @param ttl ttl + */ + public void setSingleNode(String ip, String port, int ttl) { + ServiceNode node = new ServiceNode(); + node.setIp(ip); + node.setPort(port); + node.setTtl(ttl); + nodes.add(node); + } +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/FileManager.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/FileManager.java index 69870d0c..a66e458e 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/FileManager.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/FileManager.java @@ -13,24 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.filemanage; +import org.openo.commontosca.catalog.filemanage.entity.FileLink; + import java.util.ArrayList; -import org.openo.commontosca.catalog.filemanage.entity.FileLink; public interface FileManager { - /** - * @param srcPath - * @param dstPath/packageType/provider/packageName/version - * @return - */ - boolean upload(String srcPath, String dstPath); + + /** + * package upload api. + * @param srcPath source path + * @param dstPath/packageType/provider/packageName/version + * @return boolean + */ + boolean upload(String srcPath, String dstPath); - boolean download(String srcPath, String dstPath); + boolean download(String srcPath, String dstPath); - boolean delete(String srcPath); + boolean delete(String srcPath); - ArrayList queryWorkFlow(String path); + ArrayList queryWorkFlow(String path); } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/FileManagerFactory.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/FileManagerFactory.java index b8e4ba90..fe0b6377 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/FileManagerFactory.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/FileManagerFactory.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.filemanage; import org.openo.commontosca.catalog.filemanage.http.HttpFileManagerImpl; @@ -20,29 +21,34 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FileManagerFactory { - private static final Logger logger = LoggerFactory.getLogger(FileManagerFactory.class); + private static final Logger logger = LoggerFactory.getLogger(FileManagerFactory.class); - private static FileManager getHttpFileManager() { - return new HttpFileManagerImpl(); - } + private static FileManager getHttpFileManager() { + return new HttpFileManagerImpl(); + } - public static FileManager createFileManager() { - switch (getType()) { - case http: - return getHttpFileManager(); - case ftp: - return null; - default: - return getHttpFileManager(); - } + /** + * create file manager. + * @return FileManager + */ + public static FileManager createFileManager() { + switch (getType()) { + case http: + return getHttpFileManager(); + case ftp: + return null; + default: + return getHttpFileManager(); } + } - private static FileManagerType getType() { - String type = System.getenv("useFtp"); - logger.info("read environment varibale uesFtp:" + type); - if (type != null && "true".equals(type)) - return FileManagerType.ftp; - else - return FileManagerType.http; + private static FileManagerType getType() { + String type = System.getenv("useFtp"); + logger.info("read environment varibale uesFtp:" + type); + if (type != null && "true".equals(type)) { + return FileManagerType.ftp; + } else { + return FileManagerType.http; } + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/FileManagerType.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/FileManagerType.java index eab0ee3f..3bd15fde 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/FileManagerType.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/FileManagerType.java @@ -13,11 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.filemanage; public enum FileManagerType { - ftp, http; - public static FileManagerType getType(String type) { - return valueOf(type); - } + ftp, http; + public static FileManagerType getType(String type) { + return valueOf(type); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/entity/FileLink.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/entity/FileLink.java index 9149d529..f979c8fe 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/entity/FileLink.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/entity/FileLink.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.filemanage.entity; import lombok.AllArgsConstructor; @@ -23,7 +24,7 @@ import lombok.NoArgsConstructor; @NoArgsConstructor @AllArgsConstructor public class FileLink { - private String fileName; - private String downloadUri; + private String fileName; + private String downloadUri; } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/http/HttpFileManagerImpl.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/http/HttpFileManagerImpl.java index f0a68d59..acdc767a 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/http/HttpFileManagerImpl.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/http/HttpFileManagerImpl.java @@ -13,74 +13,77 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.filemanage.http; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; +package org.openo.commontosca.catalog.filemanage.http; import org.openo.commontosca.catalog.filemanage.FileManager; import org.openo.commontosca.catalog.filemanage.entity.FileLink; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; + + public class HttpFileManagerImpl implements FileManager { - private static final Logger LOGGER = LoggerFactory.getLogger(HttpFileManagerImpl.class); + private static final Logger LOGGER = LoggerFactory.getLogger(HttpFileManagerImpl.class); - @Override - public boolean upload(String srcPath, String dstPath) { - boolean flag = true; - LOGGER.info("start upload file.srcPath:" + srcPath + " dstPath" + dstPath); - File srcFile = new File(srcPath); - if (!srcFile.exists()) { - LOGGER.error("src file not exist!"); - return false; - } - // File dstFile = new File(ToolUtil.getHttpServerPath() + dstPath); - // LOGGER.info("dstFile AbsolutePath:" + dstFile.getAbsolutePath()); - String targetDir = Class.class.getClass().getResource("/").getPath() + ToolUtil.getHttpServerPath() + dstPath; - try { - ToolUtil.copyDirectory(srcPath, targetDir, true); - } catch (IOException e) { - flag = false; - LOGGER.error("copy file failed.errorMsg:" + e.getMessage()); - } - LOGGER.info("upload file success!"); - return flag; + @Override + public boolean upload(String srcPath, String dstPath) { + boolean flag = true; + LOGGER.info("start upload file.srcPath:" + srcPath + " dstPath" + dstPath); + File srcFile = new File(srcPath); + if (!srcFile.exists()) { + LOGGER.error("src file not exist!"); + return false; } - - @Override - public boolean download(String srcPath, String dstPath) { - // TODO Auto-generated method stub - return false; + // File dstFile = new File(ToolUtil.getHttpServerPath() + dstPath); + // LOGGER.info("dstFile AbsolutePath:" + dstFile.getAbsolutePath()); + String targetDir = + Class.class.getClass().getResource("/").getPath() + ToolUtil.getHttpServerPath() + dstPath; + try { + ToolUtil.copyDirectory(srcPath, targetDir, true); + } catch (IOException e1) { + flag = false; + LOGGER.error("copy file failed.errorMsg:" + e1.getMessage()); } + LOGGER.info("upload file success!"); + return flag; + } - @Override - public boolean delete(String srcPath) { - boolean flag = true; - LOGGER.info("start delete file from http server.srcPath:" + srcPath); - flag = ToolUtil.deleteDir(new File(ToolUtil.getHttpServerPath() + srcPath)); - LOGGER.info("delete file from http server end.flag:" + flag); - return flag; - } + @Override + public boolean download(String srcPath, String dstPath) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean delete(String srcPath) { + boolean flag = true; + LOGGER.info("start delete file from http server.srcPath:" + srcPath); + flag = ToolUtil.deleteDir(new File(ToolUtil.getHttpServerPath() + srcPath)); + LOGGER.info("delete file from http server end.flag:" + flag); + return flag; + } - @Override - public ArrayList queryWorkFlow(String path) { - LOGGER.info("start query workFlow from http server.path:" + path); - File workFlowRoot = new File(ToolUtil.getHttpServerPath() + path); - ArrayList fileLinks = new ArrayList(); - File[] files = workFlowRoot.listFiles(); - if (files != null && files.length != 0) { - for (File file : files) { - if (file.isFile() && file.getName().endsWith(".zip")) { - FileLink fileLink = new FileLink(); - fileLink.setFileName(file.getName()); - fileLink.setDownloadUri(path + "/" + file.getName()); - } - } + @Override + public ArrayList queryWorkFlow(String path) { + LOGGER.info("start query workFlow from http server.path:" + path); + File workFlowRoot = new File(ToolUtil.getHttpServerPath() + path); + ArrayList fileLinks = new ArrayList(); + File[] files = workFlowRoot.listFiles(); + if (files != null && files.length != 0) { + for (File file : files) { + if (file.isFile() && file.getName().endsWith(".zip")) { + FileLink fileLink = new FileLink(); + fileLink.setFileName(file.getName()); + fileLink.setDownloadUri(path + "/" + file.getName()); } - LOGGER.info("start query workFlow from http server.size:" + fileLinks.size()); - return fileLinks; + } } + LOGGER.info("start query workFlow from http server.size:" + fileLinks.size()); + return fileLinks; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/http/ToolUtil.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/http/ToolUtil.java index c90e6dbe..97abd3ae 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/http/ToolUtil.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/http/ToolUtil.java @@ -13,8 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.filemanage.http; +import org.openo.commontosca.catalog.common.HttpServerPathConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -23,142 +28,167 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import org.openo.commontosca.catalog.common.HttpServerPathConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; public class ToolUtil { - private static final Logger LOGGER = LoggerFactory.getLogger(ToolUtil.class); - - public static boolean copyDirectory(String srcDirName, String destDirName, boolean overlay) - throws IOException { - File srcDir = new File(srcDirName); - if (!srcDir.exists()) { - return false; - } else if (!srcDir.isDirectory()) { - return false; - } + private static final Logger LOGGER = LoggerFactory.getLogger(ToolUtil.class); - if (!destDirName.endsWith(File.separator)) { - destDirName = destDirName + File.separator; - } - File destDir = new File(destDirName); - if (destDir.exists()) { - if (overlay) { - new File(destDirName).delete(); - } else { - return false; - } - } else { - if (!destDir.mkdirs()) { - return false; - } - } - boolean flag = true; - File[] files = srcDir.listFiles(); - for (int i = 0; i < files.length; i++) { - if (files[i].isFile()) { - flag = copyFile(files[i].getAbsolutePath(), destDirName + files[i].getName(), true); - if (!flag) - break; - } else if (files[i].isDirectory()) { - flag = - copyDirectory(files[i].getAbsolutePath(), destDirName + files[i].getName(), - overlay); - if (!flag) - break; - } + /** + * copy from directory. + * @param srcDirName source directory name + * @param destDirName destination directory name + * @param overlay overwrite or not + * @return boolean + * @throws IOException e + */ + public static boolean copyDirectory(String srcDirName, String destDirName, boolean overlay) + throws IOException { + File srcDir = new File(srcDirName); + if (!srcDir.exists()) { + return false; + } else if (!srcDir.isDirectory()) { + return false; + } + + if (!destDirName.endsWith(File.separator)) { + destDirName = destDirName + File.separator; + } + File destDir = new File(destDirName); + if (destDir.exists()) { + if (overlay) { + new File(destDirName).delete(); + } else { + return false; + } + } else { + if (!destDir.mkdirs()) { + return false; + } + } + boolean flag = true; + File[] files = srcDir.listFiles(); + for (int i = 0; i < files.length; i++) { + if (files[i].isFile()) { + flag = copyFile(files[i].getAbsolutePath(), destDirName + files[i].getName(), true); + if (!flag) { + break; } + } else if (files[i].isDirectory()) { + flag = copyDirectory(files[i].getAbsolutePath(), destDirName + files[i].getName(), overlay); if (!flag) { - String MESSAGE = "Copy catagory " + srcDirName + " to " + destDirName + " failed!"; - LOGGER.error(MESSAGE); - return false; - } else { - return true; + break; } + } } + if (!flag) { + String message = "Copy catagory " + srcDirName + " to " + destDirName + " failed!"; + LOGGER.error(message); + return false; + } else { + return true; + } + } - public static boolean copyFile(String srcFileName, String destFileName, boolean overlay) { - File srcFile = new File(srcFileName); - - if (!srcFile.exists()) { - String MESSAGE = "Source file :" + srcFileName + " not exist !"; - LOGGER.error(MESSAGE); - return false; - } else if (!srcFile.isFile()) { - return false; - } + /** + * copy file. + * @param srcFileName source file name + * @param destFileName target file name + * @param overlay overwrite or not + * @return boolean + */ + public static boolean copyFile(String srcFileName, String destFileName, boolean overlay) { + File srcFile = new File(srcFileName); - File destFile = new File(destFileName); - if (destFile.exists()) { - if (overlay) { - new File(destFileName).delete(); - } - } else { - if (!destFile.getParentFile().exists()) { - if (!destFile.getParentFile().mkdirs()) { - return false; - } - } - } + if (!srcFile.exists()) { + String message = "Source file :" + srcFileName + " not exist !"; + LOGGER.error(message); + return false; + } else if (!srcFile.isFile()) { + return false; + } - int byteread = 0; - InputStream in = null; - OutputStream out = null; - - try { - in = new FileInputStream(srcFile); - out = new FileOutputStream(destFile); - byte[] buffer = new byte[1024]; - - while ((byteread = in.read(buffer)) != -1) { - out.write(buffer, 0, byteread); - } - return true; - } catch (FileNotFoundException e) { - return false; - } catch (IOException e) { - return false; - } finally { - try { - if (out != null) - out.close(); - if (in != null) - in.close(); - } catch (IOException e) { - e.printStackTrace(); - } + File destFile = new File(destFileName); + if (destFile.exists()) { + if (overlay) { + new File(destFileName).delete(); + } + } else { + if (!destFile.getParentFile().exists()) { + if (!destFile.getParentFile().mkdirs()) { + return false; } + } } - public static boolean createDir(String destDirName) { - File dir = new File(destDirName); - if (dir.exists()) { - dir.delete(); + int byteread = 0; + InputStream in = null; + OutputStream out = null; + + try { + in = new FileInputStream(srcFile); + out = new FileOutputStream(destFile); + byte[] buffer = new byte[1024]; + + while ((byteread = in.read(buffer)) != -1) { + out.write(buffer, 0, byteread); + } + return true; + } catch (FileNotFoundException e1) { + return false; + } catch (IOException e1) { + return false; + } finally { + try { + if (out != null) { + out.close(); } - if (!destDirName.endsWith(File.separator)) - destDirName = destDirName + File.separator; - if (dir.mkdirs()) { - return true; - } else { - return false; + if (in != null) { + in.close(); } + } catch (IOException e1) { + e1.printStackTrace(); + } } + } - public static String getHttpServerPath() { - return HttpServerPathConfig.getHttpServerPath(); + /** + * create directory. + * @param destDirName target directory name + * @return boolean + */ + public static boolean createDir(String destDirName) { + File dir = new File(destDirName); + if (dir.exists()) { + dir.delete(); } + if (!destDirName.endsWith(File.separator)) { + destDirName = destDirName + File.separator; + } + if (dir.mkdirs()) { + return true; + } else { + return false; + } + } + + public static String getHttpServerPath() { + return HttpServerPathConfig.getHttpServerPath(); + } - public static boolean deleteDir(File dir) { - if (dir.isDirectory()) { - String[] children = dir.list(); - for (int i = 0; i < children.length; i++) { - boolean success = deleteDir(new File(dir, children[i])); - if (!success) { - return false; - } - } + /** + * delete directory. + * @param dir file to delete + * @return boolean + */ + public static boolean deleteDir(File dir) { + if (dir.isDirectory()) { + String[] children = dir.list(); + for (int i = 0; i < children.length; i++) { + boolean success = deleteDir(new File(dir, children[i])); + if (!success) { + return false; } - return dir.delete(); + } } + return dir.delete(); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/ftp/Ftp.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/ftp/Ftp.java index 74b30662..ed075ce2 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/ftp/Ftp.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/ftp/Ftp.java @@ -13,30 +13,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.ftp; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; - -/** - * @author 00164331 - * - */ @Data @NoArgsConstructor @AllArgsConstructor public class Ftp { - private String ipAddr; + private String ipAddr; - private Integer port; + private Integer port; - private String userName; + private String userName; - private String pwd; + private String pwd; - private String path; + private String path; } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/ftp/FtpUtil.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/ftp/FtpUtil.java index cec4d30f..6f74bbf9 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/ftp/FtpUtil.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/ftp/FtpUtil.java @@ -13,200 +13,196 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.ftp; +import org.apache.commons.net.ftp.FTPClient; +import org.apache.commons.net.ftp.FTPFile; +import org.apache.commons.net.ftp.FTPReply; +import org.apache.log4j.Logger; + import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; -import org.apache.commons.net.ftp.FTPClient; -import org.apache.commons.net.ftp.FTPFile; -import org.apache.commons.net.ftp.FTPReply; -import org.apache.log4j.Logger; - -/** - * @author 00164331 - * - */ public class FtpUtil { - private static Logger logger = Logger.getLogger(FtpUtil.class); + private static Logger logger = Logger.getLogger(FtpUtil.class); - private static FTPClient ftp; + private static FTPClient ftp; - /** - * 获取ftp连接 - * - * @param f - * @return - * @throws Exception - */ - public static boolean connectFtp(Ftp f) throws Exception { - ftp = new FTPClient(); - boolean flag = false; - int reply; - if (f.getPort() == null) { - ftp.connect(f.getIpAddr(), 21); - } else { - ftp.connect(f.getIpAddr(), f.getPort()); - } - ftp.login(f.getUserName(), f.getPwd()); - ftp.setFileType(FTPClient.BINARY_FILE_TYPE); - reply = ftp.getReplyCode(); - if (!FTPReply.isPositiveCompletion(reply)) { - ftp.disconnect(); - return flag; - } - ftp.changeWorkingDirectory(f.getPath()); - flag = true; - return flag; + /** + * get ftp connection. + * + * @param conftp Ftp + * @return boolean + * @throws Exception e + */ + public static boolean connectFtp(Ftp conftp) throws Exception { + ftp = new FTPClient(); + boolean flag = false; + if (conftp.getPort() == null) { + ftp.connect(conftp.getIpAddr(), 21); + } else { + ftp.connect(conftp.getIpAddr(), conftp.getPort()); + } + ftp.login(conftp.getUserName(), conftp.getPwd()); + ftp.setFileType(FTPClient.BINARY_FILE_TYPE); + int reply = ftp.getReplyCode(); + if (!FTPReply.isPositiveCompletion(reply)) { + ftp.disconnect(); + return flag; } + ftp.changeWorkingDirectory(conftp.getPath()); + flag = true; + return flag; + } - /** - * 关闭ftp连接 - */ - public static void closeFtp() { - if (ftp != null && ftp.isConnected()) { - try { - ftp.logout(); - ftp.disconnect(); - } catch (IOException e) { - e.printStackTrace(); - } - } + /** + * close ftp connection. + */ + public static void closeFtp() { + if (ftp != null && ftp.isConnected()) { + try { + ftp.logout(); + ftp.disconnect(); + } catch (IOException e1) { + e1.printStackTrace(); + } } + } - /** - * ftp上传文件 - * - * @param f - * @throws Exception - */ - public static void upload(File f) throws Exception { - if (f.isDirectory()) { - ftp.makeDirectory(f.getName()); - ftp.changeWorkingDirectory(f.getName()); - String[] files = f.list(); - for (String fstr : files) { - File file1 = new File(f.getPath() + "/" + fstr); - if (file1.isDirectory()) { - upload(file1); - ftp.changeToParentDirectory(); - } else { - File file2 = new File(f.getPath() + "/" + fstr); - FileInputStream input = new FileInputStream(file2); - ftp.storeFile(file2.getName(), input); - input.close(); - } - } + /** + * upload file by ftp. + * + * @param file file to upload + * @throws Exception e + */ + public static void upload(File file) throws Exception { + if (file.isDirectory()) { + ftp.makeDirectory(file.getName()); + ftp.changeWorkingDirectory(file.getName()); + String[] files = file.list(); + for (String fstr : files) { + File file1 = new File(file.getPath() + "/" + fstr); + if (file1.isDirectory()) { + upload(file1); + ftp.changeToParentDirectory(); } else { - File file2 = new File(f.getPath()); - FileInputStream input = new FileInputStream(file2); - ftp.storeFile(file2.getName(), input); - input.close(); + File file2 = new File(file.getPath() + "/" + fstr); + FileInputStream input = new FileInputStream(file2); + ftp.storeFile(file2.getName(), input); + input.close(); } + } + } else { + File file2 = new File(file.getPath()); + FileInputStream input = new FileInputStream(file2); + ftp.storeFile(file2.getName(), input); + input.close(); } + } - /** - * 下载链接配置 - * - * @param f - * @param localBaseDir 本地目录 - * @param remoteBaseDir 远程目录 - * @throws Exception - */ - public static void startDown(Ftp f, String localBaseDir, String remoteBaseDir) throws Exception { - if (FtpUtil.connectFtp(f)) { + /** + * download inline config. + * + * @param downftp ftp to download + * @param localBaseDir local directory + * @param remoteBaseDir remote directory + * @throws Exception e + */ + public static void startDown(Ftp downftp, String localBaseDir, String remoteBaseDir) + throws Exception { + if (FtpUtil.connectFtp(downftp)) { + try { + FTPFile[] files = null; + boolean changedir = ftp.changeWorkingDirectory(remoteBaseDir); + if (changedir) { + ftp.setControlEncoding("GBK"); + files = ftp.listFiles(); + for (int i = 0; i < files.length; i++) { try { - FTPFile[] files = null; - boolean changedir = ftp.changeWorkingDirectory(remoteBaseDir); - if (changedir) { - ftp.setControlEncoding("GBK"); - files = ftp.listFiles(); - for (int i = 0; i < files.length; i++) { - try { - downloadFile(files[i], localBaseDir, remoteBaseDir); - } catch (Exception e) { - logger.error(e); - logger.error("<" + files[i].getName() + ">下载失败"); - } - } - } - } catch (Exception e) { - logger.error(e); - logger.error("下载过程中出现异常"); + downloadFile(files[i], localBaseDir, remoteBaseDir); + } catch (Exception e1) { + logger.error(e1); + logger.error("<" + files[i].getName() + ">download failed"); } - } else { - logger.error("链接失败!"); + } } - + } catch (Exception e1) { + logger.error(e1); + logger.error("error occoured while download"); + } + } else { + logger.error("Connect failed !"); } + } - /** - * - * 下载FTP文件 当你需要下载FTP文件的时候,调用此方法 根据获取的文件名,本地地址,远程地址进行下载 - * - * @param ftpFile - * @param relativeLocalPath - * @param relativeRemotePath - */ - private static void downloadFile(FTPFile ftpFile, String relativeLocalPath, - String relativeRemotePath) { - if (ftpFile.isFile()) { - if (ftpFile.getName().indexOf("?") == -1) { - OutputStream outputStream = null; - try { - File locaFile = new File(relativeLocalPath + ftpFile.getName()); - // 判断文件是否存在,存在则返回 - if (locaFile.exists()) { - return; - } else { - outputStream = new FileOutputStream(relativeLocalPath + ftpFile.getName()); - ftp.retrieveFile(ftpFile.getName(), outputStream); - outputStream.flush(); - outputStream.close(); - } - } catch (Exception e) { - logger.error(e); - } finally { - try { - if (outputStream != null) { - outputStream.close(); - } - } catch (IOException e) { - logger.error("输出文件流异常"); - } - } - } - } else { - String newlocalRelatePath = relativeLocalPath + ftpFile.getName(); - String newRemote = new String(relativeRemotePath + ftpFile.getName().toString()); - File fl = new File(newlocalRelatePath); - if (!fl.exists()) { - fl.mkdirs(); - } - try { - newlocalRelatePath = newlocalRelatePath + '/'; - newRemote = newRemote + "/"; - String currentWorkDir = ftpFile.getName().toString(); - boolean changedir = ftp.changeWorkingDirectory(currentWorkDir); - if (changedir) { - FTPFile[] files = null; - files = ftp.listFiles(); - for (int i = 0; i < files.length; i++) { - downloadFile(files[i], newlocalRelatePath, newRemote); - } - } - if (changedir) { - ftp.changeToParentDirectory(); - } - } catch (Exception e) { - logger.error(e); + + /** + * download ftp file. + * + * @param ftpFile ftp file to download + * @param relativeLocalPath relative local path + * @param relativeRemotePath relative remote path + */ + private static void downloadFile(FTPFile ftpFile, String relativeLocalPath, + String relativeRemotePath) { + if (ftpFile.isFile()) { + if (ftpFile.getName().indexOf("?") == -1) { + OutputStream outputStream = null; + try { + File locaFile = new File(relativeLocalPath + ftpFile.getName()); + // 判断文件是否存在,存在则返回 + if (locaFile.exists()) { + return; + } else { + outputStream = new FileOutputStream(relativeLocalPath + ftpFile.getName()); + ftp.retrieveFile(ftpFile.getName(), outputStream); + outputStream.flush(); + outputStream.close(); + } + } catch (Exception e1) { + logger.error(e1); + } finally { + try { + if (outputStream != null) { + outputStream.close(); } + } catch (IOException e1) { + logger.error("输出文件流异常"); + } + } + } + } else { + String newlocalRelatePath = relativeLocalPath + ftpFile.getName(); + String newRemote = new String(relativeRemotePath + ftpFile.getName().toString()); + File fl = new File(newlocalRelatePath); + if (!fl.exists()) { + fl.mkdirs(); + } + try { + newlocalRelatePath = newlocalRelatePath + '/'; + newRemote = newRemote + "/"; + String currentWorkDir = ftpFile.getName().toString(); + boolean changedir = ftp.changeWorkingDirectory(currentWorkDir); + if (changedir) { + FTPFile[] files = null; + files = ftp.listFiles(); + for (int i = 0; i < files.length; i++) { + downloadFile(files[i], newlocalRelatePath, newRemote); + } + } + if (changedir) { + ftp.changeToParentDirectory(); } + } catch (Exception e1) { + logger.error(e1); + } } + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/health/ConsoleHealthCheck.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/health/ConsoleHealthCheck.java index b517bc8b..a39428a6 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/health/ConsoleHealthCheck.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/health/ConsoleHealthCheck.java @@ -13,23 +13,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.health; import com.codahale.metrics.health.HealthCheck; public class ConsoleHealthCheck extends HealthCheck { - private final String template; + private final String template; - public ConsoleHealthCheck(String template) { - this.template = template; - } + public ConsoleHealthCheck(String template) { + this.template = template; + } - @Override - protected Result check() throws Exception { - final String saying = String.format(template, "TEST"); - if (!saying.contains("TEST")) { - return Result.unhealthy("template doesn't include a name"); - } - return Result.healthy(); + @Override + protected Result check() throws Exception { + final String saying = String.format(template, "TEST"); + if (!saying.contains("TEST")) { + return Result.unhealthy("template doesn't include a name"); } + return Result.healthy(); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/common/EnumToscaNodeTypeDefinition.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/common/EnumToscaNodeTypeDefinition.java index 0627d743..6c519d93 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/common/EnumToscaNodeTypeDefinition.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/common/EnumToscaNodeTypeDefinition.java @@ -13,48 +13,54 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.common; public enum EnumToscaNodeTypeDefinition { - VNF{ - @Override - public String getName(){ - return "tosca.nodes.nfv.VNF"; - } - }, - VDU{ - @Override - public String getName(){ - return "tosca.nodes.nfv.VDU"; - } - }, - VNFC{ - @Override - public String getName(){ - return "tosca.nodes.nfv.VNFC"; - } - }, - VL{ - @Override - public String getName(){ - return "tosca.nodes.nfv.VL"; - } - }, - CP{ - @Override - public String getName(){ - return "tosca.nodes.nfv.CP"; - } - }; - - public abstract String getName(); - - public static boolean isToscaNodeTypeDef(String type){ - for(EnumToscaNodeTypeDefinition enumDef : EnumToscaNodeTypeDefinition.values()){ - if(type.indexOf(enumDef.getName()) != -1){ - return true; - } - } - return false; + VNF { + @Override + public String getName() { + return "tosca.nodes.nfv.VNF"; + } + }, + VDU { + @Override + public String getName() { + return "tosca.nodes.nfv.VDU"; + } + }, + VNFC { + @Override + public String getName() { + return "tosca.nodes.nfv.VNFC"; + } + }, + VL { + @Override + public String getName() { + return "tosca.nodes.nfv.VL"; + } + }, + CP { + @Override + public String getName() { + return "tosca.nodes.nfv.CP"; + } + }; + + public abstract String getName(); + + /** + * judge wether is tosca node type definition or not. + * @param type node type + * @return boolean + */ + public static boolean isToscaNodeTypeDef(String type) { + for (EnumToscaNodeTypeDefinition enumDef : EnumToscaNodeTypeDefinition.values()) { + if (type.indexOf(enumDef.getName()) != -1) { + return true; + } } + return false; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/common/EnumToscaRelationShipDefinition.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/common/EnumToscaRelationShipDefinition.java index 2aecf42c..41998183 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/common/EnumToscaRelationShipDefinition.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/common/EnumToscaRelationShipDefinition.java @@ -13,34 +13,35 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.common; public enum EnumToscaRelationShipDefinition { - VirtualBindsTo{ - @Override - public String getName(){ - return "tosca.relationships.nfv.VirtualBindsTo"; - } - }, - VirtualLinksTo{ - @Override - public String getName(){ - return "tosca.relationships.nfv.VirtualLinksTo"; - } - }, - DeployedOn{ - @Override - public String getName(){ - return "tosca.relationships.nfv.DeployedOn"; - } - }, - BelongTo{ - @Override - public String getName(){ - return "tosca.relationships.nfv.BelongTo"; - } - }; - - public abstract String getName(); - + VirtualBindsTo { + @Override + public String getName() { + return "tosca.relationships.nfv.VirtualBindsTo"; + } + }, + VirtualLinksTo { + @Override + public String getName() { + return "tosca.relationships.nfv.VirtualLinksTo"; + } + }, + DeployedOn { + @Override + public String getName() { + return "tosca.relationships.nfv.DeployedOn"; + } + }, + BelongTo { + @Override + public String getName() { + return "tosca.relationships.nfv.BelongTo"; + } + }; + + public abstract String getName(); + } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/common/TemplateDataHelper.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/common/TemplateDataHelper.java index 859ea522..6583f4b3 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/common/TemplateDataHelper.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/common/TemplateDataHelper.java @@ -13,8 +13,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.common; +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; + +import org.openo.commontosca.catalog.common.ToolUtil; +import org.openo.commontosca.catalog.db.entity.NodeTemplateData; +import org.openo.commontosca.catalog.db.entity.ServiceTemplateData; +import org.openo.commontosca.catalog.db.entity.ServiceTemplateMappingData; +import org.openo.commontosca.catalog.db.entity.TemplateData; +import org.openo.commontosca.catalog.model.entity.NodeTemplate; +import org.openo.commontosca.catalog.model.entity.Parameters; +import org.openo.commontosca.catalog.model.entity.RelationShip; +import org.openo.commontosca.catalog.model.entity.ServiceTemplate; +import org.openo.commontosca.catalog.model.entity.ServiceTemplateOperation; +import org.openo.commontosca.catalog.model.entity.SubstitutionMapping; + import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -23,224 +41,202 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; -import org.openo.commontosca.catalog.db.entity.ServiceTemplateMappingData; -import org.openo.commontosca.catalog.db.entity.TemplateData; -import org.openo.commontosca.catalog.model.entity.ServiceTemplate; -import org.openo.commontosca.catalog.model.entity.ServiceTemplateOperation; -import org.openo.commontosca.catalog.model.entity.SubstitutionMapping; -import org.openo.commontosca.catalog.common.ToolUtil; -import org.openo.commontosca.catalog.db.entity.NodeTemplateData; -import org.openo.commontosca.catalog.db.entity.ServiceTemplateData; -import org.openo.commontosca.catalog.model.entity.InputParameter; -import org.openo.commontosca.catalog.model.entity.NodeTemplate; -import org.openo.commontosca.catalog.model.entity.RelationShip; -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; -/** - * @author 10090474 - * - */ public class TemplateDataHelper { - /** - * @param st - * @param ntList - * @return - */ - public static TemplateData convert2TemplateData(ServiceTemplate st, - String rawData, List ntList) { - TemplateData td = new TemplateData(); - td.setServiceTemplate(convert2ServiceTemplateData(st, rawData)); - td.setNodeTemplates(convert2NodeTemplateDataList(ntList, - st.getServiceTemplateId())); - return td; - } - - /** - * @param st - * @return - */ - private static ServiceTemplateData convert2ServiceTemplateData( - ServiceTemplate st, String rawData) { - ServiceTemplateData std = new ServiceTemplateData(); - std.setServiceTemplateId(st.getServiceTemplateId()); - std.setTemplateName(st.getTemplateName()); - std.setVendor(st.getVendor()); - std.setVersion(st.getVersion()); - std.setCsarId(st.getCsarid()); - std.setType(st.getType()); - std.setDownloadUri(st.getDownloadUri()); - std.setInputs(ToolUtil.toJson(st.getInputs())); - std.setOperations(ToolUtil.toJson(st.getOperations())); - std.setRowData(rawData); - return std; - } - - /** - * @param ntList - * @param serviceTemplateId - * @return - */ - private static ArrayList convert2NodeTemplateDataList( - List ntList, String serviceTemplateId) { - ArrayList ntdList = new ArrayList<>(); - for (NodeTemplate nt : ntList) { - ntdList.add(convert2NodeTemplateData(nt, serviceTemplateId)); - - } - return ntdList; - } - - - /** - * @param nt - * @param serviceTemplateId - * @return - */ - private static NodeTemplateData convert2NodeTemplateData(NodeTemplate nt, - String serviceTemplateId) { - NodeTemplateData ntd = new NodeTemplateData(); - - ntd.setNodeTemplateId(nt.getId()); - ntd.setName(nt.getName()); - ntd.setType(nt.getType()); - ntd.setServiceTemplateId(serviceTemplateId); - ntd.setProperties(ToolUtil.toJson(nt.getProperties())); - ntd.setRelationShips(ToolUtil.toJson(nt.getRelationShips())); - - return ntd; - } - - - /** - * @param stdList - * @return - */ - public static ServiceTemplate[] convert2ServiceTemplates( - List stdList) { - List stList = new ArrayList<>(); - for (ServiceTemplateData std : stdList) { - stList.add(convert2ServiceTemplate(std)); - } + /** + * convert to template data. + * @param st ServiceTemplate + * @param ntList NodeTemplate list + * @return TemplateData + */ + public static TemplateData convert2TemplateData(ServiceTemplate st, String rawData, + List ntList) { + TemplateData td = new TemplateData(); + td.setServiceTemplate(convert2ServiceTemplateData(st, rawData)); + td.setNodeTemplates(convert2NodeTemplateDataList(ntList, st.getServiceTemplateId())); + return td; + } + + /** + * convert to service template data. + * @param st ServiceTemplate + * @return ServiceTemplateData + */ + private static ServiceTemplateData convert2ServiceTemplateData(ServiceTemplate st, + String rawData) { + ServiceTemplateData std = new ServiceTemplateData(); + std.setServiceTemplateId(st.getServiceTemplateId()); + std.setTemplateName(st.getTemplateName()); + std.setVendor(st.getVendor()); + std.setVersion(st.getVersion()); + std.setCsarId(st.getCsarid()); + std.setType(st.getType()); + std.setDownloadUri(st.getDownloadUri()); + Parameters parameters = new Parameters(st.getInputs(), st.getOutputs()); + std.setInputs(ToolUtil.toJson(parameters)); + std.setOperations(ToolUtil.toJson(st.getOperations())); + std.setRowData(rawData); + return std; + } + + /** + * convert to nodeTemplate data list. + * @param ntList NodeTemplate list + * @param serviceTemplateId service template id + * @return NodeTemplateData list + */ + private static ArrayList convert2NodeTemplateDataList(List ntList, + String serviceTemplateId) { + ArrayList ntdList = new ArrayList<>(); + for (NodeTemplate nt : ntList) { + ntdList.add(convert2NodeTemplateData(nt, serviceTemplateId)); - return stList.toArray(new ServiceTemplate[0]); } - - /** - * @param std - * @return - */ - public static ServiceTemplate convert2ServiceTemplate( - ServiceTemplateData std) { - InputParameter[] inputs = ToolUtil.fromJson(std.getInputs(), - InputParameter[].class); - ServiceTemplateOperation[] operations = ToolUtil.fromJson( - std.getOperations(), ServiceTemplateOperation[].class); - - return new ServiceTemplate(std.getServiceTemplateId(), - std.getTemplateName(), std.getVendor(), std.getVersion(), - std.getCsarId(), std.getType(), std.getDownloadUri(), inputs, - operations); - } - - /** - * - * @param ntdList - * @return - */ - public static NodeTemplate[] convert2NodeTemplates( - List ntdList) { - List ntList = new ArrayList<>(); - for (NodeTemplateData ntd : ntdList) { - ntList.add(convert2NodeTemplate(ntd)); - } - return ntList.toArray(new NodeTemplate[0]); - } - - /** - * @param ntd - * @return - */ - public static NodeTemplate convert2NodeTemplate(NodeTemplateData ntd) { - List relationShips = convert2RelationShipList(ntd - .getRelationShips()); - return new NodeTemplate(ntd.getNodeTemplateId(), ntd.getName(), - ntd.getType(), convert2Property(ntd.getProperties()), - relationShips); - } - - /** - * @param sRelationShips - * @return - */ - private static List convert2RelationShipList( - String sRelationShips) { - RelationShip[] relationShips = ToolUtil.fromJson(sRelationShips, - RelationShip[].class); - return Arrays.asList(relationShips); + return ntdList; + } + + + /** + * convert to nodeTemplate data. + * @param nt NodeTemplate + * @param serviceTemplateId service template id + * @return NodeTemplateData + */ + private static NodeTemplateData convert2NodeTemplateData(NodeTemplate nt, + String serviceTemplateId) { + NodeTemplateData ntd = new NodeTemplateData(); + + ntd.setNodeTemplateId(nt.getId()); + ntd.setName(nt.getName()); + ntd.setType(nt.getType()); + ntd.setServiceTemplateId(serviceTemplateId); + ntd.setProperties(ToolUtil.toJson(nt.getProperties())); + ntd.setRelationShips(ToolUtil.toJson(nt.getRelationShips())); + + return ntd; + } + + + /** + * convert to service templates. + * @param stdList ServiceTemplateData list + * @return ServiceTemplate list + */ + public static ServiceTemplate[] convert2ServiceTemplates(List stdList) { + List stList = new ArrayList<>(); + for (ServiceTemplateData std : stdList) { + stList.add(convert2ServiceTemplate(std)); } - /** - * @param properties - * @return - */ - private static Map convert2Property(String properties) { - JsonObject jsonObject = new Gson().fromJson(properties, - JsonObject.class); - return parseMapValue(jsonObject); + return stList.toArray(new ServiceTemplate[0]); + } + + /** + * covert to service template. + * @param std ServiceTemplateData + * @return ServiceTemplate + */ + public static ServiceTemplate convert2ServiceTemplate(ServiceTemplateData std) { + Parameters parameters = ToolUtil.fromJson(std.getInputs(), Parameters.class); + ServiceTemplateOperation[] operations = + ToolUtil.fromJson(std.getOperations(), ServiceTemplateOperation[].class); + + return new ServiceTemplate(std.getServiceTemplateId(), std.getTemplateName(), std.getVendor(), + std.getVersion(), std.getCsarId(), std.getType(), std.getDownloadUri(), + parameters.getInputs(), parameters.getOutputs(), operations); + } + + /** + * covert to nodeTemplates. + * @param ntdList NodeTemplateData list + * @return NodeTemplate list + */ + public static NodeTemplate[] convert2NodeTemplates(List ntdList) { + List ntList = new ArrayList<>(); + for (NodeTemplateData ntd : ntdList) { + ntList.add(convert2NodeTemplate(ntd)); } - - private static Map parseMapValue(JsonObject jsonObject) { - Map map = new HashMap<>(); - - Iterator> iterator = jsonObject.entrySet() - .iterator(); - while (iterator.hasNext()) { - Entry next = iterator.next(); - if (next.getValue() instanceof JsonPrimitive) { - map.put(next.getKey(), next.getValue().getAsString()); - continue; - } - - if (next.getValue() instanceof JsonObject) { - map.put(next.getKey(), - parseMapValue((JsonObject) next.getValue())); - continue; - } - } - return map; - } - - - /** - * @param stm - * @return - */ - public static ServiceTemplateMappingData convert2TemplateMappingData( - SubstitutionMapping stm) { - ServiceTemplateMappingData stmd = new ServiceTemplateMappingData(); - - stmd.setMappingId(ToolUtil.generateId()); - stmd.setServiceTemplateId(stm.getServiceTemplateId()); - stmd.setNodeType(stm.getNode_type()); - stmd.setRequirements(ToolUtil.toJson(stm.getRequirements())); - stmd.setCapabilities(ToolUtil.toJson(stm.getCapabilities())); - - return stmd; - } - - /** - * @param stmData - * @return - */ - public static SubstitutionMapping convert2SubstitutionMapping( - ServiceTemplateMappingData stmData) { - return new SubstitutionMapping(stmData.getServiceTemplateId(), - stmData.getNodeType()); + return ntList.toArray(new NodeTemplate[0]); + } + + /** + * covert to nodeTemplate. + * @param ntd NodeTemplateData + * @return NodeTemplate + */ + public static NodeTemplate convert2NodeTemplate(NodeTemplateData ntd) { + List relationShips = convert2RelationShipList(ntd.getRelationShips()); + return new NodeTemplate(ntd.getNodeTemplateId(), ntd.getName(), ntd.getType(), + convert2Property(ntd.getProperties()), relationShips); + } + + /** + * covert to relationship list. + * @param sRelationShips relationships + * @return RelationShip list + */ + private static List convert2RelationShipList(String srelationShips) { + RelationShip[] relationShips = ToolUtil.fromJson(srelationShips, RelationShip[].class); + return Arrays.asList(relationShips); + } + + /** + * convert to propterty. + * @param properties properties to covert + * @return map + */ + private static Map convert2Property(String properties) { + JsonObject jsonObject = new Gson().fromJson(properties, JsonObject.class); + return parseMapValue(jsonObject); + } + + private static Map parseMapValue(JsonObject jsonObject) { + Map map = new HashMap<>(); + + Iterator> iterator = jsonObject.entrySet().iterator(); + while (iterator.hasNext()) { + Entry next = iterator.next(); + if (next.getValue() instanceof JsonPrimitive) { + map.put(next.getKey(), next.getValue().getAsString()); + continue; + } + + if (next.getValue() instanceof JsonObject) { + map.put(next.getKey(), parseMapValue((JsonObject) next.getValue())); + continue; + } } + return map; + } + + + /** + * covert to template mapping data. + * @param stm data to convert + * @return ServiceTemplateMappingData + */ + public static ServiceTemplateMappingData convert2TemplateMappingData(SubstitutionMapping stm) { + ServiceTemplateMappingData stmd = new ServiceTemplateMappingData(); + + stmd.setMappingId(ToolUtil.generateId()); + stmd.setServiceTemplateId(stm.getServiceTemplateId()); + stmd.setNodeType(stm.getNodeType()); + stmd.setRequirements(ToolUtil.toJson(stm.getRequirements())); + stmd.setCapabilities(ToolUtil.toJson(stm.getCapabilities())); + + return stmd; + } + + /** + * convert to substitution mapping. + * @param stmData data to covert + * @return SubstitutionMapping + */ + public static SubstitutionMapping convert2SubstitutionMapping( + ServiceTemplateMappingData stmData) { + return new SubstitutionMapping(stmData.getServiceTemplateId(), stmData.getNodeType()); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/EnumDataType.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/EnumDataType.java index 3bafbbef..091a9554 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/EnumDataType.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/EnumDataType.java @@ -13,30 +13,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.entity; import lombok.AllArgsConstructor; -/** - * @author 10090474 - * - */ @AllArgsConstructor public enum EnumDataType { - STRING("String"), INTEGER("Integer"), FLOAT("Float"), BOOLEAN("Boolean"); - - private String value; + STRING("String"), INTEGER("Integer"), FLOAT("Float"), BOOLEAN("Boolean"); + + private String value; - public String getValue() { - return value; - } + public String getValue() { + return value; + } - public void setValue(String value) { - this.value = value; - } + public void setValue(String value) { + this.value = value; + } - @Override - public String toString() { - return value; - } + @Override + public String toString() { + return value; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/InputParameter.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/InputParameter.java index 1f8a1b49..5dc9a246 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/InputParameter.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/InputParameter.java @@ -13,24 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -/** - * @author 10090474 - * - */ @Data @NoArgsConstructor @AllArgsConstructor public class InputParameter { - private String name; - private EnumDataType type = EnumDataType.STRING; - private String description; - private String defaultValue; - private boolean required; + private String name; + private EnumDataType type = EnumDataType.STRING; + private String description; + private String defaultValue; + private boolean required; } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/KeyValuePair.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/KeyValuePair.java index b582b876..c6f86ded 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/KeyValuePair.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/KeyValuePair.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.entity; import lombok.AllArgsConstructor; @@ -23,6 +24,6 @@ import lombok.NoArgsConstructor; @NoArgsConstructor @AllArgsConstructor public class KeyValuePair { - private String key; - private String value; + private String key; + private String value; } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/NfvTemplate.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/NfvTemplate.java index ab606621..bbbfa5c0 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/NfvTemplate.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/NfvTemplate.java @@ -13,21 +13,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.model.entity; -import java.util.List; +package org.openo.commontosca.catalog.model.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; +import java.util.List; + + @Data @NoArgsConstructor @AllArgsConstructor public class NfvTemplate { - private List vduNodes; - private List networkNodes; - private List vnfcNodes; - private List vnfNodes; + private List vduNodes; + private List networkNodes; + private List vnfcNodes; + private List vnfNodes; } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/NodeTemplate.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/NodeTemplate.java index f2a8ca34..569a9379 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/NodeTemplate.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/NodeTemplate.java @@ -13,22 +13,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.model.entity; -import java.util.List; -import java.util.Map; +package org.openo.commontosca.catalog.model.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; +import java.util.List; +import java.util.Map; + @Data @NoArgsConstructor @AllArgsConstructor public class NodeTemplate { - private String id; - private String name; - private String type; - private Map properties; - private List relationShips; + private String id; + private String name; + private String type; + private Map properties; + private List relationShips; } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/OutputParameter.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/OutputParameter.java new file mode 100644 index 00000000..af586f8f --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/OutputParameter.java @@ -0,0 +1,34 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.model.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class OutputParameter { + + private String name; + + private String description; + + private Object value; + +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/Parameters.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/Parameters.java new file mode 100644 index 00000000..80a56bec --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/Parameters.java @@ -0,0 +1,32 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.model.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Parameters { + + private InputParameter[] inputs; + + private OutputParameter[] outputs; + +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/QueryRawDataCondition.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/QueryRawDataCondition.java index 6eff7437..7c514f26 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/QueryRawDataCondition.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/QueryRawDataCondition.java @@ -13,21 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -/** - * @author 10090474 - * - */ @Data @NoArgsConstructor @AllArgsConstructor public class QueryRawDataCondition { - private String csarId; - private KeyValuePair[] inputParameters; + private String csarId; + private KeyValuePair[] inputParameters; } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/RelationShip.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/RelationShip.java index a65e74d4..04dfad8d 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/RelationShip.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/RelationShip.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.entity; import lombok.AllArgsConstructor; @@ -22,10 +23,16 @@ import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor -public class RelationShip { - private String sourceNodeName; - private String targetNodeName; - private String sourceNodeId; - private String targetNodeId; - private String type; +public class RelationShip { + + private String sourceNodeName; + + private String targetNodeName; + + private String sourceNodeId; + + private String targetNodeId; + + private String type; + } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/ServiceTemplate.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/ServiceTemplate.java index 703103b3..c6030e3e 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/ServiceTemplate.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/ServiceTemplate.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.entity; import lombok.AllArgsConstructor; @@ -23,13 +24,25 @@ import lombok.NoArgsConstructor; @NoArgsConstructor @AllArgsConstructor public class ServiceTemplate { - private String serviceTemplateId; - private String templateName; - private String vendor; - private String version; - private String csarid; - private String type; - private String downloadUri; - private InputParameter[] inputs; - private ServiceTemplateOperation[] operations; + + private String serviceTemplateId; + + private String templateName; + + private String vendor; + + private String version; + + private String csarid; + + private String type; + + private String downloadUri; + + private InputParameter[] inputs; + + private OutputParameter[] outputs; + + private ServiceTemplateOperation[] operations; + } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/ServiceTemplateOperation.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/ServiceTemplateOperation.java index dab206c2..3de66c73 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/ServiceTemplateOperation.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/ServiceTemplateOperation.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.entity; import lombok.AllArgsConstructor; @@ -23,8 +24,15 @@ import lombok.NoArgsConstructor; @NoArgsConstructor @AllArgsConstructor public class ServiceTemplateOperation { - private String name; - private String description; - private String processId; - private InputParameter[] inputs; + + private String name; + + private String description; + + private String packageName; + + private String processId; + + private InputParameter[] inputs; + } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/ServiceTemplateRawData.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/ServiceTemplateRawData.java index 351f74e4..92db3e7f 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/ServiceTemplateRawData.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/ServiceTemplateRawData.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.entity; import lombok.AllArgsConstructor; @@ -23,5 +24,7 @@ import lombok.NoArgsConstructor; @NoArgsConstructor @AllArgsConstructor public class ServiceTemplateRawData { - private String rawData; + + private String rawData; + } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/SubstitutionMapping.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/SubstitutionMapping.java index 56223381..034e736f 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/SubstitutionMapping.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/SubstitutionMapping.java @@ -13,54 +13,54 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.model.entity; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +package org.openo.commontosca.catalog.model.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -/** - * @author 10090474 - * - */ +import java.util.HashMap; +import java.util.Map; + @Data @NoArgsConstructor @AllArgsConstructor public class SubstitutionMapping { - private String serviceTemplateId; - private String node_type; - private List> requirements = new ArrayList<>(); - private Map capabilities = new HashMap(); + private String serviceTemplateId; + private String nodeType; + private Map requirements = new HashMap(); + private Map capabilities = new HashMap(); - /** - * @param key - * @param value - * @return - */ - public boolean putRequirement(String key, String[] value) { - Map requirement = new HashMap<>(); - requirement.put(key, value); - return this.requirements.add(requirement); - } + /** + * put requirement. + * @param key key + * @param value value + * @return string list + */ + public String[] putRequirement(String key, String[] value) { + return this.requirements.put(key, value); + } - /** - * @param key - * @param value - * @return - */ - public String[] putCapability(String key, String[] value) { - return this.capabilities.put(key, value); - } + /** + * put capability. + * @param key key + * @param value value + * @return string list + */ + public String[] putCapability(String key, String[] value) { + return this.capabilities.put(key, value); + } - public SubstitutionMapping(String serviceTemplateId, String node_type) { - super(); - this.serviceTemplateId = serviceTemplateId; - this.node_type = node_type; - } + /** + * substitution mapping. + * @param serviceTemplateId service template id + * @param nodeType node type + */ + public SubstitutionMapping(String serviceTemplateId, String nodeType) { + super(); + this.serviceTemplateId = serviceTemplateId; + this.nodeType = nodeType; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerSelfServiceProvider.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerSelfServiceProvider.java index e6a6423c..66d14834 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerSelfServiceProvider.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerSelfServiceProvider.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.externalservice.container; import java.io.IOException; @@ -28,39 +29,39 @@ import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; -import org.openo.commontosca.catalog.model.externalservice.entity.containerEntity.ContainerSelfService; +import org.openo.commontosca.catalog.model.externalservice.entity.container.ContainerSelfService; + /** - * The opentosca container self service returns data to the entity + * The opentosca container self service returns data to the entity. + * * @author 10189609 - * + * */ -public class ContainerSelfServiceProvider implements - MessageBodyReader { +public class ContainerSelfServiceProvider implements MessageBodyReader { + + @Override + public boolean isReadable(Class type, Type genericType, Annotation[] annotations, + MediaType mediaType) { + return ContainerSelfService.class.isAssignableFrom(type); + } + + @Override + public ContainerSelfService readFrom(Class type, Type genericType, + Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, + InputStream entityStream) throws IOException, WebApplicationException { + ContainerSelfService object = null; - @Override - public boolean isReadable(Class type, Type genericType, - Annotation[] annotations, MediaType mediaType) { - return ContainerSelfService.class.isAssignableFrom(type); - } + try { + JAXBContext jaxbContext = JAXBContext.newInstance(ContainerSelfService.class); + Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); + object = (ContainerSelfService) unmarshaller.unmarshal(entityStream); + } catch (JAXBException e1) { + e1.printStackTrace(); + } - @Override - public ContainerSelfService readFrom(Class type, - Type genericType, Annotation[] annotations, MediaType mediaType, - MultivaluedMap httpHeaders, InputStream entityStream) - throws IOException, WebApplicationException { - ContainerSelfService object = null; - - try { - JAXBContext jaxbContext = JAXBContext.newInstance(ContainerSelfService.class); - Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); - object = (ContainerSelfService) unmarshaller.unmarshal(entityStream); - } catch (JAXBException e) { - e.printStackTrace(); - } - - return object; - } + return object; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerServiceConsumer.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerServiceConsumer.java index d6f70d0c..4d26c06a 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerServiceConsumer.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerServiceConsumer.java @@ -13,17 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.externalservice.container; -import java.io.InputStream; -import java.util.List; +import com.google.gson.JsonObject; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; +import com.eclipsesource.jaxrs.consumer.ConsumerFactory; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.media.multipart.BodyPart; @@ -32,201 +27,203 @@ import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.FormDataMultiPart; import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.openo.commontosca.catalog.common.Config; -import org.openo.commontosca.catalog.model.externalservice.entity.containerEntity.ContainerSelfServiceOption; import org.openo.commontosca.catalog.common.ToolUtil; -import org.openo.commontosca.catalog.model.externalservice.entity.containerEntity.ContainerSelfService; -import org.openo.commontosca.catalog.model.externalservice.entity.containerEntity.ContainerServiceNodeTemplateList; -import org.openo.commontosca.catalog.model.externalservice.entity.containerEntity.ContainerServiceTemplateList; +import org.openo.commontosca.catalog.model.externalservice.entity.container.ContainerSelfService; +import org.openo.commontosca.catalog.model.externalservice.entity.container.ContainerSelfServiceOption; +import org.openo.commontosca.catalog.model.externalservice.entity.container.ContainerServiceNodeTemplateList; +import org.openo.commontosca.catalog.model.externalservice.entity.container.ContainerServiceTemplateList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.eclipsesource.jaxrs.consumer.ConsumerFactory; -import com.google.gson.JsonObject; +import java.io.InputStream; +import java.util.List; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + + /** - * By rest requesting access container services + * By rest requesting access container services. + * * @author 10189609 - * + * */ public class ContainerServiceConsumer { - private static final Logger LOG = LoggerFactory.getLogger(ContainerServiceConsumer.class); - /** - * get service template by template id from container service. - * @param templateid id - * @return template list entity - */ - public static ContainerServiceTemplateList getServiceTemplates( - final String templateid) { - ClientConfig config = new ClientConfig( - new ContainerServiceTemplateProvider()); - IContainerTemplateRest containerservicetemplateproxy = ConsumerFactory - .createConsumer(getBaseURL(), config, - IContainerTemplateRest.class); - return containerservicetemplateproxy - .getToscaServiceTemplate(templateid); - } + private static final Logger LOG = LoggerFactory.getLogger(ContainerServiceConsumer.class); + + /** + * get service template by template id from container service. + * + * @param templateid id + * @return template list entity + */ + public static ContainerServiceTemplateList getServiceTemplates(final String templateid) { + ClientConfig config = new ClientConfig(new ContainerServiceTemplateProvider()); + IContainerTemplateRest containerservicetemplateproxy = + ConsumerFactory.createConsumer(getBaseUrl(), config, IContainerTemplateRest.class); + return containerservicetemplateproxy.getToscaServiceTemplate(templateid); + } - /** - * get operation input param xml from container service - * @param csarId - * @param operationId - * @return xml - */ - public static String getOperationInputParamXml(final String csarId, - final String operationId) { - String inputparamsSoapXml = null; - ClientConfig config = new ClientConfig() - .register(new ContainerSelfServiceProvider()); - IContainerSelfServiceRest containerserviceoperationproxy = ConsumerFactory - .createConsumer(getPackageURL(), config, - IContainerSelfServiceRest.class); - String csarid = ToolUtil.formatCsar(csarId); - ContainerSelfService containerselfservice = containerserviceoperationproxy - .getContainerSelfService(csarid); - if (containerselfservice != null) { - for (int i = 0; i < containerselfservice.getOptionList().size(); i++) { - ContainerSelfServiceOption serviceOption = containerselfservice - .getOptionList().get(i); - if (serviceOption != null - && operationId.equals(serviceOption.getId())) { - inputparamsSoapXml = containerserviceoperationproxy - .getContainerSelfServiceOptionInputMessage( - csarid, - serviceOption.getPlanInputMessageUrl()); - break; - } - } + /** + * get operation input param xml from container service. + * + * @param csarId package Id + * @param operationId operation id + * @return xml + */ + public static String getOperationInputParamXml(final String csarId, final String operationId) { + String inputparamsSoapXml = null; + ClientConfig config = new ClientConfig().register(new ContainerSelfServiceProvider()); + IContainerSelfServiceRest containerserviceoperationproxy = + ConsumerFactory.createConsumer(getPackageUrl(), config, IContainerSelfServiceRest.class); + String csarid = ToolUtil.formatCsar(csarId); + ContainerSelfService containerselfservice = + containerserviceoperationproxy.getContainerSelfService(csarid); + if (containerselfservice != null) { + for (int i = 0; i < containerselfservice.getOptionList().size(); i++) { + ContainerSelfServiceOption serviceOption = containerselfservice.getOptionList().get(i); + if (serviceOption != null && operationId.equals(serviceOption.getId())) { + inputparamsSoapXml = + containerserviceoperationproxy.getContainerSelfServiceOptionInputMessage(csarid, + serviceOption.getPlanInputMessageUrl()); + break; } - return inputparamsSoapXml; - } - - /** - * get operations by csar id. - * @param csarId - * @return xml - */ - public static String getOperations(final String csarId) { - ClientConfig config = new ClientConfig() - .register(new ContainerSelfServiceProvider()); - IContainerSelfServiceRest containerselfserviceproxy = ConsumerFactory - .createConsumer(getPackageURL(), config, - IContainerSelfServiceRest.class); - return containerselfserviceproxy.getContainerSelfServiceXML(ToolUtil.formatCsar(csarId)); - } - - public static List getOperationList(final String csarId) { - ClientConfig config = new ClientConfig() - .register(new ContainerSelfServiceProvider()); - IContainerSelfServiceRest containerserviceoperationproxy = ConsumerFactory - .createConsumer(getPackageURL(), config, - IContainerSelfServiceRest.class); - String csarid = ToolUtil.formatCsar(csarId); - ContainerSelfService containerselfservice = containerserviceoperationproxy - .getContainerSelfService(csarid); - return containerselfservice.getOptionList(); + } } + return inputparamsSoapXml; + } - /** - * upload csar package to opentosca containerapi service. - * @param uploadedInputStream stream - * @param fileDetail - * @return response - */ - public static Response uploadServicePackage( - InputStream uploadedInputStream, - FormDataContentDisposition fileDetail) { - final FormDataMultiPart formData = new FormDataMultiPart(); - final BodyPart bodyPart = new FormDataBodyPart(fileDetail, - uploadedInputStream, MediaType.APPLICATION_OCTET_STREAM_TYPE); - formData.bodyPart(bodyPart); - formData.setContentDisposition(fileDetail); - formData.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE); - final Client client = ClientBuilder.newBuilder() - .register(MultiPartFeature.class).build(); - final WebTarget target = client.target(getPackageURL()).path( - "/containerapi/CSARs"); - final Response response = target.request().post( - Entity.entity(formData, formData.getMediaType())); - return response; - } + /** + * get operations by csar id. + * + * @param csarId package id + * @return xml + */ + public static String getOperations(final String csarId) { + ClientConfig config = new ClientConfig().register(new ContainerSelfServiceProvider()); + IContainerSelfServiceRest containerselfserviceproxy = + ConsumerFactory.createConsumer(getPackageUrl(), config, IContainerSelfServiceRest.class); + return containerselfserviceproxy.getContainerSelfServiceXml(ToolUtil.formatCsar(csarId)); + } - /** - * upload csar package by file location. - * @param fileLocation - * @param fileDetail - * @return response - */ - public static Response uploadServicePackageByLocation(String fileLocation) { - ClientConfig config = new ClientConfig(); - IContainerExtPackageRest containerservicepackageproxy = ConsumerFactory - .createConsumer(getBaseURL(), config, - IContainerExtPackageRest.class); - String result = containerservicepackageproxy - .uploadPackageByToscaService(fileLocation); - JsonObject json = new JsonObject(); - json.addProperty("result", result); - return Response.ok(json.toString()).build(); - } + /** + * get operation list. + * @param csarId package id + * @return container operation list + */ + public static List getOperationList(final String csarId) { + ClientConfig config = new ClientConfig().register(new ContainerSelfServiceProvider()); + IContainerSelfServiceRest containerserviceoperationproxy = + ConsumerFactory.createConsumer(getPackageUrl(), config, IContainerSelfServiceRest.class); + String csarid = ToolUtil.formatCsar(csarId); + ContainerSelfService containerselfservice = + containerserviceoperationproxy.getContainerSelfService(csarid); + return containerselfservice.getOptionList(); + } - /** - * delete a csar package by csar name. - * @param csarName - * @return - */ - public static String delServicePackage(final String csarName) { - ClientConfig config = new ClientConfig(); - IContainerExtPackageRest containerservicepackageproxy = ConsumerFactory - .createConsumer(getBaseURL(), config, - IContainerExtPackageRest.class); - LOG.info("url:" + getBaseURL() + " csarName:" + csarName); - return containerservicepackageproxy.deletePackageById(csarName); - } - - /** - * get node template list. - * @param templateId - * @return - */ - public static ContainerServiceNodeTemplateList getNodeTemplates( - final String templateId) { - ClientConfig config = new ClientConfig(new ContainerServiceNodeTemplateProvider()); - IContainerTemplateRest containertemplateproxy = ConsumerFactory - .createConsumer(getBaseURL(), config, IContainerTemplateRest.class); - return containertemplateproxy.getToscaServiceNodeTemplates(templateId); - } + /** + * upload csar package to opentosca containerapi service. + * + * @param uploadedInputStream stream + * @param fileDetail file detail + * @return response + */ + public static Response uploadServicePackage(InputStream uploadedInputStream, + FormDataContentDisposition fileDetail) { + final FormDataMultiPart formData = new FormDataMultiPart(); + final BodyPart bodyPart = + new FormDataBodyPart(fileDetail, uploadedInputStream, + MediaType.APPLICATION_OCTET_STREAM_TYPE); + formData.bodyPart(bodyPart); + formData.setContentDisposition(fileDetail); + formData.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE); + final Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build(); + final WebTarget target = client.target(getPackageUrl()).path("/containerapi/CSARs"); + final Response response = + target.request().post(Entity.entity(formData, formData.getMediaType())); + return response; + } - /** - * get policy infomation by service template id from vnfd - * @param serviceTemplateID - * @return - */ - public static String getPolicys(String serviceTemplateID) { - ClientConfig config = new ClientConfig(new StringProvider()); - IContainerPortabilityRest containerPolicyproxy = ConsumerFactory - .createConsumer(getBaseURL(), config, - IContainerPortabilityRest.class); - return containerPolicyproxy.getToscaPolicys(serviceTemplateID); - } - - /** - * http://127.0.0.1:1337/containerapi/extension - * - * @return - */ - private static String getBaseURL() { - StringBuffer buffer = new StringBuffer(); - buffer.append(Config.getConfigration().getOpentoscaServerAddr() + "/containerapi/extension"); - return buffer.toString(); - } + /** + * upload csar package by file location. + * + * @param fileLocation file location + * @return response + */ + public static Response uploadServicePackageByLocation(String fileLocation) { + ClientConfig config = new ClientConfig(); + IContainerExtPackageRest containerservicepackageproxy = + ConsumerFactory.createConsumer(getBaseUrl(), config, IContainerExtPackageRest.class); + String result = containerservicepackageproxy.uploadPackageByToscaService(fileLocation); + JsonObject json = new JsonObject(); + json.addProperty("result", result); + return Response.ok(json.toString()).build(); + } - /** - * http://127.0.0.1:1337 - * - * @return - */ - private static String getPackageURL() { - StringBuffer buffer = new StringBuffer(); - buffer.append(Config.getConfigration().getOpentoscaServerAddr()); - return buffer.toString(); - } + /** + * delete a csar package by csar name. + * + * @param csarName package name + * @return package id which deleted + */ + public static String delServicePackage(final String csarName) { + ClientConfig config = new ClientConfig(); + IContainerExtPackageRest containerservicepackageproxy = + ConsumerFactory.createConsumer(getBaseUrl(), config, IContainerExtPackageRest.class); + LOG.info("url:" + getBaseUrl() + " csarName:" + csarName); + return containerservicepackageproxy.deletePackageById(csarName); + } + + /** + * get node template list. + * + * @param templateId template id + * @return container service nodeTemplate list + */ + public static ContainerServiceNodeTemplateList getNodeTemplates(final String templateId) { + ClientConfig config = new ClientConfig(new ContainerServiceNodeTemplateProvider()); + IContainerTemplateRest containertemplateproxy = + ConsumerFactory.createConsumer(getBaseUrl(), config, IContainerTemplateRest.class); + return containertemplateproxy.getToscaServiceNodeTemplates(templateId); + } + + /** + * get policy infomation by service template id from vnfd. + * + * @param serviceTemplateId service template id + * @return tosca policys + */ + public static String getPolicys(String serviceTemplateId) { + ClientConfig config = new ClientConfig(new StringProvider()); + IContainerPortabilityRest containerPolicyproxy = + ConsumerFactory.createConsumer(getBaseUrl(), config, IContainerPortabilityRest.class); + return containerPolicyproxy.getToscaPolicys(serviceTemplateId); + } + + /** + * http://127.0.0.1:1337/containerapi/extension. + * + * @return base url + */ + private static String getBaseUrl() { + StringBuffer buffer = new StringBuffer(); + buffer.append(Config.getConfigration().getOpentoscaServerAddr() + "/containerapi/extension"); + return buffer.toString(); + } + + /** + * http://127.0.0.1:1337 + * + * @return package url + */ + private static String getPackageUrl() { + StringBuffer buffer = new StringBuffer(); + buffer.append(Config.getConfigration().getOpentoscaServerAddr()); + return buffer.toString(); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerServiceNodeTemplateProvider.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerServiceNodeTemplateProvider.java index daf57c28..45597118 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerServiceNodeTemplateProvider.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerServiceNodeTemplateProvider.java @@ -13,8 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.externalservice.container; +import org.openo.commontosca.catalog.model.externalservice.entity.container.ContainerServiceNodeTemplateList; +import org.xml.sax.InputSource; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.XMLReaderFactory; + import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; @@ -29,48 +35,43 @@ import javax.xml.bind.Unmarshaller; import javax.xml.transform.Source; import javax.xml.transform.sax.SAXSource; -import org.openo.commontosca.catalog.model.externalservice.entity.containerEntity.ContainerServiceNodeTemplateList; -import org.xml.sax.InputSource; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - /** - * The opentosca container service returns data to the node template entity + * The opentosca container service returns data to the node template entity. + * * @author 10189609 - * + * */ -public class ContainerServiceNodeTemplateProvider implements - MessageBodyReader { +public class ContainerServiceNodeTemplateProvider implements + MessageBodyReader { + + @Override + public boolean isReadable(Class type, Type genericType, Annotation[] annotations, + MediaType mediaType) { + return ContainerServiceNodeTemplateList.class.isAssignableFrom(type); + } + + @Override + public ContainerServiceNodeTemplateList readFrom(Class type, + Type genericType, Annotation[] annotations, MediaType mediaType, + MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, + WebApplicationException { + ContainerServiceNodeTemplateList nodetemplatelist = null; + + try { + JAXBContext jaxbContext = JAXBContext.newInstance(ContainerServiceNodeTemplateList.class); + Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); + // ignore namespace + NamespaceFilter inFilter = new NamespaceFilter(null, false); + XMLReader reader = XMLReaderFactory.createXMLReader(); + inFilter.setParent(reader); + Source source = new SAXSource(inFilter, new InputSource(entityStream)); - @Override - public boolean isReadable(Class type, Type genericType, - Annotation[] annotations, MediaType mediaType) { - return ContainerServiceNodeTemplateList.class.isAssignableFrom(type); - } + nodetemplatelist = (ContainerServiceNodeTemplateList) unmarshaller.unmarshal(source); + } catch (Exception e1) { + e1.printStackTrace(); + } - @Override - public ContainerServiceNodeTemplateList readFrom( - Class type, Type genericType, - Annotation[] annotations, MediaType mediaType, - MultivaluedMap httpHeaders, InputStream entityStream) - throws IOException, WebApplicationException { - ContainerServiceNodeTemplateList nodetemplatelist = null; - - try { - JAXBContext jaxbContext = JAXBContext.newInstance(ContainerServiceNodeTemplateList.class); - Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); - //ignore namespace - NamespaceFilter inFilter = new NamespaceFilter(null, false); - XMLReader reader = XMLReaderFactory.createXMLReader(); - inFilter.setParent(reader); - Source source = new SAXSource(inFilter, new InputSource(entityStream)); - - nodetemplatelist = (ContainerServiceNodeTemplateList) unmarshaller.unmarshal(source); - } catch (Exception e) { - e.printStackTrace(); - } - - return nodetemplatelist; - } + return nodetemplatelist; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerServicePackageProvider.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerServicePackageProvider.java index 5cb25499..a8f44d97 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerServicePackageProvider.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerServicePackageProvider.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.externalservice.container; import java.io.IOException; @@ -28,39 +29,39 @@ import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; -import org.openo.commontosca.catalog.model.externalservice.entity.containerEntity.ContainerServicePackageList; +import org.openo.commontosca.catalog.model.externalservice.entity.container.ContainerServicePackageList; /** - * The opentosca container service returns data to the package entity + * The opentosca container service returns data to the package entity. + * * @author 10189609 - * + * */ -public class ContainerServicePackageProvider implements MessageBodyReader { +public class ContainerServicePackageProvider implements + MessageBodyReader { + + @Override + public boolean isReadable(Class type, Type genericType, Annotation[] annotations, + MediaType mediaType) { + return ContainerServicePackageList.class.isAssignableFrom(type); + } + + @Override + public ContainerServicePackageList readFrom(Class type, + Type genericType, Annotation[] annotations, MediaType mediaType, + MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, + WebApplicationException { + ContainerServicePackageList packageList = null; - @Override - public boolean isReadable(Class type, Type genericType, - Annotation[] annotations, MediaType mediaType) { - return ContainerServicePackageList.class.isAssignableFrom(type); - } + try { + JAXBContext jaxbContext = JAXBContext.newInstance(ContainerServicePackageList.class); + Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); + packageList = (ContainerServicePackageList) unmarshaller.unmarshal(entityStream); + } catch (JAXBException e1) { + e1.printStackTrace(); + } - @Override - public ContainerServicePackageList readFrom( - Class type, Type genericType, - Annotation[] annotations, MediaType mediaType, - MultivaluedMap httpHeaders, InputStream entityStream) - throws IOException, WebApplicationException { - ContainerServicePackageList packageList = null; - - try - { - JAXBContext jaxbContext = JAXBContext.newInstance(ContainerServicePackageList.class); - Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); - packageList = (ContainerServicePackageList) unmarshaller.unmarshal(entityStream); - } catch (JAXBException e) { - e.printStackTrace(); - } - - return packageList; - } + return packageList; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerServiceTemplateProvider.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerServiceTemplateProvider.java index 38a66ddd..9a0d70c8 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerServiceTemplateProvider.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerServiceTemplateProvider.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.externalservice.container; import java.io.IOException; @@ -28,41 +29,40 @@ import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; -import org.openo.commontosca.catalog.model.externalservice.entity.containerEntity.ContainerServiceTemplateList; +import org.openo.commontosca.catalog.model.externalservice.entity.container.ContainerServiceTemplateList; + /** - * The opentosca container self service returns data to the service template entity + * The opentosca container self service returns data to the service template entity. + * * @author 10189609 - * + * */ public class ContainerServiceTemplateProvider implements - MessageBodyReader { + MessageBodyReader { + + @Override + public boolean isReadable(Class type, Type genericType, Annotation[] annotations, + MediaType mediaType) { + return ContainerServiceTemplateList.class.isAssignableFrom(type); + } + + @Override + public ContainerServiceTemplateList readFrom(Class type, + Type genericType, Annotation[] annotations, MediaType mediaType, + MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, + WebApplicationException { + ContainerServiceTemplateList object = null; - @Override - public boolean isReadable(Class type, Type genericType, - Annotation[] annotations, MediaType mediaType) { - return ContainerServiceTemplateList.class.isAssignableFrom( type ); - } + try { + JAXBContext jaxbContext = JAXBContext.newInstance(ContainerServiceTemplateList.class); + Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); + object = (ContainerServiceTemplateList) jaxbUnmarshaller.unmarshal(entityStream); + } catch (JAXBException e1) { + e1.printStackTrace(); + } - @Override - public ContainerServiceTemplateList readFrom(Class type, - Type genericType, Annotation[] annotations, MediaType mediaType, - MultivaluedMap httpHeaders, InputStream entityStream) - throws IOException, WebApplicationException { - ContainerServiceTemplateList object = null; - - try - { - JAXBContext jaxbContext = JAXBContext.newInstance(ContainerServiceTemplateList.class); - Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); - object = (ContainerServiceTemplateList)jaxbUnmarshaller.unmarshal(entityStream); - } - catch(JAXBException e) - { - e.printStackTrace(); - } - - return object; - } + return object; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/IContainerExtPackageRest.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/IContainerExtPackageRest.java index e471ea16..8be43c9f 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/IContainerExtPackageRest.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/IContainerExtPackageRest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.externalservice.container; import javax.ws.rs.Consumes; @@ -25,24 +26,27 @@ import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; -import org.openo.commontosca.catalog.model.externalservice.entity.containerEntity.ContainerServicePackageList; +import org.openo.commontosca.catalog.model.externalservice.entity.container.ContainerServicePackageList; + /** * The opentosca container interface for csar. + * * @author 10189609 - * + * */ @Path("/csars") public interface IContainerExtPackageRest { - @GET - @Produces(MediaType.APPLICATION_OCTET_STREAM) - public ContainerServicePackageList getToscaServicePackage(@QueryParam("csarName") String csarName); - - @POST - @Consumes(MediaType.TEXT_PLAIN) - public String uploadPackageByToscaService(@QueryParam("fileLocation") String fileLocation); - - @Path("/{csarId}") - @DELETE - public String deletePackageById(@PathParam("csarId") String csarId); + @GET + @Produces(MediaType.APPLICATION_OCTET_STREAM) + public ContainerServicePackageList getToscaServicePackage( + @QueryParam("csarName") String csarName); + + @POST + @Consumes(MediaType.TEXT_PLAIN) + public String uploadPackageByToscaService(@QueryParam("fileLocation") String fileLocation); + + @Path("/{csarId}") + @DELETE + public String deletePackageById(@PathParam("csarId") String csarId); } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/IContainerPortabilityRest.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/IContainerPortabilityRest.java index a12c0a1b..ee74afed 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/IContainerPortabilityRest.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/IContainerPortabilityRest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.externalservice.container; import javax.ws.rs.GET; @@ -21,13 +22,14 @@ import javax.ws.rs.PathParam; /** * The opentosca container interface for policy. + * * @author 10189609 - * + * */ @Path("/servicetemplates") -public interface IContainerPortabilityRest { - - @Path("/{templateid}/policys") - @GET - String getToscaPolicys(@PathParam("templateid") String serviceTemplateID); +public interface IContainerPortabilityRest { + + @Path("/{templateid}/policys") + @GET + String getToscaPolicys(@PathParam("templateid") String serviceTemplateId); } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/IContainerSelfServiceRest.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/IContainerSelfServiceRest.java index 29a59f99..36ffa8ab 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/IContainerSelfServiceRest.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/IContainerSelfServiceRest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.externalservice.container; import javax.ws.rs.GET; @@ -20,28 +21,30 @@ import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; -import org.openo.commontosca.catalog.model.externalservice.entity.containerEntity.ContainerSelfService; +import org.openo.commontosca.catalog.model.externalservice.entity.container.ContainerSelfService; + /** * The opentosca container interface for self service. + * * @author 10189609 - * + * */ @Path("/containerapi/CSARs/{csarid}/Content/SELFSERVICE-Metadata") -public interface IContainerSelfServiceRest { - @GET - @Path("/data.xml") - @Produces({ "application/octet-stream" }) - ContainerSelfService getContainerSelfService(@PathParam("csarid") String csarId); - - @GET - @Path("/data.xml") - @Produces({ "application/octet-stream" }) - String getContainerSelfServiceXML(@PathParam("csarid") String csarId); - - @GET - @Path("/{inputmessageurl}") - @Produces({ "application/octet-stream" }) - String getContainerSelfServiceOptionInputMessage(@PathParam("csarid") String csarId, - @PathParam("inputmessageurl") String inputmessageUrl); +public interface IContainerSelfServiceRest { + @GET + @Path("/data.xml") + @Produces({"application/octet-stream"}) + ContainerSelfService getContainerSelfService(@PathParam("csarid") String csarId); + + @GET + @Path("/data.xml") + @Produces({"application/octet-stream"}) + String getContainerSelfServiceXml(@PathParam("csarid") String csarId); + + @GET + @Path("/{inputmessageurl}") + @Produces({"application/octet-stream"}) + String getContainerSelfServiceOptionInputMessage(@PathParam("csarid") String csarId, + @PathParam("inputmessageurl") String inputmessageUrl); } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/IContainerTemplateRest.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/IContainerTemplateRest.java index 5573d996..b0cbec0b 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/IContainerTemplateRest.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/IContainerTemplateRest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.externalservice.container; import javax.ws.rs.GET; @@ -22,22 +23,25 @@ import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; -import org.openo.commontosca.catalog.model.externalservice.entity.containerEntity.ContainerServiceNodeTemplateList; -import org.openo.commontosca.catalog.model.externalservice.entity.containerEntity.ContainerServiceTemplateList; +import org.openo.commontosca.catalog.model.externalservice.entity.container.ContainerServiceNodeTemplateList; +import org.openo.commontosca.catalog.model.externalservice.entity.container.ContainerServiceTemplateList; + /** * The opentosca container interface for service template. + * * @author 10189609 - * + * */ @Path("/servicetemplates") public interface IContainerTemplateRest { - @GET - @Produces(MediaType.APPLICATION_OCTET_STREAM) - ContainerServiceTemplateList getToscaServiceTemplate(@QueryParam("templateid") String templateId); - - @Path("/{templateid}/nodetemplates") - @GET - @Produces(MediaType.APPLICATION_OCTET_STREAM) - ContainerServiceNodeTemplateList getToscaServiceNodeTemplates(@PathParam("templateid") String templateId); + @GET + @Produces(MediaType.APPLICATION_OCTET_STREAM) + ContainerServiceTemplateList getToscaServiceTemplate(@QueryParam("templateid") String templateId); + + @Path("/{templateid}/nodetemplates") + @GET + @Produces(MediaType.APPLICATION_OCTET_STREAM) + ContainerServiceNodeTemplateList getToscaServiceNodeTemplates( + @PathParam("templateid") String templateId); } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/NamespaceFilter.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/NamespaceFilter.java index 4f71996e..e5768b28 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/NamespaceFilter.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/NamespaceFilter.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.externalservice.container; import org.xml.sax.Attributes; @@ -20,77 +21,81 @@ import org.xml.sax.SAXException; import org.xml.sax.helpers.XMLFilterImpl; /** - * NamespaceFilter + * NamespaceFilter. + * * @author 10189609 - * + * */ public class NamespaceFilter extends XMLFilterImpl { - private String usedNamespaceUri; - private boolean addNamespace; + private String usedNamespaceUri; + private boolean addNamespace; - //State variable - private boolean addedNamespace = false; + // State variable + private boolean addedNamespace = false; - public NamespaceFilter(String namespaceUri, - boolean addNamespace) { - super(); + /** + * constructor. + * @param namespaceUri namspace uri + * @param addNamespace add namespace or not + */ + public NamespaceFilter(String namespaceUri, boolean addNamespace) { + super(); - if (addNamespace) - this.usedNamespaceUri = namespaceUri; - else - this.usedNamespaceUri = ""; - this.addNamespace = addNamespace; + if (addNamespace) { + this.usedNamespaceUri = namespaceUri; + } else { + this.usedNamespaceUri = ""; } + this.addNamespace = addNamespace; + } - @Override - public void startDocument() throws SAXException { - super.startDocument(); - if (addNamespace) { - startControlledPrefixMapping(); - } + @Override + public void startDocument() throws SAXException { + super.startDocument(); + if (addNamespace) { + startControlledPrefixMapping(); } + } - @Override - public void startElement(String arg0, String arg1, String arg2, - Attributes arg3) throws SAXException { - - super.startElement(this.usedNamespaceUri, arg1, arg2, arg3); - } + @Override + public void startElement(String arg0, String arg1, String arg2, Attributes arg3) + throws SAXException { - @Override - public void endElement(String arg0, String arg1, String arg2) - throws SAXException { + super.startElement(this.usedNamespaceUri, arg1, arg2, arg3); + } - super.endElement(this.usedNamespaceUri, arg1, arg2); - } + @Override + public void endElement(String arg0, String arg1, String arg2) throws SAXException { - @Override - public void startPrefixMapping(String prefix, String url) - throws SAXException { + super.endElement(this.usedNamespaceUri, arg1, arg2); + } + @Override + public void startPrefixMapping(String prefix, String url) throws SAXException { - if (addNamespace) { - this.startControlledPrefixMapping(); - } else { - //Remove the namespace, i.e. don´t call startPrefixMapping for parent! - } + if (addNamespace) { + this.startControlledPrefixMapping(); + } else { + // Remove the namespace, i.e. don´t call startPrefixMapping for parent! } - private void startControlledPrefixMapping() throws SAXException { + } + + private void startControlledPrefixMapping() throws SAXException { - if (this.addNamespace && !this.addedNamespace) { - //We should add namespace since it is set and has not yet been done. - super.startPrefixMapping("", this.usedNamespaceUri); + if (this.addNamespace && !this.addedNamespace) { + // We should add namespace since it is set and has not yet been done. + super.startPrefixMapping("", this.usedNamespaceUri); - //Make sure we dont do it twice - this.addedNamespace = true; - } + // Make sure we dont do it twice + this.addedNamespace = true; } + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/StringProvider.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/StringProvider.java index 6eb9b95c..191e4c7c 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/StringProvider.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/StringProvider.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.externalservice.container; import java.io.IOException; @@ -27,23 +28,23 @@ import javax.ws.rs.ext.MessageBodyReader; /** * The opentosca container service returns data directly. + * * @author 10189609 - * + * */ public class StringProvider implements MessageBodyReader { - @Override - public boolean isReadable(Class type, Type genericType, - Annotation[] annotations, MediaType mediaType) { - return false;//false representation not convert query results , returned directly - } + @Override + public boolean isReadable(Class type, Type genericType, Annotation[] annotations, + MediaType mediaType) { + return false;// false representation not convert query results , returned directly + } - @Override - public String readFrom(Class type, Type genericType, - Annotation[] annotations, MediaType mediaType, - MultivaluedMap httpHeaders, InputStream entityStream) - throws IOException, WebApplicationException { - return null; - } + @Override + public String readFrom(Class type, Type genericType, Annotation[] annotations, + MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) + throws IOException, WebApplicationException { + return null; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerSelfService.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerSelfService.java new file mode 100644 index 00000000..cf05b1b1 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerSelfService.java @@ -0,0 +1,88 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.container; + +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "Application", namespace = ContainerSelfService.NAMESPACE_OF_SELFSERVICE) +public class ContainerSelfService { + public static final String NAMESPACE_OF_SELFSERVICE = + "http://www.eclipse.org/winery/model/selfservice"; + + @XmlElement(namespace = NAMESPACE_OF_SELFSERVICE) + private String displayName; + + @XmlElement(namespace = NAMESPACE_OF_SELFSERVICE) + private String description; + + @XmlElement(namespace = NAMESPACE_OF_SELFSERVICE) + private String iconUrl; + + @XmlElement(namespace = NAMESPACE_OF_SELFSERVICE) + private String imageUrl; + + @XmlElementWrapper(name = "options", namespace = NAMESPACE_OF_SELFSERVICE) + @XmlElement(name = "option", namespace = NAMESPACE_OF_SELFSERVICE) + private List optionList; + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getIconUrl() { + return iconUrl; + } + + public void setIconUrl(String iconUrl) { + this.iconUrl = iconUrl; + } + + public String getImageUrl() { + return imageUrl; + } + + public void setImageUrl(String imageUrl) { + this.imageUrl = imageUrl; + } + + public List getOptionList() { + return optionList; + } + + public void setOptionList(List optionList) { + this.optionList = optionList; + } +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerSelfServiceOption.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerSelfServiceOption.java new file mode 100644 index 00000000..fe603a6c --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerSelfServiceOption.java @@ -0,0 +1,97 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.container; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlTransient; + +@XmlAccessorType(XmlAccessType.FIELD) +public class ContainerSelfServiceOption { + @XmlElement(namespace = ContainerSelfService.NAMESPACE_OF_SELFSERVICE) + private String description; + @XmlElement(namespace = ContainerSelfService.NAMESPACE_OF_SELFSERVICE) + private String iconUrl; + @XmlElement(namespace = ContainerSelfService.NAMESPACE_OF_SELFSERVICE) + private String planServiceName; + @XmlElement(namespace = ContainerSelfService.NAMESPACE_OF_SELFSERVICE) + private String planInputMessageUrl; + @XmlAttribute + private String id; + @XmlAttribute + private String name; + @XmlTransient + private String inputMessageSoap; + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getIconUrl() { + return iconUrl; + } + + public void setIconUrl(String iconUrl) { + this.iconUrl = iconUrl; + } + + public String getPlanServiceName() { + return planServiceName; + } + + public void setPlanServiceName(String planServiceName) { + this.planServiceName = planServiceName; + } + + public String getPlanInputMessageUrl() { + return planInputMessageUrl; + } + + public void setPlanInputMessageUrl(String planInputMessageUrl) { + this.planInputMessageUrl = planInputMessageUrl; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getInputMessageSoap() { + return inputMessageSoap; + } + + public void setInputMessageSoap(String inputMessageSoap) { + this.inputMessageSoap = inputMessageSoap; + } +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceCommonParam.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceCommonParam.java new file mode 100644 index 00000000..a9f9daaa --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceCommonParam.java @@ -0,0 +1,46 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.container; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; + +@XmlAccessorType(XmlAccessType.FIELD) +public class ContainerServiceCommonParam { + @XmlElement + private String key; + + @XmlElement + private String value; + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceNodeTemplate.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceNodeTemplate.java new file mode 100644 index 00000000..82bf5859 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceNodeTemplate.java @@ -0,0 +1,316 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.container; + +import org.openo.commontosca.catalog.common.ToolUtil; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +@XmlAccessorType(XmlAccessType.NONE) +public class ContainerServiceNodeTemplate { + + @XmlAttribute(name = "nodetemplateid") + private String id; + + @XmlAttribute(name = "nodetemplatename") + private String name; + + @XmlAttribute + private String type; + + @XmlElementWrapper(name = "properties") + @XmlElement(name = "property") + private List properties; + + @XmlElementWrapper(name = "relationshipInfos") + @XmlElement(name = "relationship") + private List relationShips; + + @XmlElement(name = "Capabilities") + private ContainerServiceNodeTemplate.Capablitiies capabilities; + + public ContainerServiceNodeTemplate.Capablitiies getCapabilities() { + return capabilities; + } + + public void setCapabilities(ContainerServiceNodeTemplate.Capablitiies capabilities) { + this.capabilities = capabilities; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public List getProperties() { + return properties; + } + + public void setProperties(List properties) { + this.properties = properties; + } + + public List getRelationShips() { + return relationShips; + } + + public void setRelationShips(List relationShips) { + this.relationShips = relationShips; + } + + @XmlRootElement + @XmlAccessorType(XmlAccessType.NONE) + public static class Capablitiies { + @XmlElement(name = "Capability") + private List capabilityList; + + public List getCapabilityList() { + return capabilityList; + } + + public void setCapabilityList(List capabilityList) { + this.capabilityList = capabilityList; + } + } + + @XmlRootElement + @XmlAccessorType(XmlAccessType.NONE) + public static class Capability { + @XmlAttribute(name = "id") + private String flavorName; + + @XmlElement(name = "Properties") + private ContainerServiceNodeTemplate.CapabilityProperties properties; + + public String getFlavorName() { + return flavorName; + } + + public void setFlavorName(String flavorName) { + this.flavorName = flavorName; + } + + public ContainerServiceNodeTemplate.CapabilityProperties getProperties() { + return properties; + } + + public void setProperties(ContainerServiceNodeTemplate.CapabilityProperties properties) { + this.properties = properties; + } + + } + + @XmlRootElement + @XmlAccessorType(XmlAccessType.NONE) + public static class CapabilityProperties { + @XmlElement(name = "Properties") + private ContainerServiceNodeTemplate.CapabilityProperty property; + + public ContainerServiceNodeTemplate.CapabilityProperty getProperty() { + return property; + } + + public void setProperty(ContainerServiceNodeTemplate.CapabilityProperty property) { + this.property = property; + } + } + + @XmlRootElement + @XmlAccessorType(XmlAccessType.FIELD) + public static class CapabilityProperty { + @XmlElement + private String vcpu; + + @XmlElement + private String vram; + + @XmlElement + private String rootDisk; + + @XmlElement + private String swapDisk; + + @XmlElement + private String tempDisk; + + public String getVcpu() { + return vcpu; + } + + public void setVcpu(String vcpu) { + this.vcpu = vcpu; + } + + public String getVram() { + return vram; + } + + public void setVram(String vram) { + this.vram = vram; + } + + public String getRootDisk() { + return rootDisk; + } + + public void setRootDisk(String rootDisk) { + this.rootDisk = rootDisk; + } + + public String getSwapDisk() { + return swapDisk; + } + + public void setSwapDisk(String swapDisk) { + this.swapDisk = swapDisk; + } + + public String getTempDisk() { + return tempDisk; + } + + public void setTempDisk(String tempDisk) { + this.tempDisk = tempDisk; + } + } + + public class NtFlavor { + private String flavorName; + + private String vcpu; + + private String vram; + + private String rootDisk; + + private String swapDisk; + + private String tempDisk; + + public String getFlavorName() { + return flavorName; + } + + public void setFlavorName(String flavorName) { + this.flavorName = flavorName; + } + + public String getVcpu() { + return vcpu; + } + + public void setVcpu(String vcpu) { + this.vcpu = vcpu; + } + + public String getVram() { + return vram; + } + + public void setVram(String vram) { + this.vram = vram; + } + + public String getRootDisk() { + return rootDisk; + } + + public void setRootDisk(String rootDisk) { + this.rootDisk = rootDisk; + } + + public String getSwapDisk() { + return swapDisk; + } + + public void setSwapDisk(String swapDisk) { + this.swapDisk = swapDisk; + } + + public String getTempDisk() { + return tempDisk; + } + + public void setTempDisk(String tempDisk) { + this.tempDisk = tempDisk; + } + + } + + /** + * get nt flavor list. + * @return nt flavor list + */ + public List getNtFlavorList() { + if (null == this.capabilities || ToolUtil.isEmptyCollection(capabilities.getCapabilityList())) { + return null; + } + + List ntFlavors = new ArrayList(); + List capabilityList = capabilities.getCapabilityList(); + for (Capability capabilty : capabilityList) { + NtFlavor ntFlavor = convertCap2Flavor(capabilty); + ntFlavors.add(ntFlavor); + } + + return ntFlavors; + } + + private NtFlavor convertCap2Flavor(Capability capabilty) { + NtFlavor ntFlavor = new NtFlavor(); + ntFlavor.setFlavorName(capabilty.getFlavorName()); + if (null != capabilty.getProperties() && null != capabilty.getProperties().getProperty()) { + CapabilityProperty property = capabilty.getProperties().getProperty(); + ntFlavor.setRootDisk(property.getRootDisk()); + ntFlavor.setSwapDisk(property.getSwapDisk()); + ntFlavor.setTempDisk(property.getTempDisk()); + ntFlavor.setVcpu(property.getVcpu()); + ntFlavor.setVram(property.getVram()); + } + + return ntFlavor; + } + +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceNodeTemplateList.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceNodeTemplateList.java new file mode 100644 index 00000000..5e41f88d --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceNodeTemplateList.java @@ -0,0 +1,41 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.container; + +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "nodetemplates") +public class ContainerServiceNodeTemplateList { + @XmlElement(name = "nodetemplate") + private List nodeTemplate; + + public List getNodeTemplate() { + return nodeTemplate; + } + + public void setNodeTemplate(List nodeTemplate) { + this.nodeTemplate = nodeTemplate; + } + + +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceOperationParameter.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceOperationParameter.java new file mode 100644 index 00000000..d1485c4a --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceOperationParameter.java @@ -0,0 +1,21 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.container; + +public class ContainerServiceOperationParameter { + +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServicePackage.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServicePackage.java new file mode 100644 index 00000000..a1196d29 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServicePackage.java @@ -0,0 +1,59 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.container; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement +public class ContainerServicePackage { + @XmlAttribute + private String name; + @XmlAttribute + private String createTime; + @XmlAttribute + private String size; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCreateTime() { + return createTime; + } + + public void setCreateTime(String createTime) { + this.createTime = createTime; + } + + public String getSize() { + return size; + } + + public void setSize(String size) { + this.size = size; + } + + +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServicePackageList.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServicePackageList.java new file mode 100644 index 00000000..240dc7a1 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServicePackageList.java @@ -0,0 +1,43 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.container; + +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "packages") +public class ContainerServicePackageList { + public static final String NAMESPACE_OF_SELFSERVICE = + "http://www.eclipse.org/winery/model/selfservice"; + + @XmlElement(name = "package") + private List packageList; + + public List getPackageList() { + return packageList; + } + + public void setPackageList(List packageList) { + this.packageList = packageList; + } + +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceRelationShip.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceRelationShip.java new file mode 100644 index 00000000..7d03ed73 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceRelationShip.java @@ -0,0 +1,80 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.container; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; + +@XmlAccessorType(XmlAccessType.FIELD) +public class ContainerServiceRelationShip { + @XmlElement + private String sourceNodeName; + + @XmlElement + private String targetNodeName; + + @XmlElement + private String sourceNodeId; + + @XmlElement + private String targetNodeId; + + @XmlElement + private String type; + + public String getSourceNodeId() { + return sourceNodeId; + } + + public void setSourceNodeId(String sourceNodeId) { + this.sourceNodeId = sourceNodeId; + } + + public String getTargetNodeId() { + return targetNodeId; + } + + public void setTargetNodeId(String targetNodeId) { + this.targetNodeId = targetNodeId; + } + + public String getSourceNodeName() { + return sourceNodeName; + } + + public void setSourceNodeName(String sourceNodeName) { + this.sourceNodeName = sourceNodeName; + } + + public String getTargetNodeName() { + return targetNodeName; + } + + public void setTargetNodeName(String targetNodeName) { + this.targetNodeName = targetNodeName; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceTemplate.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceTemplate.java new file mode 100644 index 00000000..cf351457 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceTemplate.java @@ -0,0 +1,330 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.container; + +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +@XmlAccessorType(XmlAccessType.NONE) +public class ContainerServiceTemplate { + @XmlAttribute + private String templateid; + + @XmlAttribute + private String templatename; + + @XmlElement(name = "BoundaryDefinitions") + private BoundaryDefinitions boundary; + + public String getTemplateid() { + return templateid; + } + + public void setTemplateid(String templateid) { + this.templateid = templateid; + } + + public String getTemplatename() { + return templatename; + } + + public void setTemplatename(String templatename) { + this.templatename = templatename; + } + + public BoundaryDefinitions getBoundary() { + return boundary; + } + + public void setBoundary(BoundaryDefinitions boundary) { + this.boundary = boundary; + } + + @XmlRootElement + @XmlAccessorType(XmlAccessType.NONE) + public static class BoundaryDefinitions { + @XmlElement(name = "Properties", namespace = "http://docs.oasis-open.org/tosca/ns/2011/12") + private BoundaryProperties properties; + + public BoundaryProperties getProperties() { + return properties; + } + + public void setProperties(BoundaryProperties properties) { + this.properties = properties; + } + + } + + @XmlRootElement + @XmlAccessorType(XmlAccessType.NONE) + public static class BoundaryProperties { + @XmlElement(name = "Properties") + private BoundaryProperty property; + + public BoundaryProperty getProperty() { + return property; + } + + public void setProperty(BoundaryProperty property) { + this.property = property; + } + } + + @XmlRootElement + @XmlAccessorType(XmlAccessType.NONE) + public static class BoundaryProperty { + public String getTemplateVersion() { + return templateVersion; + } + + public void setTemplateVersion(String templateVersion) { + this.templateVersion = templateVersion; + } + + public String getTemplateAuthor() { + return templateAuthor; + } + + public void setTemplateAuthor(String templateAuthor) { + this.templateAuthor = templateAuthor; + } + + public String getVendor() { + return vendor; + } + + public void setVendor(String vendor) { + this.vendor = vendor; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getNfvType() { + return nfvType; + } + + public void setNfvType(String nfvType) { + this.nfvType = nfvType; + } + + public String getMoc() { + return moc; + } + + public void setMoc(String moc) { + this.moc = moc; + } + + public String getFlavor() { + return flavor; + } + + public void setFlavor(String flavor) { + this.flavor = flavor; + } + + public List getStFlavor() { + return stFlavor; + } + + public void setStFlavor(List stFlavor) { + this.stFlavor = stFlavor; + } + + @XmlElement + private String templateVersion; + + @XmlElement + private String templateAuthor; + + @XmlElement + private String vendor; + + @XmlElement + private String version; + + @XmlElement + private String nfvType; + + @XmlElement + private String moc; + + @XmlElement + private String flavor; + + @XmlElementWrapper(name = "flavorList") + @XmlElement(name = "flavor") + private List stFlavor; + } + + @XmlRootElement + @XmlAccessorType(XmlAccessType.NONE) + public static class StFlavor { + @XmlAttribute + private String name; + + @XmlAttribute + private String desc; + + @XmlElementWrapper(name = "nodeList") + @XmlElement(name = "node") + private List stFlavorConstituent; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public List getStFlavorConstituent() { + return stFlavorConstituent; + } + + public void setStFlavorConstituent(List stFlavorConstituent) { + this.stFlavorConstituent = stFlavorConstituent; + } + } + + @XmlRootElement + @XmlAccessorType(XmlAccessType.NONE) + public static class StFlavorConstituent { + @XmlAttribute + private String numberOfInstances; + + @XmlAttribute + private String name; + + @XmlAttribute + private String refNodeFlavor; + + @XmlAttribute + private String affinity; + + @XmlAttribute + private String redundancyModel; + + @XmlAttribute + private String capability; + + public String getAffinity() { + return affinity; + } + + public void setAffinity(String affinity) { + this.affinity = affinity; + } + + public String getRedundancyModel() { + return redundancyModel; + } + + public void setRedundancyModel(String redundancyModel) { + this.redundancyModel = redundancyModel; + } + + public String getCapability() { + return capability; + } + + public void setCapability(String capability) { + this.capability = capability; + } + + public String getNumberOfInstances() { + return numberOfInstances; + } + + public void setNumberOfInstances(String numberOfInstances) { + this.numberOfInstances = numberOfInstances; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getRefNodeFlavor() { + return refNodeFlavor; + } + + public void setRefNodeFlavor(String refNodeFlavor) { + this.refNodeFlavor = refNodeFlavor; + } + } + + private Boolean propNullFlag; + + private boolean isPropNotNull() { + if (null == propNullFlag) { + propNullFlag = + null != this.getBoundary() && null != this.getBoundary().getProperties() + && null != this.getBoundary().getProperties().getProperty(); + } + return propNullFlag; + } + + public String getProductType() { + return isPropNotNull() ? this.getBoundary().getProperties().getProperty().getMoc() : null; + } + + public String getVendor() { + return isPropNotNull() ? this.getBoundary().getProperties().getProperty().getVendor() : null; + } + + public String getVersion() { + return isPropNotNull() ? this.getBoundary().getProperties().getProperty().getVersion() : null; + } + + public String getNfvtype() { + return isPropNotNull() ? this.getBoundary().getProperties().getProperty().getNfvType() : null; + } + + public String getFlavor() { + return isPropNotNull() ? this.getBoundary().getProperties().getProperty().getFlavor() : null; + } + + public List getStFlavorList() { + return isPropNotNull() ? this.getBoundary().getProperties().getProperty().getStFlavor() : null; + } +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceTemplateList.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceTemplateList.java new file mode 100644 index 00000000..e0ef95a9 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/container/ContainerServiceTemplateList.java @@ -0,0 +1,42 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.container; + +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "servicetemplates") +public class ContainerServiceTemplateList { + public static final String NAMESPACE_OF_SELFSERVICE = + "http://www.eclipse.org/winery/model/selfservice"; + + @XmlElement(name = "serviceTemplate") + private List serviceTemplateList; + + public List getServiceTemplateList() { + return serviceTemplateList; + } + + public void setServiceTemplateList(List optionList) { + this.serviceTemplateList = optionList; + } +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerSelfService.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerSelfService.java deleted file mode 100644 index c01dee6b..00000000 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerSelfService.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright 2016 [ZTE] and others. - * - * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.containerEntity; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name="Application",namespace=ContainerSelfService.NAMESPACE_OF_SELFSERVICE) -public class ContainerSelfService { - public static final String NAMESPACE_OF_SELFSERVICE="http://www.eclipse.org/winery/model/selfservice"; - - @XmlElement(namespace=NAMESPACE_OF_SELFSERVICE) - private String displayName; - - @XmlElement(namespace=NAMESPACE_OF_SELFSERVICE) - private String description; - - @XmlElement(namespace=NAMESPACE_OF_SELFSERVICE) - private String iconUrl; - - @XmlElement(namespace=NAMESPACE_OF_SELFSERVICE) - private String imageUrl; - - @XmlElementWrapper(name="options",namespace=NAMESPACE_OF_SELFSERVICE) - @XmlElement(name="option",namespace=NAMESPACE_OF_SELFSERVICE) - private List optionList; - - public String getDisplayName() { - return displayName; - } - - public void setDisplayName(String displayName) { - this.displayName = displayName; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getIconUrl() { - return iconUrl; - } - - public void setIconUrl(String iconUrl) { - this.iconUrl = iconUrl; - } - - public String getImageUrl() { - return imageUrl; - } - - public void setImageUrl(String imageUrl) { - this.imageUrl = imageUrl; - } - - public List getOptionList() { - return optionList; - } - - public void setOptionList(List optionList) { - this.optionList = optionList; - } -} - diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerSelfServiceOption.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerSelfServiceOption.java deleted file mode 100644 index ee5794df..00000000 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerSelfServiceOption.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Copyright 2016 [ZTE] and others. - * - * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.containerEntity; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlTransient; - -@XmlAccessorType(XmlAccessType.FIELD) -public class ContainerSelfServiceOption { - @XmlElement(namespace=ContainerSelfService.NAMESPACE_OF_SELFSERVICE) - private String description; - @XmlElement(namespace=ContainerSelfService.NAMESPACE_OF_SELFSERVICE) - private String iconUrl; - @XmlElement(namespace=ContainerSelfService.NAMESPACE_OF_SELFSERVICE) - private String planServiceName; - @XmlElement(namespace=ContainerSelfService.NAMESPACE_OF_SELFSERVICE) - private String planInputMessageUrl; - @XmlAttribute - private String id; - @XmlAttribute - private String name; - @XmlTransient - private String inputMessageSoap; - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; - } - public String getIconUrl() { - return iconUrl; - } - public void setIconUrl(String iconUrl) { - this.iconUrl = iconUrl; - } - public String getPlanServiceName() { - return planServiceName; - } - public void setPlanServiceName(String planServiceName) { - this.planServiceName = planServiceName; - } - public String getPlanInputMessageUrl() { - return planInputMessageUrl; - } - public void setPlanInputMessageUrl(String planInputMessageUrl) { - this.planInputMessageUrl = planInputMessageUrl; - } - public String getId() { - return id; - } - public void setId(String id) { - this.id = id; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getInputMessageSoap() { - return inputMessageSoap; - } - public void setInputMessageSoap(String inputMessageSoap) { - this.inputMessageSoap = inputMessageSoap; - } -} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceCommonParam.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceCommonParam.java deleted file mode 100644 index 3be5de90..00000000 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceCommonParam.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright 2016 [ZTE] and others. - * - * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.containerEntity; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; - -@XmlAccessorType(XmlAccessType.FIELD) -public class ContainerServiceCommonParam { - @XmlElement - private String key; - - @XmlElement - private String value; - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } -} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceNodeTemplate.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceNodeTemplate.java deleted file mode 100644 index de4a6cd0..00000000 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceNodeTemplate.java +++ /dev/null @@ -1,320 +0,0 @@ -/** - * Copyright 2016 [ZTE] and others. - * - * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.containerEntity; - -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; - -import org.openo.commontosca.catalog.common.ToolUtil; - - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -public class ContainerServiceNodeTemplate { - - @XmlAttribute(name = "nodetemplateid") - private String id; - - @XmlAttribute(name = "nodetemplatename") - private String name; - - @XmlAttribute - private String type; - - @XmlElementWrapper(name = "properties") - @XmlElement(name = "property") - private List properties; - - @XmlElementWrapper(name = "relationshipInfos") - @XmlElement(name = "relationship") - private List relationShips; - - @XmlElement(name = "Capabilities") - private ContainerServiceNodeTemplate.Capablitiies capabilities; - - public ContainerServiceNodeTemplate.Capablitiies getCapabilities() { - return capabilities; - } - - public void setCapabilities( - ContainerServiceNodeTemplate.Capablitiies capabilities) { - this.capabilities = capabilities; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public List getProperties() { - return properties; - } - - public void setProperties(List properties) { - this.properties = properties; - } - - public List getRelationShips() { - return relationShips; - } - - public void setRelationShips( - List relationShips) { - this.relationShips = relationShips; - } - - @XmlRootElement - @XmlAccessorType(XmlAccessType.NONE) - public static class Capablitiies { - @XmlElement(name = "Capability") - private List capabilityList; - - public List getCapabilityList() { - return capabilityList; - } - - public void setCapabilityList( - List capabilityList) { - this.capabilityList = capabilityList; - } - } - - @XmlRootElement - @XmlAccessorType(XmlAccessType.NONE) - public static class Capability { - @XmlAttribute(name = "id") - private String flavorName; - - @XmlElement(name = "Properties") - private ContainerServiceNodeTemplate.CapabilityProperties properties; - - public String getFlavorName() { - return flavorName; - } - - public void setFlavorName(String flavorName) { - this.flavorName = flavorName; - } - - public ContainerServiceNodeTemplate.CapabilityProperties getProperties() { - return properties; - } - - public void setProperties( - ContainerServiceNodeTemplate.CapabilityProperties properties) { - this.properties = properties; - } - - } - - @XmlRootElement - @XmlAccessorType(XmlAccessType.NONE) - public static class CapabilityProperties { - @XmlElement(name = "Properties") - private ContainerServiceNodeTemplate.CapabilityProperty property; - - public ContainerServiceNodeTemplate.CapabilityProperty getProperty() { - return property; - } - - public void setProperty( - ContainerServiceNodeTemplate.CapabilityProperty property) { - this.property = property; - } - } - - @XmlRootElement - @XmlAccessorType(XmlAccessType.FIELD) - public static class CapabilityProperty { - @XmlElement - private String vCPU; - - @XmlElement - private String vRAM; - - @XmlElement - private String rootDisk; - - @XmlElement - private String swapDisk; - - @XmlElement - private String tempDisk; - - public String getvCPU() { - return vCPU; - } - - public void setvCPU(String vCPU) { - this.vCPU = vCPU; - } - - public String getvRAM() { - return vRAM; - } - - public void setvRAM(String vRAM) { - this.vRAM = vRAM; - } - - public String getRootDisk() { - return rootDisk; - } - - public void setRootDisk(String rootDisk) { - this.rootDisk = rootDisk; - } - - public String getSwapDisk() { - return swapDisk; - } - - public void setSwapDisk(String swapDisk) { - this.swapDisk = swapDisk; - } - - public String getTempDisk() { - return tempDisk; - } - - public void setTempDisk(String tempDisk) { - this.tempDisk = tempDisk; - } - } - - public class NTFlavor { - private String flavorName; - - private String vCPU; - - private String vRAM; - - private String rootDisk; - - private String swapDisk; - - private String tempDisk; - - public String getFlavorName() { - return flavorName; - } - - public void setFlavorName(String flavorName) { - this.flavorName = flavorName; - } - - public String getvCPU() { - return vCPU; - } - - public void setvCPU(String vCPU) { - this.vCPU = vCPU; - } - - public String getvRAM() { - return vRAM; - } - - public void setvRAM(String vRAM) { - this.vRAM = vRAM; - } - - public String getRootDisk() { - return rootDisk; - } - - public void setRootDisk(String rootDisk) { - this.rootDisk = rootDisk; - } - - public String getSwapDisk() { - return swapDisk; - } - - public void setSwapDisk(String swapDisk) { - this.swapDisk = swapDisk; - } - - public String getTempDisk() { - return tempDisk; - } - - public void setTempDisk(String tempDisk) { - this.tempDisk = tempDisk; - } - - } - - public List getNTFlavorList() { - if (null == this.capabilities - || ToolUtil.isEmptyCollection(capabilities.getCapabilityList())) { - return null; - } - - List ntFlavors = new ArrayList(); - List capabilityList = capabilities.getCapabilityList(); - for (Capability capabilty : capabilityList) { - NTFlavor ntFlavor = convertCap2Flavor(capabilty); - ntFlavors.add(ntFlavor); - } - - return ntFlavors; - } - - private NTFlavor convertCap2Flavor(Capability capabilty) { - NTFlavor ntFlavor = new NTFlavor(); - ntFlavor.setFlavorName(capabilty.getFlavorName()); - if (null != capabilty.getProperties() - && null != capabilty.getProperties().getProperty()) { - CapabilityProperty property = capabilty.getProperties() - .getProperty(); - ntFlavor.setRootDisk(property.getRootDisk()); - ntFlavor.setSwapDisk(property.getSwapDisk()); - ntFlavor.setTempDisk(property.getTempDisk()); - ntFlavor.setvCPU(property.getvCPU()); - ntFlavor.setvRAM(property.getvRAM()); - } - - return ntFlavor; - } - -} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceNodeTemplateList.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceNodeTemplateList.java deleted file mode 100644 index 096da0e6..00000000 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceNodeTemplateList.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright 2016 [ZTE] and others. - * - * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.containerEntity; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name="nodetemplates") -public class ContainerServiceNodeTemplateList { - @XmlElement(name="nodetemplate") - private List nodeTemplate; - - public List getNodeTemplate() { - return nodeTemplate; - } - - public void setNodeTemplate(List nodeTemplate) { - this.nodeTemplate = nodeTemplate; - } - - -} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceOperationParameter.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceOperationParameter.java deleted file mode 100644 index 215b3ed5..00000000 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceOperationParameter.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Copyright 2016 [ZTE] and others. - * - * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.containerEntity; - -/** - * @author 10189609 - * - */ -public class ContainerServiceOperationParameter { - -} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServicePackage.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServicePackage.java deleted file mode 100644 index c91b6e1e..00000000 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServicePackage.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright 2016 [ZTE] and others. - * - * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.containerEntity; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement -public class ContainerServicePackage { - @XmlAttribute - private String name; - @XmlAttribute - private String createTime; - @XmlAttribute - private String size; - - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getCreateTime() { - return createTime; - } - public void setCreateTime(String createTime) { - this.createTime = createTime; - } - public String getSize() { - return size; - } - public void setSize(String size) { - this.size = size; - } - - -} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServicePackageList.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServicePackageList.java deleted file mode 100644 index c3b7dd73..00000000 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServicePackageList.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright 2016 [ZTE] and others. - * - * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.containerEntity; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name="packages") -public class ContainerServicePackageList { - public static final String NAMESPACE_OF_SELFSERVICE="http://www.eclipse.org/winery/model/selfservice"; - - @XmlElement(name="package") - private List packageList; - - public List getPackageList() { - return packageList; - } - - public void setPackageList(List packageList) { - this.packageList = packageList; - } - -} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceRelationShip.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceRelationShip.java deleted file mode 100644 index 08b238fc..00000000 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceRelationShip.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Copyright 2016 [ZTE] and others. - * - * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.containerEntity; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; - -@XmlAccessorType(XmlAccessType.FIELD) -public class ContainerServiceRelationShip { - @XmlElement - private String sourceNodeName; - - @XmlElement - private String targetNodeName; - - @XmlElement - private String sourceNodeId; - - @XmlElement - private String targetNodeId; - - @XmlElement - private String type; - - public String getSourceNodeId() { - return sourceNodeId; - } - - public void setSourceNodeId(String sourceNodeId) { - this.sourceNodeId = sourceNodeId; - } - - public String getTargetNodeId() { - return targetNodeId; - } - - public void setTargetNodeId(String targetNodeId) { - this.targetNodeId = targetNodeId; - } - - public String getSourceNodeName() { - return sourceNodeName; - } - - public void setSourceNodeName(String sourceNodeName) { - this.sourceNodeName = sourceNodeName; - } - - public String getTargetNodeName() { - return targetNodeName; - } - - public void setTargetNodeName(String targetNodeName) { - this.targetNodeName = targetNodeName; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - -} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceTemplate.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceTemplate.java deleted file mode 100644 index f7165c12..00000000 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceTemplate.java +++ /dev/null @@ -1,336 +0,0 @@ -/** - * Copyright 2016 [ZTE] and others. - * - * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.containerEntity; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -public class ContainerServiceTemplate { - @XmlAttribute - private String templateid; - - @XmlAttribute - private String templatename; - - @XmlElement(name = "BoundaryDefinitions") - private BoundaryDefinitions boundary; - - public String getTemplateid() { - return templateid; - } - - public void setTemplateid(String templateid) { - this.templateid = templateid; - } - - public String getTemplatename() { - return templatename; - } - - public void setTemplatename(String templatename) { - this.templatename = templatename; - } - - public BoundaryDefinitions getBoundary() { - return boundary; - } - - public void setBoundary(BoundaryDefinitions boundary) { - this.boundary = boundary; - } - - @XmlRootElement - @XmlAccessorType(XmlAccessType.NONE) - public static class BoundaryDefinitions { - @XmlElement(name = "Properties", namespace = "http://docs.oasis-open.org/tosca/ns/2011/12") - private BoundaryProperties properties; - - public BoundaryProperties getProperties() { - return properties; - } - - public void setProperties(BoundaryProperties properties) { - this.properties = properties; - } - - } - - @XmlRootElement - @XmlAccessorType(XmlAccessType.NONE) - public static class BoundaryProperties { - @XmlElement(name = "Properties") - private BoundaryProperty property; - - public BoundaryProperty getProperty() { - return property; - } - - public void setProperty(BoundaryProperty property) { - this.property = property; - } - } - - @XmlRootElement - @XmlAccessorType(XmlAccessType.NONE) - public static class BoundaryProperty { - public String getTemplateVersion() { - return templateVersion; - } - - public void setTemplateVersion(String templateVersion) { - this.templateVersion = templateVersion; - } - - public String getTemplateAuthor() { - return templateAuthor; - } - - public void setTemplateAuthor(String templateAuthor) { - this.templateAuthor = templateAuthor; - } - - public String getVendor() { - return vendor; - } - - public void setVendor(String vendor) { - this.vendor = vendor; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getNfvType() { - return nfvType; - } - - public void setNfvType(String nfvType) { - this.nfvType = nfvType; - } - - public String getMoc() { - return moc; - } - - public void setMoc(String moc) { - this.moc = moc; - } - - public String getFlavor() { - return flavor; - } - - public void setFlavor(String flavor) { - this.flavor = flavor; - } - - public List getStFlavor() { - return stFlavor; - } - - public void setStFlavor(List stFlavor) { - this.stFlavor = stFlavor; - } - - @XmlElement - private String templateVersion; - - @XmlElement - private String templateAuthor; - - @XmlElement - private String vendor; - - @XmlElement - private String version; - - @XmlElement - private String nfvType; - - @XmlElement - private String moc; - - @XmlElement - private String flavor; - - @XmlElementWrapper(name = "flavorList") - @XmlElement(name = "flavor") - private List stFlavor; - } - - @XmlRootElement - @XmlAccessorType(XmlAccessType.NONE) - public static class STFlavor { - @XmlAttribute - private String name; - - @XmlAttribute - private String desc; - - @XmlElementWrapper(name = "nodeList") - @XmlElement(name = "node") - private List stFlavorConstituent; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDesc() { - return desc; - } - - public void setDesc(String desc) { - this.desc = desc; - } - - public List getStFlavorConstituent() { - return stFlavorConstituent; - } - - public void setStFlavorConstituent( - List stFlavorConstituent) { - this.stFlavorConstituent = stFlavorConstituent; - } - } - - @XmlRootElement - @XmlAccessorType(XmlAccessType.NONE) - public static class STFlavorConstituent { - @XmlAttribute - private String numberOfInstances; - - @XmlAttribute - private String name; - - @XmlAttribute - private String refNodeFlavor; - - @XmlAttribute - private String affinity; - - @XmlAttribute - private String redundancyModel; - - @XmlAttribute - private String capability; - - public String getAffinity() { - return affinity; - } - - public void setAffinity(String affinity) { - this.affinity = affinity; - } - - public String getRedundancyModel() { - return redundancyModel; - } - - public void setRedundancyModel(String redundancyModel) { - this.redundancyModel = redundancyModel; - } - - public String getCapability() { - return capability; - } - - public void setCapability(String capability) { - this.capability = capability; - } - - public String getNumberOfInstances() { - return numberOfInstances; - } - - public void setNumberOfInstances(String numberOfInstances) { - this.numberOfInstances = numberOfInstances; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getRefNodeFlavor() { - return refNodeFlavor; - } - - public void setRefNodeFlavor(String refNodeFlavor) { - this.refNodeFlavor = refNodeFlavor; - } - } - - private Boolean propNullFlag; - - private boolean isPropNotNull() { - if (null == propNullFlag) { - propNullFlag = null != this.getBoundary() - && null != this.getBoundary().getProperties() - && null != this.getBoundary().getProperties().getProperty(); - } - return propNullFlag; - } - - public String getProductType() { - return isPropNotNull() ? this.getBoundary().getProperties() - .getProperty().getMoc() : null; - } - - public String getVendor() { - return isPropNotNull() ? this.getBoundary().getProperties() - .getProperty().getVendor() : null; - } - - public String getVersion() { - return isPropNotNull() ? this.getBoundary().getProperties() - .getProperty().getVersion() : null; - } - - public String getNfvtype() { - return isPropNotNull() ? this.getBoundary().getProperties() - .getProperty().getNfvType() : null; - } - - public String getFlavor() { - return isPropNotNull() ? this.getBoundary().getProperties() - .getProperty().getFlavor() : null; - } - - public List getSTFlavorList() { - return isPropNotNull() ? this.getBoundary().getProperties() - .getProperty().getStFlavor() : null; - } -} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceTemplateList.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceTemplateList.java deleted file mode 100644 index 81021f52..00000000 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceTemplateList.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright 2016 [ZTE] and others. - * - * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.containerEntity; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name="servicetemplates") -public class ContainerServiceTemplateList { - public static final String NAMESPACE_OF_SELFSERVICE="http://www.eclipse.org/winery/model/selfservice"; - - @XmlElement(name="serviceTemplate") - private List serviceTemplateList; - - public List getServiceTemplateList() { - return serviceTemplateList; - } - - public void setServiceTemplateList(List optionList) { - this.serviceTemplateList = optionList; - } -} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/lifecycle/InstanceEntity.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/lifecycle/InstanceEntity.java new file mode 100644 index 00000000..9f41acf6 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/lifecycle/InstanceEntity.java @@ -0,0 +1,29 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.lifecycle; + +public class InstanceEntity { + private String serviceTemplateId; + + public String getServiceTemplateId() { + return serviceTemplateId; + } + + public void setServiceTemplateId(String serviceTemplateId) { + this.serviceTemplateId = serviceTemplateId; + } +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/lifecycleEnity/InstanceEntity.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/lifecycleEnity/InstanceEntity.java deleted file mode 100644 index 3d317c6d..00000000 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/lifecycleEnity/InstanceEntity.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright 2016 [ZTE] and others. - * - * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.lifecycleEnity; - -public class InstanceEntity { - private String serviceTemplateId; - - public String getServiceTemplateId() { - return serviceTemplateId; - } - - public void setServiceTemplateId(String serviceTemplateId) { - this.serviceTemplateId = serviceTemplateId; - } -} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/ro/ResourceResponseEntity.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/ro/ResourceResponseEntity.java new file mode 100644 index 00000000..9783dc11 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/ro/ResourceResponseEntity.java @@ -0,0 +1,40 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.ro; + +import java.util.ArrayList; + +public class ResourceResponseEntity { + ArrayList data = new ArrayList(); + String operationResult; + + public String getOperationResult() { + return operationResult; + } + + public void setOperationResult(String operationResult) { + this.operationResult = operationResult; + } + + public ArrayList getData() { + return data; + } + + public void setData(ArrayList data) { + this.data = data; + } +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/ro/VimEntity.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/ro/VimEntity.java new file mode 100644 index 00000000..2fd71c84 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/ro/VimEntity.java @@ -0,0 +1,75 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.ro; + +public class VimEntity { + private String oid; + private String name; + private String user; + private String url; + private String userName; + private String password; + + public String getOid() { + return oid; + } + + public void setOid(String oid) { + this.oid = oid; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/roEntity/ResourceResponseEntity.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/roEntity/ResourceResponseEntity.java deleted file mode 100644 index d98bb87c..00000000 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/roEntity/ResourceResponseEntity.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright 2016 [ZTE] and others. - * - * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.roEntity; - -import java.util.ArrayList; - -public class ResourceResponseEntity -{ - ArrayList data=new ArrayList(); - String operationResult; - - public String getOperationResult() - { - return operationResult; - } - - public void setOperationResult(String operationResult) - { - this.operationResult = operationResult; - } - public ArrayList getData() - { - return data; - } - public void setData(ArrayList data) - { - this.data = data; - } -} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/roEntity/VimEntity.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/roEntity/VimEntity.java deleted file mode 100644 index 98f59200..00000000 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/roEntity/VimEntity.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright 2016 [ZTE] and others. - * - * Licensed 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.openo.commontosca.catalog.model.externalservice.entity.roEntity; - -public class VimEntity -{ - private String oid; - private String name; - private String user; - private String url; - private String userName; - private String password; - public String getOid() { - return oid; - } - public void setOid(String oid) { - this.oid = oid; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getUser() { - return user; - } - public void setUser(String user) { - this.user = user; - } - public String getUrl() { - return url; - } - public void setUrl(String url) { - this.url = url; - } - public String getUserName() { - return userName; - } - public void setUserName(String userName) { - this.userName = userName; - } - public String getPassword() { - return password; - } - public void setPassword(String password) { - this.password = password; - } - -} \ No newline at end of file diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/lifecycle/ILifeCycleServiceRest.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/lifecycle/ILifeCycleServiceRest.java index df87a529..fd370ec6 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/lifecycle/ILifeCycleServiceRest.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/lifecycle/ILifeCycleServiceRest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.externalservice.lifecycle; import javax.ws.rs.GET; @@ -22,12 +23,13 @@ import javax.ws.rs.core.MediaType; /** * The lifecycle interface. + * * @author 10189609 - * + * */ @Path("/appinstances") public interface ILifeCycleServiceRest { - @GET - @Produces(MediaType.APPLICATION_JSON) - public String getVNFInstances(); + @GET + @Produces(MediaType.APPLICATION_JSON) + public String getVnfInstances(); } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/lifecycle/LifeCycleServiceConsumer.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/lifecycle/LifeCycleServiceConsumer.java index f3bed0a0..f09170ff 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/lifecycle/LifeCycleServiceConsumer.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/lifecycle/LifeCycleServiceConsumer.java @@ -13,49 +13,55 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.externalservice.lifecycle; -import java.lang.reflect.Type; -import java.util.ArrayList; +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; -import org.openo.commontosca.catalog.common.MSBUtil; +import com.eclipsesource.jaxrs.consumer.ConsumerFactory; +import org.openo.commontosca.catalog.common.MsbUtil; import org.openo.commontosca.catalog.common.ToolUtil; -import org.openo.commontosca.catalog.model.externalservice.entity.lifecycleEnity.InstanceEntity; +import org.openo.commontosca.catalog.model.externalservice.entity.lifecycle.InstanceEntity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.eclipsesource.jaxrs.consumer.ConsumerFactory; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.ArrayList; + + /** * The lifecycle service. + * * @author 10189609 - * + * */ public class LifeCycleServiceConsumer { - private static final Logger LOG = LoggerFactory.getLogger(LifeCycleServiceConsumer.class); - - /** - * get lifecycle application instances. - * @return instance entity - */ - public static ArrayList getInstances() { - ILifeCycleServiceRest resourceserviceproxy = ConsumerFactory - .createConsumer(MSBUtil.getNsocLifecycleBaseUrl(), ILifeCycleServiceRest.class); - String result = ""; - try { - result = resourceserviceproxy.getVNFInstances(); - } catch (Exception e) { - LOG.error("query vim info faild.", e); - return null; - } - if (ToolUtil.isEmptyString(result)) { - return null; - } - - Gson gson = new Gson(); - Type listType = new TypeToken>() {}.getType(); - return gson.fromJson(result, listType); - } + private static final Logger LOG = LoggerFactory.getLogger(LifeCycleServiceConsumer.class); + + /** + * get lifecycle application instances. + * + * @return instance entity + */ + public static ArrayList getInstances() { + ILifeCycleServiceRest resourceserviceproxy = + ConsumerFactory.createConsumer(MsbUtil.getNsocLifecycleBaseUrl(), + ILifeCycleServiceRest.class); + String result = ""; + try { + result = resourceserviceproxy.getVnfInstances(); + } catch (Exception e1) { + LOG.error("query vim info faild.", e1); + return null; + } + if (ToolUtil.isEmptyString(result)) { + return null; + } + + Gson gson = new Gson(); + Type listType = new TypeToken>() {}.getType(); + return gson.fromJson(result, listType); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/ro/IResourceServiceRest.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/ro/IResourceServiceRest.java index d4075abe..1f82eaf4 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/ro/IResourceServiceRest.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/ro/IResourceServiceRest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.externalservice.ro; import javax.ws.rs.GET; @@ -23,13 +24,14 @@ import javax.ws.rs.core.MediaType; /** * The roc resource interface. + * * @author 10189609 - * + * */ @Path("/resource") public interface IResourceServiceRest { - @Path("/vims/{vim_id}") - @GET - @Produces(MediaType.APPLICATION_JSON) - public String getResourceVim(@PathParam("vim_id") String vimId) throws Exception; + @Path("/vims/{vim_id}") + @GET + @Produces(MediaType.APPLICATION_JSON) + public String getResourceVim(@PathParam("vim_id") String vimId) throws Exception; } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/ro/ResourceServiceConsumer.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/ro/ResourceServiceConsumer.java index 65431a2b..198c0025 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/ro/ResourceServiceConsumer.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/ro/ResourceServiceConsumer.java @@ -13,63 +13,66 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.externalservice.ro; -import org.openo.commontosca.catalog.common.MSBUtil; +import com.google.gson.Gson; + +import com.eclipsesource.jaxrs.consumer.ConsumerFactory; + +import org.openo.commontosca.catalog.common.MsbUtil; import org.openo.commontosca.catalog.common.ToolUtil; -import org.openo.commontosca.catalog.model.externalservice.entity.roEntity.ResourceResponseEntity; -import org.openo.commontosca.catalog.model.externalservice.entity.roEntity.VimEntity; +import org.openo.commontosca.catalog.model.externalservice.entity.ro.ResourceResponseEntity; +import org.openo.commontosca.catalog.model.externalservice.entity.ro.VimEntity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.eclipsesource.jaxrs.consumer.ConsumerFactory; -import com.google.gson.Gson; /** * The roc resource service. + * * @author 10189609 - * + * */ public class ResourceServiceConsumer { - private static final Logger LOG = LoggerFactory.getLogger(ResourceServiceConsumer.class); - - private static final String RESOURCE_REST_RESULT = "SUCCESS"; - - /** - * get vim entity from roc by vimid - * @param vimId id - * @return vim entity - */ - public static VimEntity getResourceVim(String vimId) { - LOG.info("begin query vim info from roc,vimId:" + vimId); - IResourceServiceRest resourceserviceproxy = ConsumerFactory - .createConsumer(MSBUtil.getRocBaseUrl(), IResourceServiceRest.class); - String result = ""; - try { - result = resourceserviceproxy.getResourceVim(vimId); - } catch (Exception e) { - LOG.error("query vim info faild.", e); - return null; - } - if (ToolUtil.isEmptyString(result)) { - LOG.error("query vim info faild, vim info is null, vimId:" + vimId); - return null; - } - - Gson gson = new Gson(); - ResourceResponseEntity responseEntity = gson.fromJson(result, ResourceResponseEntity.class); - if (!RESOURCE_REST_RESULT.equalsIgnoreCase(responseEntity.getOperationResult())) - { - LOG.error("query vim info faild.vimId:" + vimId); - return null; - } - if (responseEntity.getData().size() <= 0) - { - LOG.error("query vim info faild, vim info is empty, vimId:" + vimId); - return null; - } - - LOG.info("end query vim info from roc."); - return responseEntity.getData().get(0); - } + private static final Logger LOG = LoggerFactory.getLogger(ResourceServiceConsumer.class); + + private static final String RESOURCE_REST_RESULT = "SUCCESS"; + + /** + * get vim entity from roc by vimid. + * + * @param vimId id + * @return vim entity + */ + public static VimEntity getResourceVim(String vimId) { + LOG.info("begin query vim info from roc,vimId:" + vimId); + IResourceServiceRest resourceserviceproxy = + ConsumerFactory.createConsumer(MsbUtil.getRocBaseUrl(), IResourceServiceRest.class); + String result = ""; + try { + result = resourceserviceproxy.getResourceVim(vimId); + } catch (Exception e1) { + LOG.error("query vim info faild.", e1); + return null; + } + if (ToolUtil.isEmptyString(result)) { + LOG.error("query vim info faild, vim info is null, vimId:" + vimId); + return null; + } + + Gson gson = new Gson(); + ResourceResponseEntity responseEntity = gson.fromJson(result, ResourceResponseEntity.class); + if (!RESOURCE_REST_RESULT.equalsIgnoreCase(responseEntity.getOperationResult())) { + LOG.error("query vim info faild.vimId:" + vimId); + return null; + } + if (responseEntity.getData().size() <= 0) { + LOG.error("query vim info faild, vim info is empty, vimId:" + vimId); + return null; + } + + LOG.info("end query vim info from roc."); + return responseEntity.getData().get(0); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/AbstractModelParser.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/AbstractModelParser.java index 22780a31..5bc5f14b 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/AbstractModelParser.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/AbstractModelParser.java @@ -13,18 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.parser; import org.openo.commontosca.catalog.db.exception.CatalogResourceException; public abstract class AbstractModelParser { - /** - * @param packageId - * @param fileLocation - * @return service template id - * @throws CatalogResourceException - */ - public abstract String parse(String packageId, String fileLocation) - throws CatalogResourceException; - + + public abstract String parse(String packageId, String fileLocation) + throws CatalogResourceException; + } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/EnumPackageFormat.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/EnumPackageFormat.java index 10f60b99..ea245ecb 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/EnumPackageFormat.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/EnumPackageFormat.java @@ -13,13 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.parser; /** * enum data. + * * @author 10189609 - * + * */ public enum EnumPackageFormat { - TOSCA_XML, TOSCA_YAML + TOSCA_XML, TOSCA_YAML } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/EnumTemplateType.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/EnumTemplateType.java index e84bc871..07cc2e5b 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/EnumTemplateType.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/EnumTemplateType.java @@ -13,8 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.parser; public enum EnumTemplateType { - NS, VNF + NS, VNF } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/ModelParserFactory.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/ModelParserFactory.java index 74c2e2c1..f69e2ece 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/ModelParserFactory.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/ModelParserFactory.java @@ -13,43 +13,46 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.parser; +import org.openo.commontosca.catalog.db.exception.CatalogResourceException; + import java.util.HashMap; import java.util.Map; -import org.openo.commontosca.catalog.db.exception.CatalogResourceException; public class ModelParserFactory { - private final static ModelParserFactory instance = new ModelParserFactory(); - public static ModelParserFactory getInstance() { - return instance; - } + private static final ModelParserFactory instance = new ModelParserFactory(); - private Map pkgType2ParseMap = new HashMap(); + public static ModelParserFactory getInstance() { + return instance; + } - private ModelParserFactory() { - // PackageParseMap.put(EnumPackageFormat.TOSCA_XML, new - // ToscaXmlModelParser()); - pkgType2ParseMap.put(EnumPackageFormat.TOSCA_YAML, new ToscaYamlModelParser()); - } + private Map pkgType2ParseMap = + new HashMap(); - /** - * - * @param packageId - * @param fileLocation - * @param format - * @return service template id - * @throws CatalogResourceException - */ - public String parse(String packageId, String fileLocation, - EnumPackageFormat format) throws CatalogResourceException { - if (pkgType2ParseMap.get(format) == null) { - throw new CatalogResourceException( - "Can't find its parser. package type = " - + format.toString()); - } - - return pkgType2ParseMap.get(format).parse(packageId, fileLocation); + private ModelParserFactory() { + // PackageParseMap.put(EnumPackageFormat.TOSCA_XML, new + // ToscaXmlModelParser()); + pkgType2ParseMap.put(EnumPackageFormat.TOSCA_YAML, new ToscaYamlModelParser()); + } + + /** + * parse package. + * @param packageId package id + * @param fileLocation package location + * @param format package format + * @return service template id + * @throws CatalogResourceException e + */ + public String parse(String packageId, String fileLocation, EnumPackageFormat format) + throws CatalogResourceException { + if (pkgType2ParseMap.get(format) == null) { + throw new CatalogResourceException("Can't find its parser. package type = " + + format.toString()); } + + return pkgType2ParseMap.get(format).parse(packageId, fileLocation); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/ToscaYamlModelParser.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/ToscaYamlModelParser.java index 17932538..773cc1b4 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/ToscaYamlModelParser.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/ToscaYamlModelParser.java @@ -13,8 +13,37 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.parser; +import org.openo.commontosca.catalog.common.ToolUtil; +import org.openo.commontosca.catalog.db.exception.CatalogResourceException; +import org.openo.commontosca.catalog.db.resource.TemplateManager; +import org.openo.commontosca.catalog.entity.response.CsarFileUriResponse; +import org.openo.commontosca.catalog.model.common.TemplateDataHelper; +import org.openo.commontosca.catalog.model.entity.EnumDataType; +import org.openo.commontosca.catalog.model.entity.InputParameter; +import org.openo.commontosca.catalog.model.entity.NodeTemplate; +import org.openo.commontosca.catalog.model.entity.OutputParameter; +import org.openo.commontosca.catalog.model.entity.RelationShip; +import org.openo.commontosca.catalog.model.entity.ServiceTemplate; +import org.openo.commontosca.catalog.model.entity.ServiceTemplateOperation; +import org.openo.commontosca.catalog.model.entity.SubstitutionMapping; +import org.openo.commontosca.catalog.model.parser.yaml.YamlParseServiceConsumer; +import org.openo.commontosca.catalog.model.parser.yaml.entity.EnumYamlServiceTemplateInfo; +import org.openo.commontosca.catalog.model.parser.yaml.entity.ParseYamlRequestParemeter; +import org.openo.commontosca.catalog.model.parser.yaml.entity.ParseYamlResult; +import org.openo.commontosca.catalog.model.parser.yaml.entity.ParseYamlResult.Plan; +import org.openo.commontosca.catalog.model.parser.yaml.entity.ParseYamlResult.Plan.PlanValue.PlanInput; +import org.openo.commontosca.catalog.model.parser.yaml.entity.ParseYamlResult.TopologyTemplate.Input; +import org.openo.commontosca.catalog.model.parser.yaml.entity.ParseYamlResult.TopologyTemplate.NodeTemplate.Relationship; +import org.openo.commontosca.catalog.model.parser.yaml.entity.ParseYamlResult.TopologyTemplate.Output; +import org.openo.commontosca.catalog.model.plan.wso2.Wso2ServiceConsumer; +import org.openo.commontosca.catalog.model.plan.wso2.entity.DeployPackageResponse; +import org.openo.commontosca.catalog.wrapper.PackageWrapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; @@ -30,343 +59,320 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; -import org.openo.commontosca.catalog.db.exception.CatalogResourceException; -import org.openo.commontosca.catalog.db.resource.TemplateManager; -import org.openo.commontosca.catalog.entity.response.CsarFileUriResponse; -import org.openo.commontosca.catalog.model.common.TemplateDataHelper; -import org.openo.commontosca.catalog.model.entity.InputParameter; -import org.openo.commontosca.catalog.model.entity.RelationShip; -import org.openo.commontosca.catalog.model.entity.ServiceTemplate; -import org.openo.commontosca.catalog.model.entity.ServiceTemplateOperation; -import org.openo.commontosca.catalog.model.entity.SubstitutionMapping; -import org.openo.commontosca.catalog.model.parser.yaml.entity.ParseYamlResult; -import org.openo.commontosca.catalog.wrapper.PackageWrapper; -import org.openo.commontosca.catalog.common.ToolUtil; -import org.openo.commontosca.catalog.model.entity.EnumDataType; -import org.openo.commontosca.catalog.model.entity.NodeTemplate; -import org.openo.commontosca.catalog.model.parser.yaml.YamlParseServiceConsumer; -import org.openo.commontosca.catalog.model.parser.yaml.entity.EnumYamlServiceTemplateInfo; -import org.openo.commontosca.catalog.model.parser.yaml.entity.ParseYamlRequestParemeter; -public class ToscaYamlModelParser extends AbstractModelParser{ - - private static final Object TOSCA_META_FIELD_ENTRY_DEFINITIONS = "Entry-Definitions"; - - /** - * - */ - @Override - public String parse(String packageId, String fileLocation) - throws CatalogResourceException { - ParseYamlResult result = YamlParseServiceConsumer.getServiceTemplates(comboRequest(fileLocation)); - - Map toscaMeta = parseToscaMeta(fileLocation); - String stFileName = toscaMeta.get(TOSCA_META_FIELD_ENTRY_DEFINITIONS); - CsarFileUriResponse stDownloadUri = PackageWrapper.getInstance() - .getCsarFileDownloadUri(packageId, stFileName); - - ServiceTemplate st = parseServiceTemplate(packageId, result, - stDownloadUri.getDownloadUri()); - List ntList = parseNodeTemplates(packageId, - st.getServiceTemplateId(), result); - st.setType(getTemplateType(result, ntList).toString()); - - TemplateManager.getInstance().addServiceTemplate( - TemplateDataHelper.convert2TemplateData(st, - ToolUtil.toJson(result), ntList)); - - SubstitutionMapping stm = parseSubstitutionMapping( - st.getServiceTemplateId(), result); - if (stm != null) { - TemplateManager.getInstance().addServiceTemplateMapping( - TemplateDataHelper.convert2TemplateMappingData(stm)); - } +public class ToscaYamlModelParser extends AbstractModelParser { - return st.getServiceTemplateId(); - } + private static final Object TOSCA_META_FIELD_ENTRY_DEFINITIONS = "Entry-Definitions"; + private static final Logger LOGGER = LoggerFactory.getLogger(ToscaYamlModelParser.class); - /** - * @param fileLocation - * @return - * @throws CatalogResourceException - */ - @SuppressWarnings("resource") - private Map parseToscaMeta(String fileLocation) - throws CatalogResourceException { - Map toscaMeta = new HashMap<>(); - - ZipInputStream zin = null; - BufferedReader br = null; - try { - InputStream in = new BufferedInputStream(new FileInputStream( - fileLocation)); - zin = new ZipInputStream(in); - ZipEntry ze; - while ((ze = zin.getNextEntry()) != null) { - if (("TOSCA-Metadata" + File.separator + "TOSCA.meta") - .equals(ze.getName()) - || "TOSCA-Metadata/TOSCA.meta".equals(ze.getName())) { - ZipFile zf = new ZipFile(fileLocation); - br = new BufferedReader(new InputStreamReader( - zf.getInputStream(ze))); - String line; - String[] tmps; - while ((line = br.readLine()) != null) { - if (line.indexOf(":") > 0) { - tmps = line.split(":"); - toscaMeta.put(tmps[0].trim(), tmps[1].trim()); - } - } - - return toscaMeta; - } - } + @Override + public String parse(String packageId, String fileLocation) throws CatalogResourceException { + ParseYamlResult result = + YamlParseServiceConsumer.getServiceTemplates(comboRequest(fileLocation)); - } catch (IOException e) { - throw new CatalogResourceException("Parse Tosca Meta Fail.", e); - } finally { - closeStreamAndReader(zin, br); - } + Map toscaMeta = parseToscaMeta(fileLocation); + String stFileName = toscaMeta.get(TOSCA_META_FIELD_ENTRY_DEFINITIONS); + CsarFileUriResponse stDownloadUri = + PackageWrapper.getInstance().getCsarFileDownloadUri(packageId, stFileName); - return toscaMeta; + ServiceTemplate st = parseServiceTemplate(packageId, result, stDownloadUri.getDownloadUri()); + ServiceTemplateOperation[] operations = parseOperations(result.getPlanList(), fileLocation); + st.setOperations(operations); + List ntList = parseNodeTemplates(packageId, st.getServiceTemplateId(), result); + st.setType(getTemplateType(result, ntList).toString()); + + TemplateManager.getInstance().addServiceTemplate( + TemplateDataHelper.convert2TemplateData(st, ToolUtil.toJson(result), ntList)); + + SubstitutionMapping stm = parseSubstitutionMapping(st.getServiceTemplateId(), result); + if (stm != null) { + TemplateManager.getInstance() + .addServiceTemplateMapping(TemplateDataHelper.convert2TemplateMappingData(stm)); } - private void closeStreamAndReader(ZipInputStream zin, BufferedReader br) { - if (br != null) { - try { - br.close(); - } catch (IOException e) { - } - } - if (zin != null) { - try { - zin.closeEntry(); - } catch (IOException e) { + return st.getServiceTemplateId(); + } + + @SuppressWarnings("resource") + private Map parseToscaMeta(String fileLocation) throws CatalogResourceException { + Map toscaMeta = new HashMap<>(); + + ZipInputStream zin = null; + BufferedReader br = null; + try { + InputStream in = new BufferedInputStream(new FileInputStream(fileLocation)); + zin = new ZipInputStream(in); + ZipEntry ze; + while ((ze = zin.getNextEntry()) != null) { + if (("TOSCA-Metadata" + File.separator + "TOSCA.meta").equals(ze.getName()) + || "TOSCA-Metadata/TOSCA.meta".equals(ze.getName())) { + ZipFile zf = new ZipFile(fileLocation); + br = new BufferedReader(new InputStreamReader(zf.getInputStream(ze))); + String line; + String[] tmps; + while ((line = br.readLine()) != null) { + if (line.indexOf(":") > 0) { + tmps = line.split(":"); + toscaMeta.put(tmps[0].trim(), tmps[1].trim()); } + } + + return toscaMeta; } - } + } - private ParseYamlRequestParemeter comboRequest(String fileLocation) { - ParseYamlRequestParemeter request = new ParseYamlRequestParemeter(); - request.setPath(fileLocation); - return request; + } catch (IOException e1) { + throw new CatalogResourceException("Parse Tosca Meta Fail.", e1); + } finally { + closeStreamAndReader(zin, br); } - /** - * @param serviceTemplateId - * @param result - * @return - */ - private SubstitutionMapping parseSubstitutionMapping( - String serviceTemplateId, ParseYamlResult result) { - String type = getSubstitutionMappingType(result); - if (ToolUtil.isTrimedEmptyString(type)) { - return null; - } + return toscaMeta; + } - ParseYamlResult.TopologyTemplate.SubstitutionMapping stm = result - .getTopologyTemplate().getSubstitutionMappings(); - return new SubstitutionMapping(serviceTemplateId, type, - stm.getRequirementList(), stm.getCapabilityList()); + private void closeStreamAndReader(ZipInputStream zin, BufferedReader br) { + if (br != null) { + try { + br.close(); + } catch (IOException e1) { + LOGGER.error("Buffered reader close failed !"); + } + } + if (zin != null) { + try { + zin.closeEntry(); + } catch (IOException e2) { + LOGGER.error("Zip inputStream close failed !"); + } + } + } + + private ParseYamlRequestParemeter comboRequest(String fileLocation) { + ParseYamlRequestParemeter request = new ParseYamlRequestParemeter(); + request.setPath(fileLocation); + return request; + } + + private SubstitutionMapping parseSubstitutionMapping(String serviceTemplateId, + ParseYamlResult result) { + String type = getSubstitutionMappingType(result); + if (ToolUtil.isTrimedEmptyString(type)) { + return null; } - private ServiceTemplate parseServiceTemplate(String packageId, - ParseYamlResult result, String stDownloadUri) { - ServiceTemplate st = new ServiceTemplate(); - - st.setServiceTemplateId(ToolUtil.generateId()); - st.setTemplateName(result.getMetadata().get( - EnumYamlServiceTemplateInfo.ID.getName())); - st.setVendor(result.getMetadata().get( - EnumYamlServiceTemplateInfo.PROVIDER.getName())); - st.setVersion(result.getMetadata().get( - EnumYamlServiceTemplateInfo.VERSION.getName())); - st.setCsarid(packageId); - st.setDownloadUri(stDownloadUri); - st.setInputs(parseInputs(result)); - ServiceTemplateOperation[] operations = parseOperations(result - .getPlanList()); - st.setOperations(operations); - return st; + org.openo.commontosca.catalog.model.parser.yaml.entity.ParseYamlResult + .TopologyTemplate.SubstitutionMapping stm = + result.getTopologyTemplate().getSubstitutionMappings(); + return new SubstitutionMapping(serviceTemplateId, type, stm.getRequirementList(), + stm.getCapabilityList()); + } + + private ServiceTemplate parseServiceTemplate(String packageId, ParseYamlResult result, + String stDownloadUri) { + ServiceTemplate st = new ServiceTemplate(); + + st.setServiceTemplateId(ToolUtil.generateId()); + st.setTemplateName(result.getMetadata().get(EnumYamlServiceTemplateInfo.ID.getName())); + st.setVendor(result.getMetadata().get(EnumYamlServiceTemplateInfo.PROVIDER.getName())); + st.setVersion(result.getMetadata().get(EnumYamlServiceTemplateInfo.VERSION.getName())); + st.setCsarid(packageId); + st.setDownloadUri(stDownloadUri); + st.setInputs(parseInputs(result)); + st.setOutputs(parseOutputs(result)); + return st; + } + + private InputParameter[] parseInputs(ParseYamlResult result) { + List inputList = result.getTopologyTemplate().getInputs(); + if (inputList == null) { + return new InputParameter[0]; + } + List retList = new ArrayList(); + for (Input input : inputList) { + retList.add(new InputParameter(input.getName(), getEnumDataType(input.getType()), + input.getDescription(), input.getDefault(), input.isRequired())); } + return retList.toArray(new InputParameter[0]); + } - /** - * @param planList - * @return - */ - private ServiceTemplateOperation[] parseOperations(List planList) { - if (planList == null || planList.isEmpty()) { - return new ServiceTemplateOperation[0]; - } + private OutputParameter[] parseOutputs(ParseYamlResult result) { + List outputList = result.getTopologyTemplate().getOutputs(); + if (outputList == null || outputList.isEmpty()) { + return new OutputParameter[0]; + } + List retList = new ArrayList(); + for (Output output : outputList) { + retList + .add(new OutputParameter(output.getName(), output.getDescription(), output.getValue())); + } + return retList.toArray(new OutputParameter[0]); + } + + private ServiceTemplateOperation[] parseOperations(List planList, String zipFileLocation) + throws CatalogResourceException { + if (planList == null || planList.isEmpty()) { + return new ServiceTemplateOperation[0]; + } - List opList = new ArrayList<>(); - for (ParseYamlResult.Plan plan : planList) { - ServiceTemplateOperation op = new ServiceTemplateOperation(); - op.setName(plan.getName()); - op.setDescription(plan.getDescription()); - String processId = null; // TODO - op.setProcessId(processId); - InputParameter[] inputs = parsePlanInputs(plan.getInputList()); - op.setInputs(inputs); + List opList = new ArrayList<>(); + for (Plan plan : planList) { + ServiceTemplateOperation op = new ServiceTemplateOperation(); + op.setName(plan.getName()); + op.setDescription(plan.getDescription()); + checkPlanLanguage(plan.getPlanLanguage()); + DeployPackageResponse response = + Wso2ServiceConsumer.deployPackage(zipFileLocation, plan.getReference()); + op.setPackageName(parsePackageName(response)); + op.setProcessId(response.getProcessId()); + op.setInputs(parsePlanInputs(plan.getInputList())); - opList.add(op); + opList.add(op); - } - return opList.toArray(new ServiceTemplateOperation[0]); } + return opList.toArray(new ServiceTemplateOperation[0]); + } - /** - * @param inputList - * @return - */ - private InputParameter[] parsePlanInputs(List inputList) { - if (inputList == null || inputList.isEmpty()) { - return new InputParameter[0]; - } + private String parsePackageName(DeployPackageResponse response) { + String packageName = response.getPackageName(); + if (packageName != null && packageName.indexOf("-") > 0) { + packageName = packageName.substring(0, packageName.lastIndexOf("-")); + } + return packageName; + } - List retList = new ArrayList<>(); - for (ParseYamlResult.Plan.PlanValue.PlanInput input : inputList) { - retList.add(new InputParameter(input.getName(), - getEnumDataType(input.getType()), input.getDescription(), - input.getDefault(), input.isRequired())); - } - return retList.toArray(new InputParameter[0]); + private void checkPlanLanguage(String planLanguage) throws CatalogResourceException { + if (planLanguage == null || planLanguage.isEmpty()) { + throw new CatalogResourceException("Plan Language is empty."); + } + if (planLanguage.equalsIgnoreCase("bpel")) { + return; } + if (planLanguage.equalsIgnoreCase("bpmn")) { + return; + } + if (planLanguage.equalsIgnoreCase("bpmn4tosca")) { + return; + } + throw new CatalogResourceException( + "Plan Language is not supported. Language = " + planLanguage); + } - private InputParameter[] parseInputs(ParseYamlResult result) { - List inputList = result.getTopologyTemplate().getInputs(); - if(inputList == null){ - return null; - } - ArrayList retList = new ArrayList(); - for(ParseYamlResult.TopologyTemplate.Input input : inputList){ - retList.add(new InputParameter(input.getName(), - getEnumDataType(input.getType()), input.getDescription(), - input.getDefault(), input.isRequired())); - } - return retList.toArray(new InputParameter[0]); + private InputParameter[] parsePlanInputs(List inputList) { + if (inputList == null || inputList.isEmpty()) { + return new InputParameter[0]; } - /** - * @param type - * @return - */ - private EnumDataType getEnumDataType(String type) { - if (EnumDataType.INTEGER.toString().equalsIgnoreCase(type)) { - return EnumDataType.INTEGER; - } + List retList = new ArrayList<>(); + for (PlanInput input : inputList) { + retList.add(new InputParameter(input.getName(), getEnumDataType(input.getType()), + input.getDescription(), input.getDefault(), input.isRequired())); + } + return retList.toArray(new InputParameter[0]); + } - if (EnumDataType.FLOAT.toString().equalsIgnoreCase(type)) { - return EnumDataType.FLOAT; - } + private EnumDataType getEnumDataType(String type) { + if (EnumDataType.INTEGER.toString().equalsIgnoreCase(type)) { + return EnumDataType.INTEGER; + } - if (EnumDataType.BOOLEAN.toString().equalsIgnoreCase(type)) { - return EnumDataType.BOOLEAN; - } + if (EnumDataType.FLOAT.toString().equalsIgnoreCase(type)) { + return EnumDataType.FLOAT; + } - return EnumDataType.STRING; + if (EnumDataType.BOOLEAN.toString().equalsIgnoreCase(type)) { + return EnumDataType.BOOLEAN; } - /** - * @param csarId - * @param templateId - * @param result - * @return - */ - private List parseNodeTemplates(String csarId, - String templateId, ParseYamlResult result) { - List nodetemplateList = result.getTopologyTemplate().getNodeTemplates(); - if(nodetemplateList == null){ - return null; - } - - List retList = new ArrayList<>(); - for (ParseYamlResult.TopologyTemplate.NodeTemplate nodeTemplate : nodetemplateList) { - NodeTemplate ret = new NodeTemplate(); - ret.setId(nodeTemplate.getName()); - ret.setName(nodeTemplate.getName()); - ret.setType(nodeTemplate.getNodeType()); - ret.setProperties(nodeTemplate.getPropertyList()); - List relationShipList = parseNodeTemplateRelationShip(nodeTemplate - .getRelationships()); - ret.setRelationShips(relationShipList); - - retList.add(ret); - } + return EnumDataType.STRING; + } - return retList; + private List parseNodeTemplates(String csarId, String templateId, + ParseYamlResult result) { + List nodetemplateList = + result.getTopologyTemplate().getNodeTemplates(); + if (nodetemplateList == null) { + return null; } - - - private List parseNodeTemplateRelationShip( - List relationshipList) { - List retList = new ArrayList<>(); - - if (relationshipList == null) { - return retList; - } - for (ParseYamlResult.TopologyTemplate.NodeTemplate.Relationship relationship : relationshipList) { - RelationShip ret = new RelationShip(); - ret.setSourceNodeId(relationship.getSourceNodeName()); - ret.setSourceNodeName(relationship.getSourceNodeName()); - ret.setTargetNodeId(relationship.getTargetNodeName()); - ret.setTargetNodeName(relationship.getTargetNodeName()); - ret.setType(relationship.getType()); - retList.add(ret); - } + List retList = new ArrayList<>(); + for (ParseYamlResult.TopologyTemplate.NodeTemplate nodeTemplate : nodetemplateList) { + NodeTemplate ret = new NodeTemplate(); + ret.setId(nodeTemplate.getName()); + ret.setName(nodeTemplate.getName()); + ret.setType(nodeTemplate.getNodeType()); + ret.setProperties(nodeTemplate.getPropertyList()); + List relationShipList = + parseNodeTemplateRelationShip(nodeTemplate.getRelationships()); + ret.setRelationShips(relationShipList); + + retList.add(ret); + } + + return retList; + } + - return retList; + private List parseNodeTemplateRelationShip(List relationshipList) { + List retList = new ArrayList<>(); + + if (relationshipList == null) { + return retList; } - - private EnumTemplateType getTemplateType(ParseYamlResult result, - List ntList) { - String type = getSubstitutionMappingType(result); - if (isNSType(type)) { - return EnumTemplateType.NS; - } - - if (isVNFType(type)) { - return EnumTemplateType.VNF; - } - return getTemplateTypeFromNodeTemplates(ntList); + for (Relationship relationship : relationshipList) { + RelationShip ret = new RelationShip(); + ret.setSourceNodeId(relationship.getSourceNodeName()); + ret.setSourceNodeName(relationship.getSourceNodeName()); + ret.setTargetNodeId(relationship.getTargetNodeName()); + ret.setTargetNodeName(relationship.getTargetNodeName()); + ret.setType(relationship.getType()); + retList.add(ret); } - private String getSubstitutionMappingType(ParseYamlResult result) { - if (result.getTopologyTemplate().getSubstitutionMappings() == null) { - return null; - } - return result.getTopologyTemplate().getSubstitutionMappings() - .getNode_type(); + return retList; + } + + private EnumTemplateType getTemplateType(ParseYamlResult result, List ntList) { + String type = getSubstitutionMappingType(result); + if (isNsType(type)) { + return EnumTemplateType.NS; } - /** - * @param ntList - * @return - */ - private EnumTemplateType getTemplateTypeFromNodeTemplates( - List ntList) { - for (NodeTemplate nt : ntList) { - if (isNSType(nt.getType()) || isVNFType(nt.getType())) { - return EnumTemplateType.NS; - } - } + if (isVnfType(type)) { + return EnumTemplateType.VNF; + } - return EnumTemplateType.VNF; + return getTemplateTypeFromNodeTemplates(ntList); + } + + private String getSubstitutionMappingType(ParseYamlResult result) { + if (result.getTopologyTemplate().getSubstitutionMappings() == null) { + return null; + } + return result.getTopologyTemplate().getSubstitutionMappings().getNodeType(); + } + + private EnumTemplateType getTemplateTypeFromNodeTemplates(List ntList) { + for (NodeTemplate nt : ntList) { + if (isNsType(nt.getType()) || isVnfType(nt.getType())) { + return EnumTemplateType.NS; + } } - private boolean isVNFType(String type) { - if (ToolUtil.isTrimedEmptyString(type)) { - return false; - } - return type.toUpperCase().contains(".VNF"); + return EnumTemplateType.VNF; + } + + private boolean isVnfType(String type) { + if (ToolUtil.isTrimedEmptyString(type)) { + return false; } + return type.toUpperCase().contains(".VNF"); + } - private boolean isNSType(String type) { - if (ToolUtil.isTrimedEmptyString(type)) { - return false; - } - return type.toUpperCase().contains(".NS"); + private boolean isNsType(String type) { + if (ToolUtil.isTrimedEmptyString(type)) { + return false; } + return type.toUpperCase().contains(".NS"); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/IYamlParseRest.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/IYamlParseRest.java index 8d24a606..82b1b47e 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/IYamlParseRest.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/IYamlParseRest.java @@ -13,31 +13,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.parser.yaml; +import org.openo.commontosca.catalog.model.parser.yaml.entity.ParseYamlRequestParemeter; + import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; -import org.openo.commontosca.catalog.model.parser.yaml.entity.ParseYamlRequestParemeter; -/** - * - * @author 10090474 - * - */ @Path("/parse") public interface IYamlParseRest { - /** - * @param request - * @return - * @throws Exception - */ - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - String parse(ParseYamlRequestParemeter request) - throws Exception; + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + String parse(ParseYamlRequestParemeter request) throws Exception; } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/YamlParseServiceConsumer.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/YamlParseServiceConsumer.java index 5942a8bd..b62bd166 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/YamlParseServiceConsumer.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/YamlParseServiceConsumer.java @@ -13,43 +13,40 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.parser.yaml; +import com.google.gson.Gson; + +import com.eclipsesource.jaxrs.consumer.ConsumerFactory; + import org.glassfish.jersey.client.ClientConfig; -import org.openo.commontosca.catalog.common.MSBUtil; +import org.openo.commontosca.catalog.common.MsbUtil; import org.openo.commontosca.catalog.db.exception.CatalogResourceException; -import org.openo.commontosca.catalog.model.parser.yaml.entity.ParseYamlResult; import org.openo.commontosca.catalog.model.parser.yaml.entity.ParseYamlRequestParemeter; +import org.openo.commontosca.catalog.model.parser.yaml.entity.ParseYamlResult; -import com.eclipsesource.jaxrs.consumer.ConsumerFactory; -import com.google.gson.Gson; -/** - * - * @author 10090474 - * - */ public class YamlParseServiceConsumer { - /** - * get service template by template id from container service. - * - * @param request - * @return - * @throws CatalogResourceException - */ - public static ParseYamlResult getServiceTemplates( - final ParseYamlRequestParemeter request) - throws CatalogResourceException { - try { - ClientConfig config = new ClientConfig(); - IYamlParseRest yamlParseProxy = ConsumerFactory - .createConsumer(MSBUtil.getYamlParseBaseUrl(), config, - IYamlParseRest.class); - String jsonStr = yamlParseProxy.parse(request); - return new Gson().fromJson(jsonStr, ParseYamlResult.class); - } catch (Exception e) { - throw new CatalogResourceException("Call parser api failed.", e); - } - + /** + * get service template by template id from container service. + * + * @param request parse yaml request + * @return parase yaml result + * @throws CatalogResourceException e + */ + public static ParseYamlResult getServiceTemplates(final ParseYamlRequestParemeter request) + throws CatalogResourceException { + try { + ClientConfig config = new ClientConfig(); + IYamlParseRest yamlParseProxy = + ConsumerFactory.createConsumer(MsbUtil.getYamlParseBaseUrl(), config, + IYamlParseRest.class); + String jsonStr = yamlParseProxy.parse(request); + return new Gson().fromJson(jsonStr, ParseYamlResult.class); + } catch (Exception e1) { + throw new CatalogResourceException("Call parser api failed.", e1); } + + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/entity/EnumYamlServiceTemplateInfo.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/entity/EnumYamlServiceTemplateInfo.java index ea9fe998..ba31eee6 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/entity/EnumYamlServiceTemplateInfo.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/entity/EnumYamlServiceTemplateInfo.java @@ -13,29 +13,29 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.model.parser.yaml.entity; +package org.openo.commontosca.catalog.model.parser.yaml.entity; public enum EnumYamlServiceTemplateInfo { - ID{ - @Override - public String getName() { - return "id"; - } - }, - VERSION{ - @Override - public String getName() { - return "version"; - } - }, - PROVIDER{ - @Override - public String getName() { - return "vendor"; - } - }; - - public abstract String getName(); + ID { + @Override + public String getName() { + return "id"; + } + }, + VERSION { + @Override + public String getName() { + return "version"; + } + }, + PROVIDER { + @Override + public String getName() { + return "vendor"; + } + }; + + public abstract String getName(); } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/entity/ParseYamlRequestParemeter.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/entity/ParseYamlRequestParemeter.java index 49d6f4cb..0ba640ac 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/entity/ParseYamlRequestParemeter.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/entity/ParseYamlRequestParemeter.java @@ -13,49 +13,54 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.parser.yaml.entity; import java.util.List; public class ParseYamlRequestParemeter { - private String path = "E:\\NFVO\\130. yaml2xml\\0. tosca-parser\\sample\\ag-vnfd-floatingIp.zip"; - - private List extensionList; - - public String getPath() { - return path; - } + private String path = "E:\\NFVO\\130. yaml2xml\\0. tosca-parser\\sample\\ag-vnfd-floatingIp.zip"; - public void setPath(String path) { - this.path = path; - } + private List extensionList; + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } - public List getExtensionList() { - return extensionList; + public List getExtensionList() { + return extensionList; + } + + public void setExtensionList(List extensionList) { + this.extensionList = extensionList; + } + + public Extension createExtension() { + return new Extension(); + } + + public class Extension { + private String name; + private String value; + + public String getName() { + return name; } - public void setExtensionList(List extensionList) { - this.extensionList = extensionList; + public void setName(String name) { + this.name = name; } - public Extension createExtension(){ - return new Extension(); + public String getValue() { + return value; } - - public class Extension { - private String name; - private String value; - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getValue() { - return value; - } - public void setValue(String value) { - this.value = value; - } + + public void setValue(String value) { + this.value = value; } + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/entity/ParseYamlResult.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/entity/ParseYamlResult.java index fa9cdf7b..5075f485 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/entity/ParseYamlResult.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/entity/ParseYamlResult.java @@ -13,8 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.parser.yaml.entity; +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.annotations.SerializedName; + import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; @@ -22,822 +29,859 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; public class ParseYamlResult { - private String toscaDefinitionsVersion; + private String toscaDefinitionsVersion; + private String description; + private JsonObject nodeTypes; + private JsonObject capabilityTypes; + private JsonObject relationshipTypes; + private JsonObject policyTypes; + private TopologyTemplate topologyTemplate; + private Map metadata; + private JsonObject plans; + + + public String getToscaDefinitionsVersion() { + return toscaDefinitionsVersion; + } + + public void setToscaDefinitionsVersion(String toscaDefinitionsVersion) { + this.toscaDefinitionsVersion = toscaDefinitionsVersion; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public JsonObject getNodeTypes() { + return nodeTypes; + } + + public void setNodeTypes(JsonObject nodeTypes) { + this.nodeTypes = nodeTypes; + } + + public List getNodeTypeList() { + return jsonObject2NodeTypes(nodeTypes); + } + + private ArrayList jsonObject2NodeTypes(JsonObject nodeTypes) { + ArrayList nodeTypeList = new ArrayList(); + Iterator> iterator = nodeTypes.entrySet().iterator(); + while (iterator.hasNext()) { + NodeType type = new NodeType(); + Entry next = iterator.next(); + type.setType(next.getKey()); + type.setValue(new Gson().fromJson(next.getValue(), NodeType.NodeTypeValue.class)); + nodeTypeList.add(type); + } + return nodeTypeList; + } + + public JsonObject getCapabilityTypes() { + return capabilityTypes; + } + + public void setCapabilityTypes(JsonObject capabilityTypes) { + this.capabilityTypes = capabilityTypes; + } + + public JsonObject getRelationshipTypes() { + return relationshipTypes; + } + + public void setRelationshipTypes(JsonObject relationshipTypes) { + this.relationshipTypes = relationshipTypes; + } + + public List getRelationshipTypeList() { + return jsonObject2RelationshipTypes(relationshipTypes); + } + + private ArrayList jsonObject2RelationshipTypes(JsonObject relationshipTypes) { + ArrayList relationshipTypeList = new ArrayList(); + Iterator> iterator = relationshipTypes.entrySet().iterator(); + while (iterator.hasNext()) { + RelationshipType type = new RelationshipType(); + Entry next = iterator.next(); + type.setType(next.getKey()); + type.setValue(new Gson().fromJson(next.getValue(), RelationshipType.RelationshipValue.class)); + relationshipTypeList.add(type); + } + return relationshipTypeList; + } + + public JsonObject getPolicyTypes() { + return policyTypes; + } + + public void setPolicyTypes(JsonObject policyTypes) { + this.policyTypes = policyTypes; + } + + public TopologyTemplate getTopologyTemplate() { + return topologyTemplate; + } + + public void setTopologyTemplate(TopologyTemplate topologyTemplate) { + this.topologyTemplate = topologyTemplate; + } + + public Map getMetadata() { + return metadata; + } + + public void setMetadata(Map metadata) { + this.metadata = metadata; + } + + public JsonObject getPlans() { + return plans; + } + + public void setPlans(JsonObject plans) { + this.plans = plans; + } + + public List getPlanList() { + return jsonObject2PlanList(this.plans); + } + + private List jsonObject2PlanList(JsonObject plans) { + List retList = new ArrayList(); + Iterator> iterator = plans.entrySet().iterator(); + while (iterator.hasNext()) { + Plan ret = new Plan(); + Entry next = iterator.next(); + ret.setName(next.getKey()); + ret.setValue(new Gson().fromJson(next.getValue(), Plan.PlanValue.class)); + retList.add(ret); + } + return retList; + } + + public class TopologyTemplate { private String description; - private JsonObject nodeTypes; - private JsonObject capabilityTypes; - private JsonObject relationshipTypes; - private JsonObject policyTypes; - private TopologyTemplate topologyTemplate; - private Map metadata; - private JsonObject plans; - + private List inputs; + private List outputs; + private List nodeTemplates; + private SubstitutionMapping substitutionMappings; - public String getToscaDefinitionsVersion() { - return toscaDefinitionsVersion; + public String getDescription() { + return description; } - public void setToscaDefinitionsVersion(String toscaDefinitionsVersion) { - this.toscaDefinitionsVersion = toscaDefinitionsVersion; + public void setDescription(String description) { + this.description = description; } - public String getDescription() { - return description; + public List getInputs() { + return inputs; } - public void setDescription(String description) { - this.description = description; + public void setInputs(List inputs) { + this.inputs = inputs; } - public JsonObject getNodeTypes() { - return nodeTypes; + public List getOutputs() { + return outputs; } - public void setNodeTypes(JsonObject nodeTypes) { - this.nodeTypes = nodeTypes; + public void setOutputs(List outputs) { + this.outputs = outputs; } - /** - * @return - */ - public List getNodeTypeList() { - return jsonObject2NodeTypes(nodeTypes); + public List getNodeTemplates() { + return nodeTemplates; } - private ArrayList jsonObject2NodeTypes(JsonObject nodeTypes) { - ArrayList nodeTypeList = new ArrayList(); - Iterator> iterator = nodeTypes.entrySet().iterator(); - while (iterator.hasNext()) { - NodeType type = new NodeType(); - Entry next = iterator.next(); - type.setType(next.getKey()); - type.setValue(new Gson().fromJson(next.getValue(), - NodeType.NodeTypeValue.class)); - nodeTypeList.add(type); - } - return nodeTypeList; + public void setNodeTemplates(List nodeTemplates) { + this.nodeTemplates = nodeTemplates; } - public JsonObject getCapabilityTypes() { - return capabilityTypes; + public SubstitutionMapping getSubstitutionMappings() { + return substitutionMappings; } - public void setCapabilityTypes(JsonObject capabilityTypes) { - this.capabilityTypes = capabilityTypes; + public void setSubstitutionMappings(SubstitutionMapping substitutionMappings) { + this.substitutionMappings = substitutionMappings; } - public JsonObject getRelationshipTypes() { - return relationshipTypes; + public class Input { + private String name; + private String type; + private String description; + private String defaultValue; + private boolean required; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getDefault() { + return defaultValue; + } + + public void setDefault(String defaultValue) { + this.defaultValue = defaultValue; + } + + public boolean isRequired() { + return required; + } + + public void setRequired(boolean required) { + this.required = required; + } } - public void setRelationshipTypes(JsonObject relationshipTypes) { - this.relationshipTypes = relationshipTypes; + public class Output { + private String name; + private String description; + private Object value; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } } - public List getRelationshipTypeList() { - return jsonObject2RelationshipTypes(relationshipTypes); + public class NodeTemplate { + private String name; + private String nodeType; + private JsonObject properties; + private JsonObject[] requirements; + private JsonObject capabilities; + private List relationships; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getNodeType() { + return nodeType; + } + + public void setNodeType(String nodeType) { + this.nodeType = nodeType; + } + + public JsonObject getProperties() { + return properties; + } + + public void setProperties(JsonObject properties) { + this.properties = properties; + } + + public Map getPropertyList() { + return jsonObject2Properties(properties); + } + + private Map jsonObject2Properties(JsonObject properties) { + Map ret = new HashMap<>(); + Iterator> iterator = properties.entrySet().iterator(); + while (iterator.hasNext()) { + Entry next = iterator.next(); + ret.put(next.getKey(), next.getValue().getAsString()); + } + return ret; + } + + public JsonObject[] getRequirements() { + return requirements; + } + + public void setRequirements(JsonObject[] requirements) { + this.requirements = requirements; + } + + public JsonObject getCapabilities() { + return capabilities; + } + + public void setCapabilities(JsonObject capabilities) { + this.capabilities = capabilities; + } + + public List getRelationships() { + return relationships; + } + + public void setRelationships(List relationships) { + this.relationships = relationships; + } + + /** + * get scalable. + * @return NodeTemplateScalable + */ + public NodeTemplateScalable getScalable() { + if (capabilities == null) { + return null; + } + JsonElement scaleableJson = capabilities.get("scalable"); + if (scaleableJson == null || !scaleableJson.isJsonObject()) { + return null; + } + JsonElement propertyJson = scaleableJson.getAsJsonObject().get("properties"); + if (propertyJson == null || !propertyJson.isJsonObject()) { + return null; + } + + NodeTemplateScalable scalable = new NodeTemplateScalable(); + scalable + .setMin_instances(propertyJson.getAsJsonObject().get("min_instances").getAsString()); + scalable + .setMax_instances(propertyJson.getAsJsonObject().get("max_instances").getAsString()); + scalable.setDefault_instances( + propertyJson.getAsJsonObject().get("default_instances").getAsString()); + return scalable; + } + + public class Relationship { + private String targetNodeName; + private String type; + private String sourceNodeName; + + public String getTargetNodeName() { + return targetNodeName; + } + + public void setTargetNodeName(String targetNodeName) { + this.targetNodeName = targetNodeName; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getSourceNodeName() { + return sourceNodeName; + } + + public void setSourceNodeName(String sourceNodeName) { + this.sourceNodeName = sourceNodeName; + } + } + + public class NodeTemplateScalable { + private String minInstances; + private String maxInstances; + private String defaultInstances; + + public String getMin_instances() { + return minInstances; + } + + public void setMin_instances(String minInstances) { + this.minInstances = minInstances; + } + + public String getMax_instances() { + return maxInstances; + } + + public void setMax_instances(String maxInstances) { + this.maxInstances = maxInstances; + } + + public String getDefault_instances() { + return defaultInstances; + } + + public void setDefault_instances(String defaultInstances) { + this.defaultInstances = defaultInstances; + } + } } - /** - * @param relationshipTypes - * @return - */ - private ArrayList jsonObject2RelationshipTypes(JsonObject relationshipTypes) { - ArrayList relationshipTypeList = new ArrayList(); - Iterator> iterator = relationshipTypes.entrySet().iterator(); + public class SubstitutionMapping { + private String nodeType; + private JsonObject requirements; + private JsonObject capabilities; + private JsonObject properties; + + public String getNodeType() { + return nodeType; + } + + public void setNodeType(String nodeType) { + this.nodeType = nodeType; + } + + public JsonObject getRequirements() { + return requirements; + } + + public void setRequirements(JsonObject requirements) { + this.requirements = requirements; + } + + public Map getRequirementList() { + return jsonObjects2Requirements(this.requirements); + } + + private Map jsonObjects2Requirements(JsonObject requirements) { + Map ret = new HashMap(); + + Iterator> iterator = requirements.entrySet().iterator(); + while (iterator.hasNext()) { + Entry next = iterator.next(); + if (next.getValue().isJsonPrimitive() || next.getValue().isJsonObject()) { + ret.put(next.getKey(), new String[] {next.getValue().getAsString()}); + continue; + } + + if (next.getValue().isJsonArray()) { + String[] value = parseListValue((JsonArray) next.getValue()); + ret.put(next.getKey(), value); + } + } + + return ret; + } + + private String[] parseListValue(JsonArray jsonArray) { + String[] value = new String[jsonArray.size()]; + for (int i = 0, size = jsonArray.size(); i < size; i++) { + value[i] = jsonArray.get(i).getAsString(); + } + return value; + } + + public JsonObject getCapabilities() { + return capabilities; + } + + public void setCapabilities(JsonObject capabilities) { + this.capabilities = capabilities; + } + + public Map getCapabilityList() { + return jsonObject2Capabilities(this.capabilities); + } + + private Map jsonObject2Capabilities(JsonObject capabilities) { + Map ret = new HashMap(); + + Iterator> iterator = capabilities.entrySet().iterator(); while (iterator.hasNext()) { - RelationshipType type = new RelationshipType(); - Entry next = iterator.next(); - type.setType(next.getKey()); - type.setValue(new Gson().fromJson(next.getValue(), - RelationshipType.RelationshipValue.class)); - relationshipTypeList.add(type); + Entry next = iterator.next(); + + if (next.getValue().isJsonPrimitive() || next.getValue().isJsonObject()) { + ret.put(next.getKey(), new String[] {next.getValue().getAsString()}); + continue; + } + + if (next.getValue().isJsonArray()) { + String[] value = parseListValue((JsonArray) next.getValue()); + ret.put(next.getKey(), value); + } + } + + return ret; + } + + public JsonObject getProperties() { + return properties; + } + + public void setProperties(JsonObject properties) { + this.properties = properties; + } + + public Map getPropertyList() { + return jsonObject2Properties(properties); + } + + private Map jsonObject2Properties(JsonObject properties) { + Map ret = new HashMap<>(); + Iterator> iterator = properties.entrySet().iterator(); + while (iterator.hasNext()) { + Entry next = iterator.next(); + ret.put(next.getKey(), next.getValue().getAsString()); } - return relationshipTypeList; + return ret; + } } - - public JsonObject getPolicyTypes() { - return policyTypes; + } + + + public class RelationshipType { + private String type; + private RelationshipValue value; + + public String getType() { + return type; } - public void setPolicyTypes(JsonObject policyTypes) { - this.policyTypes = policyTypes; + public void setType(String type) { + this.type = type; } - public TopologyTemplate getTopologyTemplate() { - return topologyTemplate; + public RelationshipValue getValue() { + return value; } - public void setTopologyTemplate(TopologyTemplate topologyTemplate) { - this.topologyTemplate = topologyTemplate; + public void setValue(RelationshipValue value) { + this.value = value; } - public Map getMetadata() { - return metadata; + public class RelationshipValue { + private String derivedFrom; + private String[] validTargetTypes; + + public String getDerivedFrom() { + return derivedFrom; + } + + public void setDerivedFrom(String derivedFrom) { + this.derivedFrom = derivedFrom; + } + + public String[] getValid_target_types() { + return validTargetTypes; + } + + public void setValid_target_types(String[] validTargetTypes) { + this.validTargetTypes = validTargetTypes; + } } + } + + + public class NodeType { + private String type; + private NodeTypeValue value; - public void setMetadata(Map metadata) { - this.metadata = metadata; + public String getType() { + return type; } - public JsonObject getPlans() { - return plans; + public void setType(String type) { + this.type = type; } - public void setPlans(JsonObject plans) { - this.plans = plans; + public NodeTypeValue getValue() { + return value; } - public List getPlanList() { - return jsonObject2PlanList(this.plans); + public void setValue(NodeTypeValue value) { + this.value = value; } - /** - * @param plans - * @return - */ - private List jsonObject2PlanList(JsonObject plans) { - List retList = new ArrayList(); - Iterator> iterator = plans.entrySet() - .iterator(); + public class NodeTypeValue { + private String derivedFrom; + private JsonObject properties; + private JsonObject[] requirements; + private JsonObject capabilities; + + public String getDerivedFrom() { + return derivedFrom; + } + + public void setDerived_from(String derivedFrom) { + this.derivedFrom = derivedFrom; + } + + public JsonObject getProperties() { + return properties; + } + + public void setProperties(JsonObject properties) { + this.properties = properties; + } + + public List getPropertyList() { + return jsonObject2Properties(properties); + } + + private List jsonObject2Properties(JsonObject properties) { + List propertieList = new ArrayList(); + Iterator> iterator = properties.entrySet().iterator(); while (iterator.hasNext()) { - Plan ret = new Plan(); - Entry next = iterator.next(); - ret.setName(next.getKey()); - ret.setValue(new Gson().fromJson(next.getValue(), - Plan.PlanValue.class)); - retList.add(ret); + NodeTypeProperty type = new NodeTypeProperty(); + Entry next = iterator.next(); + type.setKey(next.getKey()); + type.setValue(new Gson().fromJson(next.getValue(), JsonObject.class)); + propertieList.add(type); } - return retList; - } + return propertieList; + } - public class TopologyTemplate{ - private String description; - private List inputs; - private List nodeTemplates; - private SubstitutionMapping substitutionMappings; - - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; + public class NodeTypeProperty { + private String key; + private JsonObject value; + + public String getKey() { + return key; } - public List getInputs() { - return inputs; - } - public void setInputs(List inputs) { - this.inputs = inputs; - } - public List getNodeTemplates() { - return nodeTemplates; - } - public void setNodeTemplates(List nodeTemplates) { - this.nodeTemplates = nodeTemplates; - } - public SubstitutionMapping getSubstitutionMappings() { - return substitutionMappings; - } - public void setSubstitutionMappings(SubstitutionMapping substitutionMappings) { - this.substitutionMappings = substitutionMappings; - } - - public class Input{ - private String name; - private String type; - private String description; - private String defaultValue; - private boolean required; - - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; - } - public String getDefault() { - return defaultValue; - } - public void setDefault(String defaultValue) { - this.defaultValue = defaultValue; - } - public boolean isRequired() { - return required; - } - public void setRequired(boolean required) { - this.required = required; - } - } - - public class NodeTemplate{ - private String name; - private String nodeType; - private JsonObject properties; - private JsonObject[] requirements; - private JsonObject capabilities; - private List relationships; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getNodeType() { - return nodeType; - } - - public void setNodeType(String nodeType) { - this.nodeType = nodeType; - } - - public JsonObject getProperties() { - return properties; - } - - public void setProperties(JsonObject properties) { - this.properties = properties; - } - - public Map getPropertyList() { - return jsonObject2Properties(properties); - } - - private Map jsonObject2Properties( - JsonObject properties) { - Map ret = new HashMap<>(); - Iterator> iterator = properties - .entrySet().iterator(); - while (iterator.hasNext()) { - Entry next = iterator.next(); - ret.put(next.getKey(), next.getValue().getAsString()); - } - return ret; - } - - public JsonObject[] getRequirements() { - return requirements; - } - - public void setRequirements(JsonObject[] requirements) { - this.requirements = requirements; - } - - public JsonObject getCapabilities() { - return capabilities; - } - - public void setCapabilities(JsonObject capabilities) { - this.capabilities = capabilities; - } - - public List getRelationships() { - return relationships; - } - - public void setRelationships(List relationships) { - this.relationships = relationships; - } - - public NodeTemplateScalable getScalable() { - if(capabilities == null){ - return null; - } - JsonElement scaleableJson = capabilities.get("scalable"); - if (scaleableJson == null || !scaleableJson.isJsonObject()) { - return null; - } - JsonElement propertyJson = scaleableJson.getAsJsonObject().get("properties"); - if (propertyJson == null || !propertyJson.isJsonObject()) { - return null; - } - - NodeTemplateScalable scalable = new NodeTemplateScalable(); - scalable.setMin_instances(propertyJson.getAsJsonObject().get("min_instances") - .getAsString()); - scalable.setMax_instances(propertyJson.getAsJsonObject().get("max_instances") - .getAsString()); - scalable.setDefault_instances(propertyJson.getAsJsonObject() - .get("default_instances").getAsString()); - return scalable; - } - - public class Relationship{ - private String targetNodeName; - private String type; - private String sourceNodeName; - - public String getTargetNodeName() { - return targetNodeName; - } - public void setTargetNodeName(String targetNodeName) { - this.targetNodeName = targetNodeName; - } - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - public String getSourceNodeName() { - return sourceNodeName; - } - public void setSourceNodeName(String sourceNodeName) { - this.sourceNodeName = sourceNodeName; - } - } - - public class NodeTemplateScalable{ - private String min_instances; - private String max_instances; - private String default_instances; - public String getMin_instances() { - return min_instances; - } - public void setMin_instances(String min_instances) { - this.min_instances = min_instances; - } - public String getMax_instances() { - return max_instances; - } - public void setMax_instances(String max_instances) { - this.max_instances = max_instances; - } - public String getDefault_instances() { - return default_instances; - } - public void setDefault_instances(String default_instances) { - this.default_instances = default_instances; - } - } - } - - public class SubstitutionMapping{ - private String node_type; - private JsonObject[] requirements; - private JsonObject capabilities; - private JsonObject properties; - - public String getNode_type() { - return node_type; - } - - public void setNode_type(String node_type) { - this.node_type = node_type; - } - - public JsonObject[] getRequirements() { - return requirements; - } - - public void setRequirements(JsonObject[] requirements) { - this.requirements = requirements; - } - - public List> getRequirementList() { - return jsonObjects2Requirements(this.requirements); - } - - private List> jsonObjects2Requirements( - JsonObject[] requirements) { - List> retList = new ArrayList<>(); - for (JsonObject requirement : requirements) { - Iterator> iterator = requirement - .entrySet().iterator(); - while (iterator.hasNext()) { - Entry next = iterator.next(); - Map ret = new HashMap(); - if (next.getValue().isJsonPrimitive() - || next.getValue().isJsonObject()) { - ret.put(next.getKey(), new String[] { next - .getValue().getAsString() }); - retList.add(ret); - continue; - } - - if (next.getValue().isJsonArray()) { - String[] value = parseListValue((JsonArray) next.getValue()); - ret.put(next.getKey(), value); - retList.add(ret); - } - } - } - - return retList; - } - - private String[] parseListValue(JsonArray jsonArray) { - String[] value = new String[jsonArray.size()]; - for (int i = 0, size = jsonArray.size(); i < size; i++) { - value[i] = jsonArray.get(i).getAsString(); - } - return value; - } - - public JsonObject getCapabilities() { - return capabilities; - } - - public void setCapabilities(JsonObject capabilities) { - this.capabilities = capabilities; - } - - public Map getCapabilityList() { - return jsonObject2Capabilities(this.capabilities); - } - - private Map jsonObject2Capabilities( - JsonObject capabilities) { - Map ret = new HashMap(); - - Iterator> iterator = capabilities - .entrySet().iterator(); - while (iterator.hasNext()) { - Entry next = iterator.next(); - - if (next.getValue().isJsonPrimitive() - || next.getValue().isJsonObject()) { - ret.put(next.getKey(), new String[] { next.getValue() - .getAsString() }); - continue; - } - - if (next.getValue().isJsonArray()) { - String[] value = parseListValue((JsonArray) next - .getValue()); - ret.put(next.getKey(), value); - } - } - - return ret; - } - - public JsonObject getProperties() { - return properties; - } - - public void setProperties(JsonObject properties) { - this.properties = properties; - } - - public Map getPropertyList() { - return jsonObject2Properties(properties); - } - - private Map jsonObject2Properties( - JsonObject properties) { - Map ret = new HashMap<>(); - Iterator> iterator = properties.entrySet().iterator(); - while (iterator.hasNext()) { - Entry next = iterator.next(); - ret.put(next.getKey(), next.getValue().getAsString()); - } - return ret; - } - } - } - - - public class RelationshipType{ - private String type; - private RelationshipValue value; - - public String getType() { - return type; + + public void setKey(String key) { + this.key = key; } - public void setType(String type) { - this.type = type; + /** + * get default value. + * @return default value + */ + public String getDefaultValue() { + JsonElement defaultValue = value.get("default"); + if (defaultValue == null || defaultValue.isJsonObject()) { + return ""; + } + + return defaultValue.getAsString(); } - public RelationshipValue getValue() { - return value; + public JsonObject getValue() { + return value; } - public void setValue(RelationshipValue value) { - this.value = value; + public void setValue(JsonObject value) { + this.value = value; } + } - public class RelationshipValue{ - private String derived_from; - private String[] valid_target_types; + public JsonObject[] getRequirements() { + return requirements; + } - public String getDerived_from() { - return derived_from; - } + public void setRequirements(JsonObject[] requirements) { + this.requirements = requirements; + } - public void setDerived_from(String derived_from) { - this.derived_from = derived_from; - } - public String[] getValid_target_types() { - return valid_target_types; - } - public void setValid_target_types(String[] valid_target_types) { - this.valid_target_types = valid_target_types; - } - } + public JsonObject getCapabilities() { + return capabilities; + } + + public void setCapabilities(JsonObject capabilities) { + this.capabilities = capabilities; + } } + } + public class Plan { + private String name; + private PlanValue value; - public class NodeType { - private String type; - private NodeTypeValue value; - - public String getType() { - return type; - } + public String getName() { + return name; + } - public void setType(String type) { - this.type = type; + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return value.getDescription(); + } + + public String getReference() { + return value.getReference(); + } + + public String getPlanLanguage() { + return value.getPlanLanguage(); + } + + public List getInputList() { + return value.getInputList(); + } + + public PlanValue getValue() { + return value; + } + + public void setValue(PlanValue value) { + this.value = value; + } + + public class PlanValue { + private String description; + private String reference; + private String planLanguage; + private JsonObject inputs; + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getReference() { + return reference; + } + + public void setReference(String reference) { + this.reference = reference; + } + + public String getPlanLanguage() { + return planLanguage; + } + + public void setPlanLanguage(String planLanguage) { + this.planLanguage = planLanguage; + } + + public JsonObject getInputs() { + return inputs; + } + + public void setInputs(JsonObject inputs) { + this.inputs = inputs; + } + + public List getInputList() { + return jsonObject2PlanInputList(inputs); + + } + + private List jsonObject2PlanInputList(JsonObject inputs) { + List retList = new ArrayList(); + Iterator> iterator = inputs.entrySet().iterator(); + while (iterator.hasNext()) { + PlanInput ret = new PlanInput(); + Entry next = iterator.next(); + ret.setName(next.getKey()); + ret.setValue(new Gson().fromJson(next.getValue(), PlanInput.PlanInputValue.class)); + retList.add(ret); } + return retList; + } - public NodeTypeValue getValue() { - return value; - } - - public void setValue(NodeTypeValue value) { - this.value = value; - } - - public class NodeTypeValue{ - private String derived_from; - private JsonObject properties; - private JsonObject[] requirements; - private JsonObject capabilities; - - public String getDerived_from() { - return derived_from; - } - - public void setDerived_from(String derived_from) { - this.derived_from = derived_from; - } - - public JsonObject getProperties() { - return properties; - } - - public void setProperties(JsonObject properties) { - this.properties = properties; - } - - public List getPropertyList() { - return jsonObject2Properties(properties); - } - - private List jsonObject2Properties(JsonObject properties) { - List propertieList = new ArrayList(); - Iterator> iterator = properties.entrySet().iterator(); - while (iterator.hasNext()) { - NodeTypeProperty type = new NodeTypeProperty(); - Entry next = iterator.next(); - type.setKey(next.getKey()); - type.setValue(new Gson().fromJson(next.getValue(), - JsonObject.class)); - propertieList.add(type); - } - return propertieList; - } - - /** - * - */ - public class NodeTypeProperty { - private String key; - private JsonObject value; - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public String getDefaultValue() { - JsonElement defaultValue = value.get("default"); - if (defaultValue == null || defaultValue.isJsonObject()) { - return ""; - } - - return defaultValue.getAsString(); - } - - public JsonObject getValue() { - return value; - } - - public void setValue(JsonObject value) { - this.value = value; - } - } - - public JsonObject[] getRequirements() { - return requirements; - } - - public void setRequirements(JsonObject[] requirements) { - this.requirements = requirements; - } - - public JsonObject getCapabilities() { - return capabilities; - } - - public void setCapabilities(JsonObject capabilities) { - this.capabilities = capabilities; - } - } - } - - public class Plan { + public class PlanInput { private String name; - private PlanValue value; + private PlanInputValue value; public String getName() { - return name; + return name; } + public void setName(String name) { - this.name = name; + this.name = name; + } + + public String getType() { + return value.getType(); } public String getDescription() { - return value.getDescription(); + return value.getDescription(); } - public String getReference() { - return value.getReference(); - } - public String getPlanLanguage() { - return value.getPlanLanguage(); + + public String getDefault() { + return value.getDefaultValue(); } - public List getInputList() { - return value.getInputList(); - } + public boolean isRequired() { + return value.isRequired(); + } - public PlanValue getValue() { - return value; - } - public void setValue(PlanValue value) { - this.value = value; + public PlanInputValue getValue() { + return value; } - public class PlanValue { - private String description; - private String reference; - private String planLanguage; - private JsonObject inputs; - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getReference() { - return reference; - } - - public void setReference(String reference) { - this.reference = reference; - } - - public String getPlanLanguage() { - return planLanguage; - } - - public void setPlanLanguage(String planLanguage) { - this.planLanguage = planLanguage; - } - - public JsonObject getInputs() { - return inputs; - } - - public void setInputs(JsonObject inputs) { - this.inputs = inputs; - } - - public List getInputList() { - return jsonObject2PlanInputList(inputs); + public void setValue(PlanInputValue value) { + this.value = value; + } - } + public class PlanInputValue { + private String type; + private String description; + @SerializedName("default") + private String defaultValue; + private boolean required; - /** - * @param inputs - * @return - */ - private List jsonObject2PlanInputList(JsonObject inputs) { - List retList = new ArrayList(); - Iterator> iterator = inputs - .entrySet().iterator(); - while (iterator.hasNext()) { - PlanInput ret = new PlanInput(); - Entry next = iterator.next(); - ret.setName(next.getKey()); - ret.setValue(new Gson().fromJson(next.getValue(), - PlanInput.PlanInputValue.class)); - retList.add(ret); - } - return retList; - } + public String getType() { + return type; + } - public class PlanInput { - private String name; - private PlanInputValue value; + public void setType(String type) { + this.type = type; + } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } - public String getType() { - return value.getType(); - } + public String getDefaultValue() { + return defaultValue; + } - public String getDescription() { - return value.getDescription(); - } + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } - public String getDefault() { - return value.getDefault(); - } + public boolean isRequired() { + return required; + } - public boolean isRequired() { - return value.isRequired(); - } - - public PlanInputValue getValue() { - return value; - } - - public void setValue(PlanInputValue value) { - this.value = value; - } - - public class PlanInputValue { - private String type; - private String description; - private String defaultValue; - private boolean required; - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getDefault() { - return defaultValue; - } - - public void setDefault(String defaultValue) { - this.defaultValue = defaultValue; - } - - public boolean isRequired() { - return required; - } - - public void setRequired(boolean required) { - this.required = required; - } - } - } + public void setRequired(boolean required) { + this.required = required; + } } + } } + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/IWSO2RestService.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/IWSO2RestService.java deleted file mode 100644 index 9f1706a3..00000000 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/IWSO2RestService.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright 2016 [ZTE] and others. - * - * Licensed 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.openo.commontosca.catalog.model.plan.wso2; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; - -import org.glassfish.jersey.media.multipart.FormDataMultiPart; -import org.openo.commontosca.catalog.model.plan.wso2.entity.DeletePackageResponse; -import org.openo.commontosca.catalog.model.plan.wso2.entity.DeployPackageResponse; -import org.openo.commontosca.catalog.model.plan.wso2.entity.StartProcessResponse; -import org.openo.commontosca.catalog.model.plan.wso2.entity.StartProcessRequest; - -/** - * - * @author 10090474 - * - */ -@Path("/openoapi/wso2bpel/v1") -public interface IWSO2RestService { - /** - * @param request - * @return - * @throws Exception - */ - @Path("/package") - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - DeployPackageResponse deployPackage(FormDataMultiPart request) throws Exception; - - @Path("/package/{packageName}") - @DELETE - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - DeletePackageResponse deletePackage( - @PathParam("packageName") String packageName) throws Exception; - - @Path("process/instance") - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - StartProcessResponse startProcess(StartProcessRequest request) - throws Exception; -} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/Iwso2RestService.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/Iwso2RestService.java new file mode 100644 index 00000000..6600c06f --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/Iwso2RestService.java @@ -0,0 +1,57 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.model.plan.wso2; + +import org.openo.commontosca.catalog.model.plan.wso2.entity.DeletePackageResponse; +import org.openo.commontosca.catalog.model.plan.wso2.entity.StartProcessRequest; +import org.openo.commontosca.catalog.model.plan.wso2.entity.StartProcessResponse; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +@Path("/openoapi/wso2bpel/v1") +public interface Iwso2RestService { + // /** + // * @param request + // * @return + // * @throws Exception + // */ + // @Path("/package") + // @POST + // @Consumes(MediaType.APPLICATION_JSON) + // @Produces(MediaType.APPLICATION_JSON) + // DeployPackageResponse deployPackage(FormDataMultiPart request) throws Exception; + + @Path("/package/{packageName}") + @DELETE + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + DeletePackageResponse deletePackage( + @PathParam("packageName") String packageName) throws Exception; + + @Path("process/instance") + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + StartProcessResponse startProcess(StartProcessRequest request) + throws Exception; +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/RestResponse.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/RestResponse.java new file mode 100644 index 00000000..0af4a14f --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/RestResponse.java @@ -0,0 +1,34 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.model.plan.wso2; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@JsonIgnoreProperties(ignoreUnknown = true) +public class RestResponse { + + private Integer statusCode; + + private String result; +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/RestfulClient.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/RestfulClient.java new file mode 100644 index 00000000..5fe1f486 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/RestfulClient.java @@ -0,0 +1,117 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.model.plan.wso2; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpHost; +import org.apache.http.HttpRequest; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; + +public class RestfulClient { + private static final String HTTP = "http"; + private static final Logger logger = LoggerFactory.getLogger(RestfulClient.class); + + enum HttpMethod { + GET, POST, PUT, DELETE + } + + /** + * execute http. + * @param method http method + * @param ip ip + * @param port port + * @param url url + * @param body http body + * @return RestResponse + */ + public static RestResponse executeHttp(HttpMethod method, String ip, int port, String url, + HttpEntity body) { + CloseableHttpClient httpclient = HttpClients.createDefault(); + HttpResponse httpResponse = null; + RestResponse result = new RestResponse(); + try { + // specify the host, protocol, and port + HttpHost target = new HttpHost(ip, port, HTTP); + // specify the get request + HttpRequest request = getRequest(method, url, body); + httpResponse = httpclient.execute(target, request); + HttpEntity entity = httpResponse.getEntity(); + if (entity != null) { + result.setStatusCode(httpResponse.getStatusLine().getStatusCode()); + result.setResult(EntityUtils.toString(entity)); + } + } catch (Exception e1) { + logger.error("send get rest request error:", e1.getMessage()); + } finally { + if (httpclient != null) { + try { + httpclient.close(); + } catch (IOException e2) { + logger.error("close httpclient error:", e2.getMessage()); + } + } + } + return result; + } + + private static HttpRequest getRequest(HttpMethod method, String url, HttpEntity body) { + HttpRequest request = null; + switch (method) { + case GET: + request = new HttpGet(url); + break; + case POST: + request = new HttpPost(url); + ((HttpPost) request).setEntity(body); + break; + case PUT: + request = new HttpPut(url); + ((HttpPut) request).setEntity(body); + break; + case DELETE: + request = new HttpDelete(url); + break; + default: + break; + } + return request; + } + + public static String get(String ip, int port, String url) { + return executeHttp(HttpMethod.GET, ip, port, url, null).getResult(); + } + + public static RestResponse delete(String ip, int port, String url) { + return executeHttp(HttpMethod.GET, ip, port, url, null); + } + + public static RestResponse post(String ip, int port, String url, HttpEntity requestBody) { + return executeHttp(HttpMethod.POST, ip, port, url, requestBody); + } + +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/WSO2ServiceConsumer.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/WSO2ServiceConsumer.java deleted file mode 100644 index 114e9d21..00000000 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/WSO2ServiceConsumer.java +++ /dev/null @@ -1,123 +0,0 @@ -/** - * Copyright 2016 [ZTE] and others. - * - * Licensed 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.openo.commontosca.catalog.model.plan.wso2; - -import java.util.Map; - -import org.glassfish.jersey.client.ClientConfig; -import org.openo.commontosca.catalog.db.exception.CatalogResourceException; -import org.openo.commontosca.catalog.model.plan.wso2.entity.DeletePackageResponse; -import org.openo.commontosca.catalog.model.plan.wso2.entity.StartProcessResponse; -import org.openo.commontosca.catalog.model.plan.wso2.entity.DeployPackageResponse; -import org.openo.commontosca.catalog.model.plan.wso2.entity.StartProcessRequest; - -import com.eclipsesource.jaxrs.consumer.ConsumerFactory; - -/** - * - * @author 10090474 - * - */ -public class WSO2ServiceConsumer { - public static final String WSO2_BASE_URL = "http://localhost:9449/"; - - /** - * - * @param filePath - * @return - * @throws CatalogResourceException - */ - public static DeployPackageResponse deployPackage(String filePath) - throws CatalogResourceException { - - // final FormDataMultiPart formData = new FormDataMultiPart(); - // final BodyPart bodyPart = new FormDataBodyPart(fileDetail, - // uploadedInputStream, MediaType.APPLICATION_OCTET_STREAM_TYPE); - // formData.bodyPart(bodyPart); - // formData.setContentDisposition(fileDetail); - // formData.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE); - // final Client client = ClientBuilder.newBuilder() - // .register(MultiPartFeature.class).build(); - // final WebTarget target = client.target(getPackageURL()).path( - // "/containerapi/CSARs"); - // final Response response = target.request().post( - // Entity.entity(formData, formData.getMediaType())); - // return response; - - return null; - // try { - // ClientConfig config = new ClientConfig(); - // IWSO2RestService yamlParseProxy = ConsumerFactory - // .createConsumer(MSBUtil.getYamlParseBaseUrl(), config, - // IWSO2RestService.class); - // String jsonStr = yamlParseProxy.parse(request); - // return new Gson().fromJson(jsonStr, ParseYamlResult.class); - // } catch (Exception e) { - // throw new CatalogResourceException("Call parser api failed.", e); - // } - - } - - - /** - * @param packageName - * @return - * @throws CatalogResourceException - */ - DeletePackageResponse deletePackage(String packageName) - throws CatalogResourceException { - try { - ClientConfig config = new ClientConfig(); - IWSO2RestService wso2Proxy = ConsumerFactory.createConsumer( - WSO2_BASE_URL, config, IWSO2RestService.class); - DeletePackageResponse response = wso2Proxy - .deletePackage(packageName); - if (response.isSuccess()) { - return response; - } - throw new CatalogResourceException(response.getException()); - } catch (Exception e) { - throw new CatalogResourceException( - "Call Delete Package api failed.", e); - } - } - - - /** - * @param processId - * @param params - * @return - * @throws CatalogResourceException - */ - StartProcessResponse startProcess(String processId, - Map params) throws CatalogResourceException { - try { - ClientConfig config = new ClientConfig(); - IWSO2RestService wso2Proxy = ConsumerFactory.createConsumer( - WSO2_BASE_URL, config, IWSO2RestService.class); - StartProcessResponse response = wso2Proxy - .startProcess(new StartProcessRequest(processId, params)); - if (response.isSuccess()) { - return response; - } - throw new CatalogResourceException(response.getException()); - } catch (Exception e) { - throw new CatalogResourceException( - "Call Start Process api failed.", e); - } - } - -} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/Wso2ServiceConsumer.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/Wso2ServiceConsumer.java new file mode 100644 index 00000000..da52dcd7 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/Wso2ServiceConsumer.java @@ -0,0 +1,185 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.model.plan.wso2; + +import com.google.gson.Gson; + +import com.eclipsesource.jaxrs.consumer.ConsumerFactory; + +import org.apache.http.HttpEntity; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.glassfish.jersey.client.ClientConfig; +import org.openo.commontosca.catalog.common.Config; +import org.openo.commontosca.catalog.db.exception.CatalogResourceException; +import org.openo.commontosca.catalog.model.plan.wso2.entity.DeletePackageResponse; +import org.openo.commontosca.catalog.model.plan.wso2.entity.DeployPackageResponse; +import org.openo.commontosca.catalog.model.plan.wso2.entity.StartProcessRequest; +import org.openo.commontosca.catalog.model.plan.wso2.entity.StartProcessResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipInputStream; + + + +public class Wso2ServiceConsumer { + public static final String WSO2_APP_URL = "/openoapi/wso2bpel/v1/package"; + private static final Logger LOGGER = LoggerFactory.getLogger(Wso2ServiceConsumer.class); + + /** + * deploy package. + * @param zipFileLocation zip file location + * @param planFilePath plan file path + * @return DeployPackageResponse + * @throws CatalogResourceException e1 + */ + public static DeployPackageResponse deployPackage(String zipFileLocation, String planFilePath) + throws CatalogResourceException { + InputStream ins = null; + try { + ins = getInputStream(zipFileLocation, planFilePath); + RestResponse res = RestfulClient.post(Config.getConfigration().getWso2HostIp(), + Integer.parseInt(Config.getConfigration().getWso2HostPort()), WSO2_APP_URL, + buildRequest(ins, planFilePath)); + + if (200 == res.getStatusCode() || 201 == res.getStatusCode()) { + DeployPackageResponse response = + new Gson().fromJson(res.getResult(), DeployPackageResponse.class); + if (response.isSuccess()) { + return response; + } + } + + throw new CatalogResourceException( + "Deploy Package return fail. Response = " + res.getResult()); + } catch (FileNotFoundException e1) { + throw new CatalogResourceException("Deploy Package failed.", e1); + } finally { + if (ins != null) { + try { + ins.close(); + } catch (IOException e1) { + LOGGER.error("inputStream close failed !"); + } + } + } + } + + private static HttpEntity buildRequest(InputStream inputStream, String filePath) + throws FileNotFoundException { + MultipartEntityBuilder builder = MultipartEntityBuilder.create(); + builder.seContentType(ContentType.MULTIPART_FORM_DATA); + builder.addBinaryBody("file", inputStream, ContentType.APPLICATION_OCTET_STREAM, + new File(filePath).getName()); + return builder.build(); + } + + @SuppressWarnings("resource") + private static InputStream getInputStream(String zipFileLocation, String planFilePath) + throws CatalogResourceException { + ZipInputStream zin = null; + try { + InputStream in = new BufferedInputStream(new FileInputStream(zipFileLocation)); + zin = new ZipInputStream(in); + ZipEntry ze; + while ((ze = zin.getNextEntry()) != null) { + if (planFilePath.equals(ze.getName())) { + ZipFile zf = new ZipFile(zipFileLocation); + return zf.getInputStream(ze); + } + } + } catch (IOException e1) { + throw new CatalogResourceException("Get InputStream failed. planFilePath = " + planFilePath, + e1); + } finally { + closeStream(zin); + } + + throw new CatalogResourceException("Get InputStream failed. planFilePath = " + planFilePath); + } + + private static void closeStream(ZipInputStream zin) { + + if (zin != null) { + try { + zin.closeEntry(); + } catch (IOException e1) { + LOGGER.error("zip inputStream close failed !"); + } + } + } + + /** + * delet package. + * @param packageName package to delete according packageName + * @return DeletePackageResponse + * @throws CatalogResourceException e1 + */ + public static DeletePackageResponse deletePackage(String packageName) + throws CatalogResourceException { + try { + ClientConfig config = new ClientConfig(); + Iwso2RestService wso2Proxy = ConsumerFactory.createConsumer( + Config.getConfigration().getWso2BaseUrl(), config, Iwso2RestService.class); + DeletePackageResponse response = wso2Proxy.deletePackage(packageName); + if (response.isSuccess()) { + return response; + } + throw new CatalogResourceException(response.getException()); + } catch (Exception e1) { + throw new CatalogResourceException( + "Call Delete Package api failed. packageName = " + packageName, e1); + } + } + + + /** + * start process. + * @param processId process id + * @param params params + * @return StartProcessResponse + * @throws CatalogResourceException e1 + */ + public static StartProcessResponse startProcess(String processId, Map params) + throws CatalogResourceException { + try { + ClientConfig config = new ClientConfig(); + Iwso2RestService wso2Proxy = ConsumerFactory.createConsumer( + Config.getConfigration().getWso2BaseUrl(), config, Iwso2RestService.class); + StartProcessResponse response = + wso2Proxy.startProcess(new StartProcessRequest(processId, params)); + if (response.isSuccess()) { + return response; + } + throw new CatalogResourceException(response.getException()); + } catch (Exception e1) { + throw new CatalogResourceException("Call Start Process api failed.", e1); + } + } + +} + diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/entity/DeletePackageResponse.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/entity/DeletePackageResponse.java index b905ee61..8aac6122 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/entity/DeletePackageResponse.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/entity/DeletePackageResponse.java @@ -13,30 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.plan.wso2.entity; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -/** - * @author 10090474 - * - */ @Data @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class DeletePackageResponse { - private static final int STATUS_SUCCESS = 1; + private static final int STATUS_SUCCESS = 1; - private int status; - private String message; - private String exception; + private int status; + private String message; + private String exception; - public boolean isSuccess() { - return this.status == STATUS_SUCCESS; - } + public boolean isSuccess() { + return this.status == STATUS_SUCCESS; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/entity/DeployPackageResponse.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/entity/DeployPackageResponse.java index 3e171445..3c81d724 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/entity/DeployPackageResponse.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/entity/DeployPackageResponse.java @@ -13,32 +13,30 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.plan.wso2.entity; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -/** - * @author 10090474 - * - */ @Data @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class DeployPackageResponse { - private static final int STATUS_SUCCESS = 1; + private static final int STATUS_SUCCESS = 1; - private int status; - private String message; - private String packageName; - private String processId; - private String exception; + private int status; + private String message; + private String packageName; + private String processId; + private String exception; - public boolean isSuccess() { - return this.status == STATUS_SUCCESS; - } + public boolean isSuccess() { + return this.status == STATUS_SUCCESS; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/entity/StartProcessRequest.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/entity/StartProcessRequest.java index da9aefb5..0801c445 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/entity/StartProcessRequest.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/entity/StartProcessRequest.java @@ -13,25 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.plan.wso2.entity; -import java.util.Map; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import java.util.Map; -/** - * @author 10090474 - * - */ @Data @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class StartProcessRequest { - private String processId; - private Map params; + private String processId; + private Map params; } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/entity/StartProcessResponse.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/entity/StartProcessResponse.java index 73c9fad2..3b648939 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/entity/StartProcessResponse.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/entity/StartProcessResponse.java @@ -13,31 +13,29 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.model.plan.wso2.entity; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -/** - * @author 10090474 - * - */ @Data @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class StartProcessResponse { - private static final int STATUS_SUCCESS = 1; + private static final int STATUS_SUCCESS = 1; - private int status; - private String message; - private String response; - private String exception; + private int status; + private String message; + private String response; + private String exception; - public boolean isSuccess() { - return this.status == STATUS_SUCCESS; - } + public boolean isSuccess() { + return this.status == STATUS_SUCCESS; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/service/ModelService.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/service/ModelService.java new file mode 100644 index 00000000..664f8ad7 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/service/ModelService.java @@ -0,0 +1,55 @@ +/** + * Copyright 2016 [ZTE] and others. + * + * Licensed 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.openo.commontosca.catalog.model.service; + +import org.openo.commontosca.catalog.db.exception.CatalogResourceException; +import org.openo.commontosca.catalog.db.resource.TemplateManager; +import org.openo.commontosca.catalog.model.entity.ServiceTemplate; +import org.openo.commontosca.catalog.model.entity.ServiceTemplateOperation; +import org.openo.commontosca.catalog.model.plan.wso2.Wso2ServiceConsumer; +import org.openo.commontosca.catalog.model.wrapper.ServiceTemplateWrapper; +import org.openo.commontosca.catalog.resources.CatalogBadRequestException; + +public class ModelService { + + private static final ModelService instance = new ModelService(); + + public static ModelService getInstance() { + return instance; + } + + /** + * delete service template according package id. + * @param packageId package id + * @throws CatalogBadRequestException e1 + * @throws CatalogResourceException e2 + */ + public void delete(String packageId) throws CatalogBadRequestException, CatalogResourceException { + ServiceTemplate st = ServiceTemplateWrapper.getInstance().getServiceTemplateByCsarId(packageId); + + TemplateManager.getInstance().deleteServiceTemplateById(st.getServiceTemplateId()); + TemplateManager.getInstance().deleteServiceTemplateMapping(null, st.getServiceTemplateId()); + + ServiceTemplateOperation[] operations = st.getOperations(); + if (operations != null && operations.length > 0) { + for (ServiceTemplateOperation op : operations) { + Wso2ServiceConsumer.deletePackage(op.getPackageName()); + } + } + } + +} diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/wrapper/ServiceTemplateWrapper.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/wrapper/ServiceTemplateWrapper.java index 039d64b4..448c6a86 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/wrapper/ServiceTemplateWrapper.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/wrapper/ServiceTemplateWrapper.java @@ -13,14 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.model.wrapper; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +package org.openo.commontosca.catalog.model.wrapper; -import org.openo.commontosca.catalog.model.entity.ServiceTemplateOperation; -import org.openo.commontosca.catalog.resources.CatalogBadRequestException; import org.openo.commontosca.catalog.common.ToolUtil; import org.openo.commontosca.catalog.db.entity.NodeTemplateData; import org.openo.commontosca.catalog.db.entity.PackageData; @@ -32,320 +27,336 @@ import org.openo.commontosca.catalog.model.common.TemplateDataHelper; import org.openo.commontosca.catalog.model.entity.InputParameter; import org.openo.commontosca.catalog.model.entity.NfvTemplate; import org.openo.commontosca.catalog.model.entity.NodeTemplate; +import org.openo.commontosca.catalog.model.entity.Parameters; import org.openo.commontosca.catalog.model.entity.QueryRawDataCondition; import org.openo.commontosca.catalog.model.entity.ServiceTemplate; +import org.openo.commontosca.catalog.model.entity.ServiceTemplateOperation; import org.openo.commontosca.catalog.model.entity.ServiceTemplateRawData; import org.openo.commontosca.catalog.model.entity.SubstitutionMapping; +import org.openo.commontosca.catalog.resources.CatalogBadRequestException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * - * @author 10090474 - * - */ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + + public class ServiceTemplateWrapper { - private static ServiceTemplateWrapper instance; - private static final Logger logger = LoggerFactory.getLogger(ServiceTemplateWrapper.class); - - public static ServiceTemplateWrapper getInstance() { - if (instance == null) { - instance = new ServiceTemplateWrapper(); - } - return instance; + private static ServiceTemplateWrapper instance; + private static final Logger logger = LoggerFactory.getLogger(ServiceTemplateWrapper.class); + + /** + * get service template wrapper instance. + * @return ServiceTemplateWrapper instance + */ + public static ServiceTemplateWrapper getInstance() { + if (instance == null) { + instance = new ServiceTemplateWrapper(); } - - /** - * - * @param serviceTemplateId - * @return - * @throws CatalogResourceException - */ - public ServiceTemplate getServiceTemplateById(String serviceTemplateId) - throws CatalogResourceException { - logger.info("getServiceTemplateById. serviceTemplateId = " - + serviceTemplateId); - - List stdList = TemplateManager.getInstance() - .queryServiceTemplateById(serviceTemplateId); - if (stdList == null || stdList.isEmpty()) { - throw new CatalogResourceException("Can't find this servcie template"); - } - - return TemplateDataHelper.convert2ServiceTemplate(stdList.get(0)); + return instance; + } + + /** + * get service template by id. + * @param serviceTemplateId service template id + * @return service template + * @throws CatalogResourceException e1 + */ + public ServiceTemplate getServiceTemplateById(String serviceTemplateId) + throws CatalogResourceException { + logger.info("getServiceTemplateById. serviceTemplateId = " + serviceTemplateId); + + List stdList = + TemplateManager.getInstance().queryServiceTemplateById(serviceTemplateId); + if (stdList == null || stdList.isEmpty()) { + throw new CatalogResourceException("Can't find this servcie template"); } - - /** - * - * @param status - * @param deletionPending - * @return - * @throws CatalogResourceException - */ - public ServiceTemplate[] getServiceTemplates(String status, - boolean deletionPending) throws CatalogResourceException { - PackageData pd = new PackageData(); - pd.setUsageState(status); - pd.setDeletionPending(String.valueOf(deletionPending)); - - List stdList = TemplateManager.getInstance() - .queryServiceTemplateByCsarPackageInfo(pd); - - return TemplateDataHelper.convert2ServiceTemplates(stdList); + return TemplateDataHelper.convert2ServiceTemplate(stdList.get(0)); + } + + + /** + * get service templates. + * @param status usage status + * @param deletionPending package's deletionPending + * @return service template list + * @throws CatalogResourceException e + */ + public ServiceTemplate[] getServiceTemplates(String status, boolean deletionPending) + throws CatalogResourceException { + PackageData pd = new PackageData(); + pd.setUsageState(status); + pd.setDeletionPending(String.valueOf(deletionPending)); + + List stdList = + TemplateManager.getInstance().queryServiceTemplateByCsarPackageInfo(pd); + + return TemplateDataHelper.convert2ServiceTemplates(stdList); + } + + + /** + * get nesting service template. + * @param nodeTypeIds nodeType id list + * @return service template list + * @throws CatalogResourceException e + */ + public ServiceTemplate[] getNestingServiceTemplate(String[] nodeTypeIds) + throws CatalogResourceException { + ServiceTemplate[] sts = new ServiceTemplate[nodeTypeIds.length]; + for (int i = 0; i < nodeTypeIds.length; i++) { + SubstitutionMapping stm = getSubstitutionMappingsByNodeTypeId(nodeTypeIds[i]); + if (stm == null) { + sts[i] = null; + } else { + sts[i] = getServiceTemplateById(stm.getServiceTemplateId()); + } } - - /** - * @param nodeTypeIds - * @return - * @throws CatalogResourceException - */ - public ServiceTemplate[] getNestingServiceTemplate(String[] nodeTypeIds) - throws CatalogResourceException { - ServiceTemplate[] sts = new ServiceTemplate[nodeTypeIds.length]; - for (int i = 0; i < nodeTypeIds.length; i++) { - SubstitutionMapping stm = getSubstitutionMappingsByNodeTypeId(nodeTypeIds[i]); - if (stm == null) { - sts[i] = null; - } else { - sts[i] = getServiceTemplateById(stm.getServiceTemplateId()); - } - } - - return sts; + return sts; + } + + /** + * get substitution mappings by nodeTpe id. + * @param nodeTypeId nodeType id + * @return SubstitutionMapping + * @throws CatalogResourceException e + */ + private SubstitutionMapping getSubstitutionMappingsByNodeTypeId(String nodeTypeId) + throws CatalogResourceException { + List stmDataList = + TemplateManager.getInstance().queryServiceTemplateMapping(nodeTypeId, null); + if (stmDataList == null || stmDataList.isEmpty()) { + return null; } - /** - * @param nodeTypeId - * @return - * @throws CatalogResourceException - */ - private SubstitutionMapping getSubstitutionMappingsByNodeTypeId( - String nodeTypeId) throws CatalogResourceException { - List stmDataList = TemplateManager - .getInstance().queryServiceTemplateMapping(nodeTypeId, null); - if (stmDataList == null || stmDataList.isEmpty()) { - return null; - } - - return TemplateDataHelper.convert2SubstitutionMapping(stmDataList - .get(0)); + return TemplateDataHelper.convert2SubstitutionMapping(stmDataList.get(0)); + } + + + /** + * get service template raw data. + * @param queryCondition query raw data condition + * @return ServiceTemplateRawData + * @throws CatalogResourceException e1 + * @throws CatalogBadRequestException e2 + */ + public ServiceTemplateRawData getServiceTemplateRawData(QueryRawDataCondition queryCondition) + throws CatalogResourceException, CatalogBadRequestException { + ServiceTemplateData std = getServiceTemplateDataByCsarId(queryCondition.getCsarId()); + return new ServiceTemplateRawData(std.getRowData()); + } + + /** + * get service template data by package id. + * @param csarId package id + * @return ServiceTemplateData + * @throws CatalogBadRequestException e1 + * @throws CatalogResourceException e2 + */ + private ServiceTemplateData getServiceTemplateDataByCsarId(String csarId) + throws CatalogBadRequestException, CatalogResourceException { + if (ToolUtil.isTrimedEmptyString(csarId)) { + throw new CatalogBadRequestException("CsarId is null."); } + PackageData pd = new PackageData(); + pd.setCsarId(csarId); + List stdList = + TemplateManager.getInstance().queryServiceTemplateByCsarPackageInfo(pd); - /** - * @param queryCondition - * @return - * @throws CatalogResourceException - * @throws CatalogBadRequestException - */ - public ServiceTemplateRawData getServiceTemplateRawData( - QueryRawDataCondition queryCondition) - throws CatalogResourceException, CatalogBadRequestException { - if (ToolUtil.isTrimedEmptyString(queryCondition.getCsarId())) { - throw new CatalogBadRequestException("CsarId is null."); - } - PackageData pd = new PackageData(); - pd.setCsarId(queryCondition.getCsarId()); - - List stdList = TemplateManager.getInstance() - .queryServiceTemplateByCsarPackageInfo(pd); - - if (stdList == null || stdList.isEmpty()) { - throw new CatalogResourceException( - "Can't find this servcie template"); - } - - return new ServiceTemplateRawData(stdList.get(0).getRowData()); + if (stdList == null || stdList.isEmpty()) { + throw new CatalogResourceException("Can't find this servcie template"); } - /** - * - * @param serviceTemplateId - * @return - * @throws CatalogResourceException - */ - public InputParameter[] getServiceTemplateParameters( - String serviceTemplateId) throws CatalogResourceException { - ServiceTemplate st = getServiceTemplateById(serviceTemplateId); - return st.getInputs(); + return stdList.get(0); + } + + /** + * get service template by package id. + * @param packageId package id + * @return service template data + * @throws CatalogBadRequestException e1 + * @throws CatalogResourceException e2 + */ + public ServiceTemplate getServiceTemplateByCsarId(String packageId) + throws CatalogBadRequestException, CatalogResourceException { + ServiceTemplateData std = getServiceTemplateDataByCsarId(packageId); + ServiceTemplate st = TemplateDataHelper.convert2ServiceTemplate(std); + return st; + } + + /** + * get service template parameters. + * @param serviceTemplateId service template id + * @return service template parameters + * @throws CatalogResourceException e + */ + public Parameters getServiceTemplateParameters(String serviceTemplateId) + throws CatalogResourceException { + ServiceTemplate st = getServiceTemplateById(serviceTemplateId); + return new Parameters(st.getInputs(), st.getOutputs()); + } + + /** + * get template operation. + * @param serviceTemplateId service template id + * @return service template operations + */ + public ServiceTemplateOperation[] getTemplateOperations(String serviceTemplateId) + throws CatalogResourceException { + ServiceTemplate st = getServiceTemplateById(serviceTemplateId); + + if (st.getOperations() == null) { + return new ServiceTemplateOperation[0]; } - - /** - * - * @param serviceTemplateId - * @return - */ - public ServiceTemplateOperation[] getTemplateOperations( - String serviceTemplateId) throws CatalogResourceException { - ServiceTemplate st = getServiceTemplateById(serviceTemplateId); - - if (st.getOperations() == null) { - return new ServiceTemplateOperation[0]; - } - return st.getOperations(); + return st.getOperations(); + } + + /** + * get parameters by operation name. + * @param serviceTemplateId service template id + * @param operationName operation name + * @return InputParameter list + * @throws CatalogResourceException e + */ + public InputParameter[] getParametersByOperationName(String serviceTemplateId, + String operationName) throws CatalogResourceException { + if (ToolUtil.isTrimedEmptyString(operationName)) { + throw new CatalogResourceException("Operation Name is null."); } - /** - * @param serviceTemplateId - * @param operationName - * @return - * @throws CatalogResourceException - */ - public InputParameter[] getParametersByOperationName( - String serviceTemplateId, String operationName) - throws CatalogResourceException { - if (ToolUtil.isTrimedEmptyString(operationName)) { - throw new CatalogResourceException("Operation Name is null."); - } - - ServiceTemplateOperation[] operations = getTemplateOperations(serviceTemplateId); - for (int i = 0; i < operations.length; i++) { - if (operationName.equals(operations[i].getName())) { - return operations[i].getInputs(); - } - } - - throw new CatalogResourceException("Can't find this operation."); + ServiceTemplateOperation[] operations = getTemplateOperations(serviceTemplateId); + for (int i = 0; i < operations.length; i++) { + if (operationName.equals(operations[i].getName())) { + return operations[i].getInputs(); + } } + throw new CatalogResourceException("Can't find this operation."); + } - /** - * @param serviceTemplateId - * @param nodeTemplateId - * @return - * @throws CatalogResourceException - */ - public NodeTemplate getNodeTemplateById(String serviceTemplateId, - String nodeTemplateId) throws CatalogResourceException { - List ntdList = TemplateManager.getInstance() - .queryNodeTemplateById(serviceTemplateId, nodeTemplateId); - if (ntdList == null || ntdList.isEmpty()) { - throw new CatalogResourceException("Can't find this node template."); - } + /** + * get nodeTemplate by id. + * @param serviceTemplateId service template id + * @param nodeTemplateId node template id + * @return NodeTemplate + * @throws CatalogResourceException e1 + */ + public NodeTemplate getNodeTemplateById(String serviceTemplateId, String nodeTemplateId) + throws CatalogResourceException { + List ntdList = + TemplateManager.getInstance().queryNodeTemplateById(serviceTemplateId, nodeTemplateId); - return TemplateDataHelper.convert2NodeTemplate(ntdList.get(0)); + if (ntdList == null || ntdList.isEmpty()) { + throw new CatalogResourceException("Can't find this node template."); } - /** - * @param serviceTemplateId - * @param types - * @return - * @throws CatalogResourceException - */ - public NodeTemplate[] getNodeTemplates(String serviceTemplateId, - String[] types) throws CatalogResourceException { - List ntdList = TemplateManager.getInstance() - .queryNodeTemplateBySeriviceTemplateId(serviceTemplateId); - if (ntdList == null || ntdList.isEmpty()) { - return new NodeTemplate[0]; - } - - if (ToolUtil.isTrimedEmptyArray(types)) { // return all node templates - return TemplateDataHelper.convert2NodeTemplates(ntdList); - } - - List ntList = new ArrayList<>(); - for (String type : types) { - if (!ToolUtil.isTrimedEmptyString(type)) { - List typedNtdList = filterNodeTemplateDataListByType( - ntdList, type); - ntList.addAll(Arrays -.asList(TemplateDataHelper - .convert2NodeTemplates(typedNtdList))); - } - } - return ntList.toArray(new NodeTemplate[0]); + return TemplateDataHelper.convert2NodeTemplate(ntdList.get(0)); + } + + /** + * get node templates. + * @param serviceTemplateId service template id + * @param types type list + * @return NodeTemplate list + * @throws CatalogResourceException e + */ + public NodeTemplate[] getNodeTemplates(String serviceTemplateId, String[] types) + throws CatalogResourceException { + List ntdList = + TemplateManager.getInstance().queryNodeTemplateBySeriviceTemplateId(serviceTemplateId); + if (ntdList == null || ntdList.isEmpty()) { + return new NodeTemplate[0]; } - /** - * @param ntdList - * @param type - * @return - */ - private List filterNodeTemplateDataListByType( - List ntdList, String type) { - List retList = new ArrayList<>(); - for (NodeTemplateData ntd : ntdList) { - if (type.equals(ntd.getType())) { - retList.add(ntd); - } - } - return retList; + if (ToolUtil.isTrimedEmptyArray(types)) { // return all node templates + return TemplateDataHelper.convert2NodeTemplates(ntdList); } - - /** - * @param serviceTemlateId - * @return - * @throws CatalogResourceException - */ - public NfvTemplate getNfvTemplate(String serviceTemlateId) - throws CatalogResourceException { - NodeTemplate[] nts = getNodeTemplates(serviceTemlateId, null); - - List vduNodes = new ArrayList<>(); - List networkNodes = new ArrayList<>(); - List vnfcNodes = new ArrayList<>(); - List vnfNodes = new ArrayList<>(); - for (NodeTemplate nt : nts) { - if (isVduNode(nt.getType())) { - vduNodes.add(nt); - continue; - } - - if (isNetworkNode(nt.getType())) { - networkNodes.add(nt); - continue; - } - - if (isVnfcNode(nt.getType())) { - vnfcNodes.add(nt); - continue; - } - - if (isVnfNode(nt.getType())) { - vnfNodes.add(nt); - continue; - } - } - - return new NfvTemplate(vduNodes, networkNodes, vnfcNodes, vnfNodes); + List ntList = new ArrayList<>(); + for (String type : types) { + if (!ToolUtil.isTrimedEmptyString(type)) { + List typedNtdList = filterNodeTemplateDataListByType(ntdList, type); + ntList.addAll(Arrays.asList(TemplateDataHelper.convert2NodeTemplates(typedNtdList))); + } } - - /** - * @param type - * @return - */ - private boolean isVnfNode(String type) { - return type.toUpperCase().indexOf(".VNF") > 0; + return ntList.toArray(new NodeTemplate[0]); + } + + /** + * filter node template data list by type. + * @param ntdList nodeTemplate list + * @param type node type + * @return node template data list + */ + private List filterNodeTemplateDataListByType(List ntdList, + String type) { + List retList = new ArrayList<>(); + for (NodeTemplateData ntd : ntdList) { + if (type.equals(ntd.getType())) { + retList.add(ntd); + } } - - /** - * @param type - * @return - */ - private boolean isVnfcNode(String type) { - return type.toUpperCase().indexOf(".VNFC") > 0; + return retList; + } + + + /** + * get nfv template. + * @param serviceTemlateId service template id + * @return NfvTemplate + * @throws CatalogResourceException e + */ + public NfvTemplate getNfvTemplate(String serviceTemlateId) throws CatalogResourceException { + NodeTemplate[] nts = getNodeTemplates(serviceTemlateId, null); + + List vduNodes = new ArrayList<>(); + List networkNodes = new ArrayList<>(); + List vnfcNodes = new ArrayList<>(); + List vnfNodes = new ArrayList<>(); + for (NodeTemplate nt : nts) { + if (isVduNode(nt.getType())) { + vduNodes.add(nt); + continue; + } + + if (isNetworkNode(nt.getType())) { + networkNodes.add(nt); + continue; + } + + if (isVnfcNode(nt.getType())) { + vnfcNodes.add(nt); + continue; + } + + if (isVnfNode(nt.getType())) { + vnfNodes.add(nt); + continue; + } } - /** - * @param type - * @return - */ - private boolean isNetworkNode(String type) { - return type.toUpperCase().indexOf(".VL") > 0 - || type.toUpperCase().indexOf(".VIRTUALLINK") > 0; - } + return new NfvTemplate(vduNodes, networkNodes, vnfcNodes, vnfNodes); + } - /** - * @param type - * @return - */ - private boolean isVduNode(String type) { - return type.toUpperCase().indexOf(".VDU") > 0; - } + private boolean isVnfNode(String type) { + return type.toUpperCase().indexOf(".VNF") > 0; + } + + private boolean isVnfcNode(String type) { + return type.toUpperCase().indexOf(".VNFC") > 0; + } + + private boolean isNetworkNode(String type) { + return type.toUpperCase().indexOf(".VL") > 0 || type.toUpperCase().indexOf(".VIRTUALLINK") > 0; + } + + private boolean isVduNode(String type) { + return type.toUpperCase().indexOf(".VDU") > 0; + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/resources/CatalogBadRequestException.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/resources/CatalogBadRequestException.java index 17ec7cd6..0d1a2605 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/resources/CatalogBadRequestException.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/resources/CatalogBadRequestException.java @@ -13,63 +13,61 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.resources; import org.openo.commontosca.catalog.db.exception.ErrorCodeException; -/** - * - */ public class CatalogBadRequestException extends ErrorCodeException { - private static final long serialVersionUID = 5699508780537383310L; + private static final long serialVersionUID = 5699508780537383310L; - public CatalogBadRequestException(int errcode) { - super(errcode, ""); - } + public CatalogBadRequestException(int errcode) { + super(errcode, ""); + } - public CatalogBadRequestException(int errcode, Throwable cause) { - super(cause, errcode); - } + public CatalogBadRequestException(int errcode, Throwable cause) { + super(cause, errcode); + } - public CatalogBadRequestException(int errcode, String message, Throwable cause) { - super(cause, errcode, message); - } + public CatalogBadRequestException(int errcode, String message, Throwable cause) { + super(cause, errcode, message); + } - public CatalogBadRequestException() { - super(9999999, null); - } + public CatalogBadRequestException() { + super(9999999, null); + } - public CatalogBadRequestException(String message) { - super(9999999, message); - } + public CatalogBadRequestException(String message) { + super(9999999, message); + } - public CatalogBadRequestException(Throwable cause) { - super(cause, 9999999); - } + public CatalogBadRequestException(Throwable cause) { + super(cause, 9999999); + } - public CatalogBadRequestException(String message, Throwable cause) { - super(cause, 9999999, message); - } + public CatalogBadRequestException(String message, Throwable cause) { + super(cause, 9999999, message); + } - public CatalogBadRequestException(Throwable source, int errID, String debugMessage, - String[] arguments) { - super(source, errID, debugMessage, arguments); - } + public CatalogBadRequestException(Throwable source, int errId, String debugMessage, + String[] arguments) { + super(source, errId, debugMessage, arguments); + } - public CatalogBadRequestException(Throwable source, int category, int code, - String debugMessage, String[] arguments) { - super(source, category, code, debugMessage, arguments); - } + public CatalogBadRequestException(Throwable source, int category, int code, String debugMessage, + String[] arguments) { + super(source, category, code, debugMessage, arguments); + } - public int getErrcode() { - return super.getErrorCode(); - } + public int getErrcode() { + return super.getErrorCode(); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/resources/PackageResource.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/resources/PackageResource.java index 0fd61f77..48cd1cfc 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/resources/PackageResource.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/resources/PackageResource.java @@ -13,16 +13,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.resources; +import com.codahale.metrics.annotation.Timed; + 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 java.io.InputStream; +import org.eclipse.jetty.http.HttpStatus; +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataParam; +import org.openo.commontosca.catalog.entity.response.CsarFileUriResponse; +import org.openo.commontosca.catalog.entity.response.PackageMeta; +import org.openo.commontosca.catalog.entity.response.UploadPackageResponse; +import org.openo.commontosca.catalog.wrapper.PackageWrapper; +import java.io.InputStream; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; @@ -37,16 +47,6 @@ import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import org.eclipse.jetty.http.HttpStatus; -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; -import org.glassfish.jersey.media.multipart.FormDataParam; -import org.openo.commontosca.catalog.entity.response.UploadPackageResponse; -import org.openo.commontosca.catalog.wrapper.PackageWrapper; -import org.openo.commontosca.catalog.entity.response.CsarFileUriResponse; -import org.openo.commontosca.catalog.entity.response.PackageMeta; - -import com.codahale.metrics.annotation.Timed; - /** * csar package service. * @@ -57,212 +57,182 @@ import com.codahale.metrics.annotation.Timed; @Api(tags = {"Package Resource"}) public class PackageResource { - @Path("/csars") - @GET - @ApiOperation(value = "get csar package list by condition", response = PackageMeta.class, - responseContainer = "List") - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", - response = String.class), - @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, - message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, - message = "resource grant error", response = String.class)}) - @Timed - public Response queryPackageListByCond( - @ApiParam(value = "csar name") @QueryParam("name") String name, - @ApiParam(value = "csar provider") @QueryParam("provider") String provider, - @ApiParam(value = "csar version") @QueryParam("version") String version, - @ApiParam(value = "delay to delete") @QueryParam("deletionPending") String deletionPending, - @ApiParam(value = "csar type") @QueryParam("type") String type) { - return PackageWrapper.getInstance().queryPackageListByCond(name, provider, version, - deletionPending, type); - } - - - /** - * query CSAR package infos - * - * @param csarName The CSAR name. it will return all the CSARs if the csarName is null. - * @param deletionPending - * @return - */ - @Path("/csars/{csarId}") - @GET - @ApiOperation(value = "get csar package list", response = PackageMeta.class, - responseContainer = "List") - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", - response = String.class), - @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, - message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, - message = "resource grant error", response = String.class)}) - @Timed - public Response queryPackageById(@ApiParam(value = "csar id") @PathParam("csarId") String csarId) { - return PackageWrapper.getInstance().queryPackageById(csarId); - } - - /** - * upload CSAR package with stream - * - * @param uploadedInputStream - * @param fileDetail - * @return - * @throws Exception - */ - // @Path("/csars/ftp") - // @POST - // @ApiOperation(value = "upload csar package", response = UploadPackageResponse.class) - // @Consumes(MediaType.APPLICATION_JSON) - // @Produces(MediaType.APPLICATION_JSON) - // @ApiResponses(value = { - // @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", response = - // String.class), - // @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, message = - // "Unprocessable MicroServiceInfo Entity ", response = String.class), - // @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "resource grant error", - // response = String.class)}) - // @Timed - // public Response uploadPackageFromFtp(UploadPackageFromFtpRequest request) throws Exception { - // return PackageWrapper.getInstance().uploadPackageFromFtp(request); - // } - - /** - * upload CSAR package from ftp - * - * @param uploadedInputStream - * @param fileDetail - * @return - * @throws Exception - */ - @Path("/csars") - @POST - @ApiOperation(value = "upload csar package", response = UploadPackageResponse.class) - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", - response = String.class), - @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, - message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, - message = "resource grant error", response = String.class)}) - @Timed - public Response uploadPackage( - @ApiParam(value = "file inputstream", required = true) @FormDataParam("file") InputStream uploadedInputStream, - @ApiParam(value = "file detail", required = false) @FormDataParam("file") FormDataContentDisposition fileDetail, - @ApiParam(value = "http header") @Context HttpHeaders head) throws Exception { - return PackageWrapper.getInstance().uploadPackage(uploadedInputStream, fileDetail, head); - } - - /** - * delete CSAR package - * - * @param csarName - * @return - */ - @Path("/csars/{csarId}") - @DELETE - @ApiOperation(value = "delete a package") - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", - response = String.class), - @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, - message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, - message = "resource grant error", response = String.class)}) - @Timed - public Response delPackage(@ApiParam(value = "csar Id") @PathParam("csarId") String csarId) { - return PackageWrapper.getInstance().delPackage(csarId); - } - - /** - * delete CSAR package by VNF/NS instance template id - */ - // @Path("/csars") - // @DELETE - // @ApiOperation(value = "delete a package by serviceTemplateId") - // @ApiResponses(value = { - // @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", response = - // String.class), - // @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, message = - // "Unprocessable MicroServiceInfo Entity ", response = String.class), - // @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "resource grant error", - // response = String.class)}) - // @Timed - // public Response delPackageByServiceTemplateId( - // @ApiParam(value = "serviceTemplateId") @QueryParam("serviceTemplateId") String - // serviceTemplateId) { - // return PackageWrapper.getInstance().delPackageByServiceTemplateId(serviceTemplateId); - // } - - /** - * update the status of CSAR - * - * @param csarName - * @param status active/inactive - * @return - */ - @Path("/csars/{csarId}") - @PUT - @ApiOperation(value = "update csar package status") - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", - response = String.class), - @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, - message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, - message = "resource grant error", response = String.class)}) - @Timed - public Response updatePackageStatus( - @ApiParam(value = "csar Id", required = true) @PathParam("csarId") String csarId, - @ApiParam(value = "csar operational status", required = false) @QueryParam("operationalState") String operationalState, - @ApiParam(value = "csar usage status", required = false) @QueryParam("usageState") String usageState, - @ApiParam(value = "csar onboard status", required = false) @QueryParam("onBoardState") String onBoardState, - @ApiParam(value = "csar process status", required = false) @QueryParam("processState") String processState, - @ApiParam(value = "csar deletionPending status", required = false) @QueryParam("deletionPending") String deletionPending) { - return PackageWrapper.getInstance().updatePackageStatus(csarId, operationalState, - usageState, onBoardState, processState, deletionPending); - } - - @Path("/csars/{csarId}/files") - @GET - @ApiOperation(value = "get csar file uri by csarId", response = CsarFileUriResponse.class) - @Produces(MediaType.APPLICATION_JSON) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", - response = String.class), - @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, - message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, - message = "resource grant error", response = String.class)}) - @Timed - public Response getCsarFileUri( - @ApiParam(value = "csar Id", required = true) @PathParam("csarId") String csarId, - @ApiParam(value = "csar file path", required = true) @QueryParam("relativePath") String relativePath) { - return PackageWrapper.getInstance().getCsarFileUri(csarId, relativePath); - } - - // @Path("/csars/{csarId}/plans") - // @GET - // @ApiOperation(value = "get plans of package by csarId", response = FileLink.class, - // responseContainer = "List") - // @Produces(MediaType.APPLICATION_JSON) - // @ApiResponses(value = { - // @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", response = - // String.class), - // @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, message = - // "Unprocessable MicroServiceInfo Entity ", response = String.class), - // @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "resource grant error", - // response = String.class)}) - // @Timed - // public Response getCsarPlanUri( - // @ApiParam(value = "csar Id", required = true) @PathParam("csarId") String csarId - // ) { - // return PackageWrapper.getInstance().getCsarPlansUri(csarId); - // } + @Path("/csars") + @GET + @ApiOperation(value = "get csar package list by condition", response = PackageMeta.class, + responseContainer = "List") + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", + response = String.class), + @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, + message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "resource grant error", + response = String.class)}) + @Timed + public Response queryPackageListByCond( + @ApiParam(value = "csar name") @QueryParam("name") String name, @ApiParam( + value = "csar provider") @QueryParam("provider") String provider, @ApiParam( + value = "csar version") @QueryParam("version") String version, @ApiParam( + value = "delay to delete") @QueryParam("deletionPending") String deletionPending, + @ApiParam(value = "csar type") @QueryParam("type") String type) { + return PackageWrapper.getInstance().queryPackageListByCond(name, provider, version, + deletionPending, type); + } + + + @Path("/csars/{csarId}") + @GET + @ApiOperation(value = "get csar package list", response = PackageMeta.class, + responseContainer = "List") + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", + response = String.class), + @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, + message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "resource grant error", + response = String.class)}) + @Timed + public Response queryPackageById( + @ApiParam(value = "csar id") @PathParam("csarId") String csarId) { + return PackageWrapper.getInstance().queryPackageById(csarId); + } + + // @Path("/csars/ftp") + // @POST + // @ApiOperation(value = "upload csar package", response = UploadPackageResponse.class) + // @Consumes(MediaType.APPLICATION_JSON) + // @Produces(MediaType.APPLICATION_JSON) + // @ApiResponses(value = { + // @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", response = + // String.class), + // @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, message = + // "Unprocessable MicroServiceInfo Entity ", response = String.class), + // @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "resource grant error", + // response = String.class)}) + // @Timed + // public Response uploadPackageFromFtp(UploadPackageFromFtpRequest request) throws Exception { + // return PackageWrapper.getInstance().uploadPackageFromFtp(request); + // } + + @Path("/csars") + @POST + @ApiOperation(value = "upload csar package", response = UploadPackageResponse.class) + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", + response = String.class), + @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, + message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "resource grant error", + response = String.class)}) + @Timed + public Response uploadPackage( + @ApiParam(value = "file inputstream", + required = true) @FormDataParam("file") InputStream uploadedInputStream, + @ApiParam(value = "file detail", + required = false) @FormDataParam("file") FormDataContentDisposition fileDetail, + @ApiParam(value = "http header") @Context HttpHeaders head) throws Exception { + return PackageWrapper.getInstance().uploadPackage(uploadedInputStream, fileDetail, head); + } + + @Path("/csars/{csarId}") + @DELETE + @ApiOperation(value = "delete a package") + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", + response = String.class), + @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, + message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "resource grant error", + response = String.class)}) + @Timed + public Response delPackage(@ApiParam(value = "csar Id") @PathParam("csarId") String csarId) { + return PackageWrapper.getInstance().delPackage(csarId); + } + + // @Path("/csars") + // @DELETE + // @ApiOperation(value = "delete a package by serviceTemplateId") + // @ApiResponses(value = { + // @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", response = + // String.class), + // @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, message = + // "Unprocessable MicroServiceInfo Entity ", response = String.class), + // @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "resource grant error", + // response = String.class)}) + // @Timed + // public Response delPackageByServiceTemplateId( + // @ApiParam(value = "serviceTemplateId") @QueryParam("serviceTemplateId") String + // serviceTemplateId) { + // return PackageWrapper.getInstance().delPackageByServiceTemplateId(serviceTemplateId); + // } + + @Path("/csars/{csarId}") + @PUT + @ApiOperation(value = "update csar package status") + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", + response = String.class), + @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, + message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "resource grant error", + response = String.class)}) + @Timed + public Response updatePackageStatus( + @ApiParam(value = "csar Id", required = true) @PathParam("csarId") String csarId, + @ApiParam(value = "csar operational status", + required = false) @QueryParam("operationalState") String operationalState, + @ApiParam(value = "csar usage status", + required = false) @QueryParam("usageState") String usageState, + @ApiParam(value = "csar onboard status", + required = false) @QueryParam("onBoardState") String onBoardState, + @ApiParam(value = "csar process status", + required = false) @QueryParam("processState") String processState, + @ApiParam(value = "csar deletionPending status", + required = false) @QueryParam("deletionPending") String deletionPending) { + return PackageWrapper.getInstance().updatePackageStatus(csarId, operationalState, usageState, + onBoardState, processState, deletionPending); + } + + @Path("/csars/{csarId}/files") + @GET + @ApiOperation(value = "get csar file uri by csarId", response = CsarFileUriResponse.class) + @Produces(MediaType.APPLICATION_JSON) + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", + response = String.class), + @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, + message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "resource grant error", + response = String.class)}) + @Timed + public Response getCsarFileUri( + @ApiParam(value = "csar Id", required = true) @PathParam("csarId") String csarId, + @ApiParam(value = "csar file path", + required = true) @QueryParam("relativePath") String relativePath) { + return PackageWrapper.getInstance().getCsarFileUri(csarId, relativePath); + } + + // @Path("/csars/{csarId}/plans") + // @GET + // @ApiOperation(value = "get plans of package by csarId", response = FileLink.class, + // responseContainer = "List") + // @Produces(MediaType.APPLICATION_JSON) + // @ApiResponses(value = { + // @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", response = + // String.class), + // @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, message = + // "Unprocessable MicroServiceInfo Entity ", response = String.class), + // @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "resource grant error", + // response = String.class)}) + // @Timed + // public Response getCsarPlanUri( + // @ApiParam(value = "csar Id", required = true) @PathParam("csarId") String csarId + // ) { + // return PackageWrapper.getInstance().getCsarPlansUri(csarId); + // } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/resources/RestUtils.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/resources/RestUtils.java index 62335bca..57053f87 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/resources/RestUtils.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/resources/RestUtils.java @@ -13,34 +13,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.resources; -import javax.ws.rs.BadRequestException; -import javax.ws.rs.InternalServerErrorException; -import javax.ws.rs.core.Response; +package org.openo.commontosca.catalog.resources; import org.openo.commontosca.catalog.common.CommonErrorResponse; import org.openo.commontosca.catalog.db.exception.CatalogResourceException; +import javax.ws.rs.BadRequestException; +import javax.ws.rs.InternalServerErrorException; +import javax.ws.rs.core.Response; public class RestUtils { - /** - * @param e - * @return - */ - public static InternalServerErrorException newInternalServerErrorException( - CatalogResourceException e) { - return new InternalServerErrorException(Response - .status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(new CommonErrorResponse(e.getErrcode() + "", e.getMessage())).build(), e); - } + public static InternalServerErrorException newInternalServerErrorException( + CatalogResourceException e1) { + return new InternalServerErrorException(Response.status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(new CommonErrorResponse(e1.getErrcode() + "", e1.getMessage())).build(), e1); + } - /** - * @param e - * @return - */ - public static BadRequestException newBadRequestException(CatalogBadRequestException e) { - return new BadRequestException(Response.status(Response.Status.BAD_REQUEST) - .entity(new CommonErrorResponse(e.getErrcode() + "", e.getMessage())).build(), e); - } + public static BadRequestException newBadRequestException(CatalogBadRequestException e1) { + return new BadRequestException(Response.status(Response.Status.BAD_REQUEST) + .entity(new CommonErrorResponse(e1.getErrcode() + "", e1.getMessage())).build(), e1); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/resources/TemplateResource.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/resources/TemplateResource.java index ea1c21e4..658a2f4e 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/resources/TemplateResource.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/resources/TemplateResource.java @@ -13,423 +13,440 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.resources; +import com.codahale.metrics.annotation.Timed; + 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 javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - import org.eclipse.jetty.http.HttpStatus; import org.openo.commontosca.catalog.common.CommonErrorResponse; -import org.openo.commontosca.catalog.db.exception.CatalogResourceException; -import org.openo.commontosca.catalog.model.entity.ServiceTemplateOperation; -import org.openo.commontosca.catalog.model.wrapper.ServiceTemplateWrapper; import org.openo.commontosca.catalog.common.ToolUtil; +import org.openo.commontosca.catalog.db.exception.CatalogResourceException; import org.openo.commontosca.catalog.model.entity.InputParameter; import org.openo.commontosca.catalog.model.entity.NodeTemplate; +import org.openo.commontosca.catalog.model.entity.Parameters; import org.openo.commontosca.catalog.model.entity.QueryRawDataCondition; import org.openo.commontosca.catalog.model.entity.ServiceTemplate; +import org.openo.commontosca.catalog.model.entity.ServiceTemplateOperation; import org.openo.commontosca.catalog.model.entity.ServiceTemplateRawData; import org.openo.commontosca.catalog.model.parser.ToscaYamlModelParser; +import org.openo.commontosca.catalog.model.service.ModelService; +import org.openo.commontosca.catalog.model.wrapper.ServiceTemplateWrapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.codahale.metrics.annotation.Timed; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; /** - * @author 10090474 + * model template service. * */ @Path("/servicetemplates") @Api(tags = {"Model Resource"}) public class TemplateResource { - private static final Logger logger = LoggerFactory.getLogger(TemplateResource.class); - - /** - * @param servicetemplateid - * @return - */ - @Path("/{servicetemplateid}") - @GET - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Query service template by service template id", - response = ServiceTemplate.class) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", - response = String.class), - @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, - message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, - message = "server internal error", response = CommonErrorResponse.class)}) - @Timed - public Response getServiceTemplateById( - @ApiParam(value = "service template id") @PathParam("servicetemplateid") String servicetemplateid) { - try { - ServiceTemplate st = - ServiceTemplateWrapper.getInstance().getServiceTemplateById(servicetemplateid); - return Response.status(Response.Status.OK).entity(st).build(); - } catch (CatalogResourceException e) { - logger.error("getServiceTemplateById failed.", e); - throw RestUtils.newInternalServerErrorException(e); - } - } - - /** - * @param status - * @param deletionPending - * @return - */ - @GET - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Query service template by filter conditions", - response = ServiceTemplate.class, responseContainer = "List") - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", - response = String.class), - @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, - message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, - message = "server internal error", response = CommonErrorResponse.class)}) - @Timed - public Response getServiceTemplates( - @ApiParam(value = "template status") @QueryParam("status") String status, - @ApiParam(value = "delay to delete") @QueryParam("deletionPending") boolean deletionPending) { - try { - ServiceTemplate[] sts = - ServiceTemplateWrapper.getInstance().getServiceTemplates(status, - deletionPending); - return Response.status(Response.Status.OK).entity(sts).build(); - } catch (CatalogResourceException e) { - logger.error("getServiceTemplates failed.", e); - throw RestUtils.newInternalServerErrorException(e); - } + private static final Logger logger = LoggerFactory.getLogger(TemplateResource.class); + /** + * Query service template by service template id. + * @param servicetemplateid service template id + * @return Response + */ + @Path("/{servicetemplateid}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Query service template by service template id", + response = ServiceTemplate.class) + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", + response = String.class), + @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, + message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "server internal error", + response = CommonErrorResponse.class)}) + @Timed + public Response getServiceTemplateById(@ApiParam( + value = "service template id") @PathParam("servicetemplateid") String servicetemplateid) { + try { + ServiceTemplate st = + ServiceTemplateWrapper.getInstance().getServiceTemplateById(servicetemplateid); + return Response.status(Response.Status.OK).entity(st).build(); + } catch (CatalogResourceException e1) { + logger.error("getServiceTemplateById failed.", e1); + throw RestUtils.newInternalServerErrorException(e1); } + } - /** - * @param nodeTypeIds - * @return - */ - @Path("/nesting") - @GET - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Query nesting service template of a node type", - response = ServiceTemplate.class, responseContainer = "List") - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", - response = String.class), - @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, - message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, - message = "server internal error", response = CommonErrorResponse.class)}) - @Timed - public Response getNestingServiceTemplate( - @ApiParam(value = "Node Type Id", required = true) @QueryParam("nodeTypeIds") String nodeTypeIds) { - try { - if (ToolUtil.isTrimedEmptyString(nodeTypeIds)) { - throw new CatalogBadRequestException("nodeTypeIds is null."); - } - String[] tmpNodeTypeIds = nodeTypeIds.split(","); - ServiceTemplate[] sts = - ServiceTemplateWrapper.getInstance().getNestingServiceTemplate( - ToolUtil.TrimedStringArray(tmpNodeTypeIds)); - return Response.status(Response.Status.OK).entity(sts).build(); - } catch (CatalogResourceException e) { - logger.error("getNestingServiceTemplate failed.", e); - throw RestUtils.newInternalServerErrorException(e); - } catch (CatalogBadRequestException e) { - logger.error("getNestingServiceTemplate failed.", e); - throw RestUtils.newBadRequestException(e); - } + + /** + * Query service template by filter conditions. + * @param status template status + * @param deletionPending delay to delete + * @return Response + */ + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Query service template by filter conditions", + response = ServiceTemplate.class, responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", + response = String.class), + @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, + message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "server internal error", + response = CommonErrorResponse.class)}) + @Timed + public Response getServiceTemplates( + @ApiParam(value = "template status") @QueryParam("status") String status, + @ApiParam(value = "delay to delete") @QueryParam("deletionPending") boolean deletionPending) { + try { + ServiceTemplate[] sts = + ServiceTemplateWrapper.getInstance().getServiceTemplates(status, deletionPending); + return Response.status(Response.Status.OK).entity(sts).build(); + } catch (CatalogResourceException e1) { + logger.error("getServiceTemplates failed.", e1); + throw RestUtils.newInternalServerErrorException(e1); } - /** - * @param nodeTypeId - * @return - */ - @Path("/queryingrawdata") - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Query raw data of a service template by csar id", - response = ServiceTemplateRawData.class) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", - response = String.class), - @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, - message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, - message = "server internal error", response = CommonErrorResponse.class)}) - @Timed - public Response getServiceTemplateRawData( - @ApiParam(value = "Query Service Template Raw Data Condition", required = true) QueryRawDataCondition queryCondition) { - try { - ServiceTemplateRawData stRowData = - ServiceTemplateWrapper.getInstance().getServiceTemplateRawData(queryCondition); - return Response.status(Response.Status.OK).entity(stRowData).build(); - } catch (CatalogResourceException e) { - logger.error("getServiceTemplateRawData failed.", e); - throw RestUtils.newInternalServerErrorException(e); - } catch (CatalogBadRequestException e) { - logger.error("getServiceTemplateRawData failed.", e); - throw RestUtils.newBadRequestException(e); - } + } + + /** + * Query nesting service template of a node type. + * @param nodeTypeIds node type ids + * @return Response + */ + @Path("/nesting") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Query nesting service template of a node type", + response = ServiceTemplate.class, responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", + response = String.class), + @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, + message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "server internal error", + response = CommonErrorResponse.class)}) + @Timed + public Response getNestingServiceTemplate(@ApiParam(value = "Node Type Id", + required = true) @QueryParam("nodeTypeIds") String nodeTypeIds) { + try { + if (ToolUtil.isTrimedEmptyString(nodeTypeIds)) { + throw new CatalogBadRequestException("nodeTypeIds is null."); + } + String[] tmpNodeTypeIds = nodeTypeIds.split(","); + ServiceTemplate[] sts = ServiceTemplateWrapper.getInstance() + .getNestingServiceTemplate(ToolUtil.trimedStringArray(tmpNodeTypeIds)); + return Response.status(Response.Status.OK).entity(sts).build(); + } catch (CatalogResourceException e1) { + logger.error("getNestingServiceTemplate failed.", e1); + throw RestUtils.newInternalServerErrorException(e1); + } catch (CatalogBadRequestException e2) { + logger.error("getNestingServiceTemplate failed.", e2); + throw RestUtils.newBadRequestException(e2); } + } + /** + * Query raw data of a service template by csar id. + * @param queryCondition query condition + * @return Response + */ + @Path("/queryingrawdata") + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Query raw data of a service template by csar id", + response = ServiceTemplateRawData.class) + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", + response = String.class), + @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, + message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "server internal error", + response = CommonErrorResponse.class)}) + @Timed + public Response getServiceTemplateRawData( + @ApiParam(value = "Query Service Template Raw Data Condition", + required = true) QueryRawDataCondition queryCondition) { + try { + ServiceTemplateRawData stRowData = + ServiceTemplateWrapper.getInstance().getServiceTemplateRawData(queryCondition); + return Response.status(Response.Status.OK).entity(stRowData).build(); + } catch (CatalogResourceException e1) { + logger.error("getServiceTemplateRawData failed.", e1); + throw RestUtils.newInternalServerErrorException(e1); + } catch (CatalogBadRequestException e2) { + logger.error("getServiceTemplateRawData failed.", e2); + throw RestUtils.newBadRequestException(e2); + } + } - /** - * @param serviceTemplateId - * @return - */ - @Path("/{serviceTemplateId}/operations") - @GET - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Query operation list of service template", - response = ServiceTemplateOperation.class, responseContainer = "List") - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", - response = String.class), - @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, - message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, - message = "server internal error", response = CommonErrorResponse.class)}) - @Timed - public Response getServiceTemplateOperations(@ApiParam(value = "Service Template Id", - required = true) @PathParam("serviceTemplateId") String serviceTemplateId) { - try { - ServiceTemplateOperation[] operations = - ServiceTemplateWrapper.getInstance().getTemplateOperations(serviceTemplateId); - return Response.status(Response.Status.OK).entity(operations).build(); - } catch (CatalogResourceException e) { - logger.error("getServiceTemplateOperations failed.", e); - throw RestUtils.newInternalServerErrorException(e); - } + /** + * Query operation list of service template. + * @param serviceTemplateId service template id + * @return Response + */ + @Path("/{serviceTemplateId}/operations") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Query operation list of service template", + response = ServiceTemplateOperation.class, responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", + response = String.class), + @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, + message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "server internal error", + response = CommonErrorResponse.class)}) + @Timed + public Response getServiceTemplateOperations(@ApiParam(value = "Service Template Id", + required = true) @PathParam("serviceTemplateId") String serviceTemplateId) { + try { + ServiceTemplateOperation[] operations = + ServiceTemplateWrapper.getInstance().getTemplateOperations(serviceTemplateId); + return Response.status(Response.Status.OK).entity(operations).build(); + } catch (CatalogResourceException e1) { + logger.error("getServiceTemplateOperations failed.", e1); + throw RestUtils.newInternalServerErrorException(e1); } - /** - * @param serviceTemplateId - * @param operationName - * @return - */ - @Path("/{serviceTemplateId}/operations/{operationName}/parameters") - @GET - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Query input parameters of a specified operation", - response = InputParameter.class, responseContainer = "List") - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", - response = String.class), - @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, - message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, - message = "server internal error", response = CommonErrorResponse.class)}) - @Timed - public Response getParametersByOperationName( - @ApiParam(value = "Service Template Id", required = true) @PathParam("serviceTemplateId") String serviceTemplateId, - @ApiParam(value = "Operation Name", required = true) @PathParam("operationName") String operationName) { - try { - InputParameter[] inputs = - ServiceTemplateWrapper.getInstance().getParametersByOperationName( - serviceTemplateId, operationName); - return Response.status(Response.Status.OK).entity(inputs).build(); - } catch (CatalogResourceException e) { - logger.error("getParametersByOperationId failed.", e); - throw RestUtils.newInternalServerErrorException(e); - } + } + /** + * Query input parameters of a specified operation. + * @param serviceTemplateId service template id + * @param operationName operation name + * @return Response + */ + @Path("/{serviceTemplateId}/operations/{operationName}/parameters") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Query input parameters of a specified operation", + response = InputParameter.class, responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", + response = String.class), + @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, + message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "server internal error", + response = CommonErrorResponse.class)}) + @Timed + public Response getParametersByOperationName( + @ApiParam(value = "Service Template Id", + required = true) @PathParam("serviceTemplateId") String serviceTemplateId, + @ApiParam(value = "Operation Name", + required = true) @PathParam("operationName") String operationName) { + try { + InputParameter[] inputs = ServiceTemplateWrapper.getInstance() + .getParametersByOperationName(serviceTemplateId, operationName); + return Response.status(Response.Status.OK).entity(inputs).build(); + } catch (CatalogResourceException e1) { + logger.error("getParametersByOperationId failed.", e1); + throw RestUtils.newInternalServerErrorException(e1); } - /** - * @param servicetemplateid - * @return - */ - @Path("/{servicetemplateid}/parameters") - @GET - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Query input parameters of service template", - response = InputParameter.class, responseContainer = "List") - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", - response = String.class), - @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, - message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, - message = "server internal error", response = CommonErrorResponse.class)}) - @Timed - public Response getServiceTemplateParameters(@ApiParam(value = "service template id", - required = true) @PathParam("servicetemplateid") String servicetemplateid) { - try { - InputParameter[] inputs = - ServiceTemplateWrapper.getInstance().getServiceTemplateParameters( - servicetemplateid); - return Response.status(Response.Status.OK).entity(inputs).build(); - } catch (CatalogResourceException e) { - logger.error("getServiceTemplateParameters failed.", e); - throw RestUtils.newInternalServerErrorException(e); - } + } + /** + * Query input parameters of service template. + * @param servicetemplateid service template id + * @return Response + */ + @Path("/{servicetemplateid}/parameters") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Query input parameters of service template", response = Parameters.class) + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", + response = String.class), + @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, + message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "server internal error", + response = CommonErrorResponse.class)}) + @Timed + public Response getServiceTemplateParameters(@ApiParam(value = "service template id", + required = true) @PathParam("servicetemplateid") String servicetemplateid) { + try { + Parameters parameters = + ServiceTemplateWrapper.getInstance().getServiceTemplateParameters(servicetemplateid); + return Response.status(Response.Status.OK).entity(parameters).build(); + } catch (CatalogResourceException e1) { + logger.error("getServiceTemplateParameters failed.", e1); + throw RestUtils.newInternalServerErrorException(e1); } - /** - * @param serviceTemplateId - * @param types - * @return - */ - @Path("/{serviceTemplateId}/nodetemplates") - @GET - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Query node template list of a specified service template", - response = NodeTemplate.class, responseContainer = "List") - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", - response = String.class), - @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, - message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, - message = "server internal error", response = CommonErrorResponse.class)}) - @Timed - public Response getNodeTemplatesByType( - @ApiParam(value = "Service Template Id", required = true) @PathParam("serviceTemplateId") String serviceTemplateId, - @ApiParam(value = "The type of node template") @QueryParam("types") String types) { - try { - String[] tmpTypes = getSplitedTypes(types); - NodeTemplate[] nts = - ServiceTemplateWrapper.getInstance().getNodeTemplates(serviceTemplateId, - ToolUtil.TrimedStringArray(tmpTypes)); - return Response.status(Response.Status.OK).entity(nts).build(); - } catch (CatalogResourceException e) { - logger.error("getNodeTemplateList failed.", e); - throw RestUtils.newInternalServerErrorException(e); - } + } + /** + * Query node template list of a specified service template. + * @param serviceTemplateId service template id + * @param types node type + * @return Response + */ + @Path("/{serviceTemplateId}/nodetemplates") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Query node template list of a specified service template", + response = NodeTemplate.class, responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", + response = String.class), + @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, + message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "server internal error", + response = CommonErrorResponse.class)}) + @Timed + public Response getNodeTemplatesByType( + @ApiParam(value = "Service Template Id", + required = true) @PathParam("serviceTemplateId") String serviceTemplateId, + @ApiParam(value = "The type of node template") @QueryParam("types") String types) { + try { + String[] tmpTypes = getSplitedTypes(types); + NodeTemplate[] nts = ServiceTemplateWrapper.getInstance().getNodeTemplates(serviceTemplateId, + ToolUtil.trimedStringArray(tmpTypes)); + return Response.status(Response.Status.OK).entity(nts).build(); + } catch (CatalogResourceException e1) { + logger.error("getNodeTemplateList failed.", e1); + throw RestUtils.newInternalServerErrorException(e1); } + } - private String[] getSplitedTypes(String types) { - if (ToolUtil.isTrimedEmptyString(types)) { - return new String[0]; - } - return types.split(","); + private String[] getSplitedTypes(String types) { + if (ToolUtil.isTrimedEmptyString(types)) { + return new String[0]; } - /** - * @param serviceTemplateId - * @param nodeTemplateId - * @return - */ - @Path("/{serviceTemplateId}/nodetemplates/{nodeTemplateId}") - @GET - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Query node template by node template id", response = NodeTemplate.class) - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", - response = String.class), - @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, - message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, - message = "server internal error", response = CommonErrorResponse.class)}) - @Timed - public Response getNodeTemplateById( - @ApiParam(value = "Service Template Id", required = true) @PathParam("serviceTemplateId") String serviceTemplateId, - @ApiParam(value = "Node Template Id", required = true) @PathParam("nodeTemplateId") String nodeTemplateId) { - try { - NodeTemplate nt = - ServiceTemplateWrapper.getInstance().getNodeTemplateById(serviceTemplateId, - nodeTemplateId); - return Response.status(Response.Status.OK).entity(nt).build(); - } catch (CatalogResourceException e) { - logger.error("getNodeTemplateById failed.", e); - throw RestUtils.newInternalServerErrorException(e); - } + return types.split(","); + } + /** + * Query node template by node template id. + * @param serviceTemplateId service template id + * @param nodeTemplateId node template id + * @return Response + */ + @Path("/{serviceTemplateId}/nodetemplates/{nodeTemplateId}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Query node template by node template id", response = NodeTemplate.class) + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", + response = String.class), + @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, + message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "server internal error", + response = CommonErrorResponse.class)}) + @Timed + public Response getNodeTemplateById( + @ApiParam(value = "Service Template Id", + required = true) @PathParam("serviceTemplateId") String serviceTemplateId, + @ApiParam(value = "Node Template Id", + required = true) @PathParam("nodeTemplateId") String nodeTemplateId) { + try { + NodeTemplate nt = ServiceTemplateWrapper.getInstance().getNodeTemplateById(serviceTemplateId, + nodeTemplateId); + return Response.status(Response.Status.OK).entity(nt).build(); + } catch (CatalogResourceException e1) { + logger.error("getNodeTemplateById failed.", e1); + throw RestUtils.newInternalServerErrorException(e1); } - // /** - // * @param servicetemplateid - // * @return - // */ - // @Path("/{servicetemplateid}/nfvtemplate") - // @POST - // @Consumes(MediaType.APPLICATION_JSON) - // @Produces(MediaType.APPLICATION_JSON) - // @ApiOperation(value = - // "Query node template detail of a specified service template", response = - // NfvTemplate.class) - // @ApiResponses(value = { - // @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = - // "microservice not found", response = String.class), - // @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, message = - // "Unprocessable MicroServiceInfo Entity ", response = String.class), - // @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = - // "server internal error", response = CommonErrorResponse.class) }) - // @Timed - // public Response getNfvTemplate( - // @ApiParam(value = "service template id", required = true) - // @PathParam("servicetemplateid") String servicetemplateid) { - // try { - // NfvTemplate nfvTemplate = ServiceTemplateWrapper.getInstance() - // .getNfvTemplate(servicetemplateid); - // return Response.status(Response.Status.OK).entity(nfvTemplate) - // .build(); - // } catch (CatalogResourceException e) { - // logger.error("getNfvTemplate failed.", e); - // throw RestUtils.newInternalServerErrorException(e); - // } - // - // } - - /** - * - * @return - */ - @Path("/test") - @GET - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "test", response = String.class, responseContainer = "List") - @ApiResponses(value = { - @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", - response = String.class), - @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, - message = "Unprocessable MicroServiceInfo Entity ", response = String.class), - @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, - message = "server internal error", response = CommonErrorResponse.class)}) - @Timed - public Response test() { - try { - ToscaYamlModelParser parser = new ToscaYamlModelParser(); - parser.parse("pk11111", "C:\\Users\\10090474\\Desktop\\3\\NS_core\\NS_core.zip"); - String[] strs = {"111", "222", null, null, "555"}; - Response.status(Response.Status.OK).entity(strs).build(); - throw new CatalogResourceException("test failed."); - } catch (CatalogResourceException e) { - logger.error("test failed.", e); - throw RestUtils.newInternalServerErrorException(e); - } + } + + // /** + // * @param servicetemplateid + // * @return + // */ + // @Path("/{servicetemplateid}/nfvtemplate") + // @POST + // @Consumes(MediaType.APPLICATION_JSON) + // @Produces(MediaType.APPLICATION_JSON) + // @ApiOperation(value = + // "Query node template detail of a specified service template", response = + // NfvTemplate.class) + // @ApiResponses(value = { + // @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = + // "microservice not found", response = String.class), + // @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, message = + // "Unprocessable MicroServiceInfo Entity ", response = String.class), + // @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = + // "server internal error", response = CommonErrorResponse.class) }) + // @Timed + // public Response getNfvTemplate( + // @ApiParam(value = "service template id", required = true) + // @PathParam("servicetemplateid") String servicetemplateid) { + // try { + // NfvTemplate nfvTemplate = ServiceTemplateWrapper.getInstance() + // .getNfvTemplate(servicetemplateid); + // return Response.status(Response.Status.OK).entity(nfvTemplate) + // .build(); + // } catch (CatalogResourceException e) { + // logger.error("getNfvTemplate failed.", e); + // throw RestUtils.newInternalServerErrorException(e); + // } + // + // } + + /** + * test function. + * @return Response + */ + @Path("/test") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "test", response = String.class, responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "microservice not found", + response = String.class), + @ApiResponse(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, + message = "Unprocessable MicroServiceInfo Entity ", response = String.class), + @ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500, message = "server internal error", + response = CommonErrorResponse.class)}) + @Timed + public Response test() { + try { + ToscaYamlModelParser parser = new ToscaYamlModelParser(); + parser.parse("pk11111", "C:\\Users\\10090474\\Desktop\\1\\bm\\bm.zip"); + String[] strs = {"111", "222", null, null, "555"}; + Response.status(Response.Status.OK).entity(strs).build(); + + ModelService.getInstance().delete("pk11111"); + throw new CatalogResourceException("test failed."); + } catch (CatalogResourceException e1) { + logger.error("test failed.", e1); + throw RestUtils.newInternalServerErrorException(e1); + } catch (CatalogBadRequestException e2) { + logger.error("test failed.", e2); + throw RestUtils.newBadRequestException(e2); } + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/wrapper/PackageWrapper.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/wrapper/PackageWrapper.java index 8ded7bba..36b229b8 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/wrapper/PackageWrapper.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/wrapper/PackageWrapper.java @@ -13,19 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.wrapper; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; +package org.openo.commontosca.catalog.wrapper; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.openo.commontosca.catalog.common.CommonConstant; @@ -50,413 +39,478 @@ import org.openo.commontosca.catalog.model.parser.ModelParserFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * @author 10189609 - * - */ +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; + +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + public class PackageWrapper { - private static PackageWrapper packageWrapper; - private static final Logger LOG = LoggerFactory.getLogger(PackageWrapper.class); + private static PackageWrapper packageWrapper; + private static final Logger LOG = LoggerFactory.getLogger(PackageWrapper.class); - public static PackageWrapper getInstance() { - if (packageWrapper == null) { - packageWrapper = new PackageWrapper(); - } - return packageWrapper; + /** + * get PackageWrapper instance. + * @return package wrapper instance + */ + public static PackageWrapper getInstance() { + if (packageWrapper == null) { + packageWrapper = new PackageWrapper(); } + return packageWrapper; + } - public Response queryPackageById(String csarId) { - ArrayList dbResult = new ArrayList(); - ArrayList result = new ArrayList(); - dbResult = PackageWrapperUtil.getPackageInfoById(csarId); - if (dbResult.size() != 0) { - result = PackageWrapperUtil.packageDataList2PackageMetaList(dbResult); - return Response.ok(result).build(); - } else { - String errorMsg = "get package info by Id error !"; - return RestUtil.getRestException(errorMsg); - } + /** + * query package by id. + * @param csarId package id + * @return Response + */ + public Response queryPackageById(String csarId) { + ArrayList dbResult = new ArrayList(); + ArrayList result = new ArrayList(); + dbResult = PackageWrapperUtil.getPackageInfoById(csarId); + if (dbResult.size() != 0) { + result = PackageWrapperUtil.packageDataList2PackageMetaList(dbResult); + return Response.ok(result).build(); + } else { + String errorMsg = "get package info by Id error !"; + return RestUtil.getRestException(errorMsg); } + } - public Response uploadPackage(InputStream uploadedInputStream, - FormDataContentDisposition fileDetail, HttpHeaders head) throws Exception { - PackageBasicInfo basicInfo = new PackageBasicInfo(); - String tempDirName = null; - int fileSize = 0; - String fileName = ""; - UploadPackageResponse result = new UploadPackageResponse(); - PackageMeta packageMeta = new PackageMeta(); - if (uploadedInputStream == null) { - LOG.info("the uploadStream is null"); - return Response.serverError().build(); - } - if (fileDetail == null) { - LOG.info("the fileDetail is null"); - return Response.serverError().build(); - } + /** + * upload package. + * @param uploadedInputStream inputStream + * @param fileDetail package detail + * @param head http header + * @return Response + * @throws Exception e + */ + public Response uploadPackage(InputStream uploadedInputStream, + FormDataContentDisposition fileDetail, HttpHeaders head) throws Exception { + PackageBasicInfo basicInfo = new PackageBasicInfo(); + String tempDirName = null; + int fileSize = 0; + String fileName = ""; + UploadPackageResponse result = new UploadPackageResponse(); + PackageMeta packageMeta = new PackageMeta(); + if (uploadedInputStream == null) { + LOG.info("the uploadStream is null"); + return Response.serverError().build(); + } + if (fileDetail == null) { + LOG.info("the fileDetail is null"); + return Response.serverError().build(); + } - try { - String contentRange = null; - fileName = ToolUtil.processFileName(fileDetail.getFileName()); - tempDirName = ToolUtil.getTempDir(CommonConstant.CATALOG_CSAR_DIR_NAME, fileName); - if (head != null) { - contentRange = head.getHeaderString(CommonConstant.HTTP_HEADER_CONTENT_RANGE); - } - LOG.debug("store package chunk file, fileName:" + fileName + ",contentRange:" - + contentRange); - if (ToolUtil.isEmptyString(contentRange)) { - fileSize = uploadedInputStream.available(); - contentRange = "0-" + fileSize + "/" + fileSize; - } - Boolean isEnd = PackageWrapperUtil.isUploadEnd(contentRange, fileName); - String fileLocation = - ToolUtil.storeChunkFileInLocal(tempDirName, fileName, uploadedInputStream); - LOG.info("the fileLocation when upload package is :" + fileLocation); - uploadedInputStream.close(); + try { + String contentRange = null; + fileName = ToolUtil.processFileName(fileDetail.getFileName()); + tempDirName = ToolUtil.getTempDir(CommonConstant.CATALOG_CSAR_DIR_NAME, fileName); + if (head != null) { + contentRange = head.getHeaderString(CommonConstant.HTTP_HEADER_CONTENT_RANGE); + } + LOG.debug("store package chunk file, fileName:" + fileName + ",contentRange:" + contentRange); + if (ToolUtil.isEmptyString(contentRange)) { + fileSize = uploadedInputStream.available(); + contentRange = "0-" + fileSize + "/" + fileSize; + } + String fileLocation = + ToolUtil.storeChunkFileInLocal(tempDirName, fileName, uploadedInputStream); + LOG.info("the fileLocation when upload package is :" + fileLocation); + uploadedInputStream.close(); - basicInfo = PackageWrapperUtil.getPacageBasicInfo(fileLocation); - String path = - basicInfo.getType().toString() + File.separator + basicInfo.getProvider() - + File.separator + fileName.replace(".csar", "") + File.separator - + basicInfo.getVersion(); - LOG.info("dest path is : " + path); - packageMeta = PackageWrapperUtil.getPackageMeta(fileName, fileLocation, basicInfo); - String dowloadUri = File.separator + path + File.separator; - String destPath = File.separator + path; - packageMeta.setDownloadUri(dowloadUri); - LOG.info("packageMeta = " + ToolUtil.objectToString(packageMeta)); - if (isEnd) { - boolean uploadResult = - FileManagerFactory.createFileManager().upload(tempDirName, destPath); - if (uploadResult == true) { - // 调袁虎的接口,将fileLocation 和 packageId传给他,由他去解析包,并向数据库存储数据 - // String parseResult = - // ModelParserFactory.getInstance().parse(packageMeta.getCsarId(), - // fileLocation , EnumPackageFormat.valueOf(packageMeta.getFormat())); - PackageData packageData = PackageWrapperUtil.getPackageData(packageMeta); - PackageManager.getInstance().addPackage(packageData); - } - LOG.info("upload package file end, fileName:" + fileName); - } - result.setCsarId(packageMeta.getCsarId()); - return Response.ok(result).build(); - } catch (Exception e) { - LOG.error("upload package fail.", e); - String csarId = packageMeta.getCsarId(); - if (csarId != null) { - PackageManager.getInstance().deletePackage(csarId); - } - return RestUtil.getRestException(e.getMessage()); - } finally { - if (tempDirName != null) { - ToolUtil.deleteDir(new File(tempDirName)); - } + basicInfo = PackageWrapperUtil.getPacageBasicInfo(fileLocation); + String path = + basicInfo.getType().toString() + File.separator + basicInfo.getProvider() + + File.separator + fileName.replace(".csar", "") + File.separator + + basicInfo.getVersion(); + LOG.info("dest path is : " + path); + packageMeta = PackageWrapperUtil.getPackageMeta(fileName, fileLocation, basicInfo); + String dowloadUri = File.separator + path + File.separator; + String destPath = File.separator + path; + packageMeta.setDownloadUri(dowloadUri); + LOG.info("packageMeta = " + ToolUtil.objectToString(packageMeta)); + Boolean isEnd = PackageWrapperUtil.isUploadEnd(contentRange, fileName); + if (isEnd) { + boolean uploadResult = FileManagerFactory.createFileManager().upload(tempDirName, destPath); + if (uploadResult == true) { + // 调袁虎的接口,将fileLocation 和 packageId传给他,由他去解析包,并向数据库存储数据 + // String parseResult = + // ModelParserFactory.getInstance().parse(packageMeta.getCsarId(), + // fileLocation , EnumPackageFormat.valueOf(packageMeta.getFormat())); + PackageData packageData = PackageWrapperUtil.getPackageData(packageMeta); + PackageManager.getInstance().addPackage(packageData); } + LOG.info("upload package file end, fileName:" + fileName); + } + result.setCsarId(packageMeta.getCsarId()); + return Response.ok(result).build(); + } catch (Exception e1) { + LOG.error("upload package fail.", e1); + String csarId = packageMeta.getCsarId(); + if (csarId != null) { + PackageManager.getInstance().deletePackage(csarId); + } + return RestUtil.getRestException(e1.getMessage()); + } finally { + if (tempDirName != null) { + ToolUtil.deleteDir(new File(tempDirName)); + } } + } - public Response delPackage(String csarId) { - LOG.info("delete package info.csarId:" + csarId); - if (ToolUtil.isEmptyString(csarId)) { - LOG.error("delete package fail, csarid is null"); - return Response.serverError().build(); - } - try { - delCsarThread thread = new delCsarThread(csarId, false); - new Thread(thread).start(); - return Response.noContent().build(); - } catch (Exception e) { - LOG.error("delete fail.", e); - return RestUtil.getRestException(e.getMessage()); - } + /** + * delete package by package id. + * @param csarId package id + * @return Response + */ + public Response delPackage(String csarId) { + LOG.info("delete package info.csarId:" + csarId); + if (ToolUtil.isEmptyString(csarId)) { + LOG.error("delete package fail, csarid is null"); + return Response.serverError().build(); } + try { + DelCsarThread thread = new DelCsarThread(csarId, false); + new Thread(thread).start(); + return Response.noContent().build(); + } catch (Exception e1) { + LOG.error("delete fail.", e1); + return RestUtil.getRestException(e1.getMessage()); + } + } - // public Response delPackageByServiceTemplateId(String serviceTemplateId) { - // LOG.info("delete package info.serviceTemplateId:" + serviceTemplateId); - // if (ToolUtil.isEmptyString(serviceTemplateId)) { - // LOG.error("delete package fail, serviceTemplateId is null"); - // return Response.serverError().build(); - // } - // ArrayList result = new ArrayList(); - // try { - // result = PackageManager.getInstance().queryPackageByServiceTemplateId(serviceTemplateId); - // - // } catch (CatalogResourceException e) { - // LOG.error("query package by csarId from db error ! " + e.getMessage()); - // return RestUtil.getRestException(e.getMessage()); - // } - // if (result.size() <= 0) { - // LOG.warn("not exist package by serviceTemplateId"); - // return Response.status(Status.NOT_FOUND).build(); - // } - // if ("true".equals(result.get(0).getDeletionPending())) { - // LOG.info("start delete package.csarId:" + result.get(0).getCsarId()); - // delCsarThread thread = new delCsarThread(result.get(0).getCsarId(), true); - // new Thread(thread).start(); - // } - // return Response.noContent().build(); - // } - - class delCsarThread implements Runnable { - private String csarid; - private boolean isInstanceTemplate = false; + // public Response delPackageByServiceTemplateId(String serviceTemplateId) { + // LOG.info("delete package info.serviceTemplateId:" + serviceTemplateId); + // if (ToolUtil.isEmptyString(serviceTemplateId)) { + // LOG.error("delete package fail, serviceTemplateId is null"); + // return Response.serverError().build(); + // } + // ArrayList result = new ArrayList(); + // try { + // result = PackageManager.getInstance().queryPackageByServiceTemplateId(serviceTemplateId); + // + // } catch (CatalogResourceException e) { + // LOG.error("query package by csarId from db error ! " + e.getMessage()); + // return RestUtil.getRestException(e.getMessage()); + // } + // if (result.size() <= 0) { + // LOG.warn("not exist package by serviceTemplateId"); + // return Response.status(Status.NOT_FOUND).build(); + // } + // if ("true".equals(result.get(0).getDeletionPending())) { + // LOG.info("start delete package.csarId:" + result.get(0).getCsarId()); + // delCsarThread thread = new delCsarThread(result.get(0).getCsarId(), true); + // new Thread(thread).start(); + // } + // return Response.noContent().build(); + // } - public delCsarThread(String csarid, boolean isInstanceTemplate) { - this.csarid = csarid; - this.isInstanceTemplate = isInstanceTemplate; - } + class DelCsarThread implements Runnable { + private String csarid; + private boolean isInstanceTemplate = false; - @Override - public void run() { - try { - if (!ToolUtil.isEmptyString(csarid)) { - delCsarDATA(csarid); - } - } catch (Exception e) { - LOG.error("del instance csar fail.", e); - updatePackageStatus(csarid, null, null, null, - CommonConstant.PACKAGE_STATUS_DELETE_FAIL, null); - // publishDelFinishCometdMessage(csarid, "false"); - } - } + public DelCsarThread(String csarid, boolean isInstanceTemplate) { + this.csarid = csarid; + this.isInstanceTemplate = isInstanceTemplate; + } - private void delCsarDATA(String csarId) { - updatePackageStatus(csarid, null, null, null, CommonConstant.PACKAGE_STATUS_DELETING, - null); - String packagePath = PackageWrapperUtil.getPackagePath(csarId); - if (packagePath == null) { - LOG.error("package path is null! "); - return; - } - FileManagerFactory.createFileManager().delete(packagePath); - try { - PackageManager.getInstance().deletePackage(csarId); - } catch (CatalogResourceException e) { - LOG.error("delete package by csarId from db error ! " + e.getMessage()); - } - // delete template data from db - PackageData packageData = new PackageData(); - packageData.setCsarId(csarId); - try { - TemplateManager.getInstance().deleteServiceTemplateByCsarPackageInfo(packageData); - } catch (CatalogResourceException e) { - LOG.error("delete template data from db error! csarId = " + csarId); - } - // publishDelFinishCometdMessage(csarid, "true"); + @Override + public void run() { + try { + if (!ToolUtil.isEmptyString(csarid)) { + delCsarData(csarid); } - - // private void publishDelFinishCometdMessage(String csarid, String csarDelStatus) { - // if (isInstanceTemplate) { - // LOG.info("delete instance Template finish. csarid:{}", csarid); - // return; - // } - // try { - // Map cometdMessage = new HashMap(); - // cometdMessage.put("csarid", csarid); - // cometdMessage.put("status", csarDelStatus); - // CometdService.getInstance().publish(CommonConstant.COMETD_CHANNEL_PACKAGE_DELETE, - // cometdMessage); - // } catch (CometdException e) { - // LOG.error("publish delfinish cometdmsg fail.", e); - // } - // } + } catch (Exception e1) { + LOG.error("del instance csar fail.", e1); + updatePackageStatus(csarid, null, null, null, CommonConstant.PACKAGE_STATUS_DELETE_FAIL, + null); + // publishDelFinishCometdMessage(csarid, "false"); + } } - public Response updatePackageStatus(String csarId, String operationalState, String usageState, - String onBoardState, String processState, String deletionPending) { - LOG.info("update package status info.csarId:" + csarId + " operationalState:" - + operationalState); - if (ToolUtil.isEmptyString(csarId)) { - LOG.error("update csar status fail, csarid is null"); - return Response.serverError().build(); - } - try { - // UpdatePackageResponse result = new UpdatePackageResponse(); - SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - String currentTime = sdf1.format(new Date()); - PackageData packageInfo = new PackageData(); - if (operationalState != null) { - packageInfo.setOperationalState(operationalState); - } - if (usageState != null) { - packageInfo.setUsageState(usageState); - } - if (onBoardState != null) { - packageInfo.setOnBoardState(onBoardState); - } - if (processState != null) { - packageInfo.setProcessState(processState); - } - if (deletionPending != null) { - packageInfo.setDeletionPending(deletionPending); - } - packageInfo.setModifyTime(currentTime); - PackageManager.getInstance().updatePackage(packageInfo, csarId); - // ArrayList pacackgeList = PackageWrapperUtil.getPackageInfoById(csarId); - // String finalUsageState = pacackgeList.get(0).getUsageState(); - // result.setUsageState(finalUsageState); - return Response.ok().build(); - } catch (CatalogResourceException e) { - LOG.error("update package status by csarId from db error ! " + e.getMessage()); - return RestUtil.getRestException(e.getMessage()); - } + private void delCsarData(String csarId) { + updatePackageStatus(csarid, null, null, null, CommonConstant.PACKAGE_STATUS_DELETING, null); + String packagePath = PackageWrapperUtil.getPackagePath(csarId); + if (packagePath == null) { + LOG.error("package path is null! "); + return; + } + FileManagerFactory.createFileManager().delete(packagePath); + try { + PackageManager.getInstance().deletePackage(csarId); + } catch (CatalogResourceException e1) { + LOG.error("delete package by csarId from db error ! " + e1.getMessage()); + } + // delete template data from db + PackageData packageData = new PackageData(); + packageData.setCsarId(csarId); + try { + TemplateManager.getInstance().deleteServiceTemplateByCsarPackageInfo(packageData); + } catch (CatalogResourceException e2) { + LOG.error("delete template data from db error! csarId = " + csarId); + } + // publishDelFinishCometdMessage(csarid, "true"); } - public Response downloadCsarPackagesById(String csarId) { - ArrayList packageList = PackageWrapperUtil.getPackageInfoById(csarId); - String packageName = null; - if (null != packageList && packageList.size() > 0) { - packageName = packageList.get(0).getName(); - } - String path = ToolUtil.getCatalogueCsarPath() + File.separator + packageName; - File csarFile = new File(path); - if (!csarFile.exists()) { - return Response.status(Status.NOT_FOUND).build(); - } + // private void publishDelFinishCometdMessage(String csarid, String csarDelStatus) { + // if (isInstanceTemplate) { + // LOG.info("delete instance Template finish. csarid:{}", csarid); + // return; + // } + // try { + // Map cometdMessage = new HashMap(); + // cometdMessage.put("csarid", csarid); + // cometdMessage.put("status", csarDelStatus); + // CometdService.getInstance().publish(CommonConstant.COMETD_CHANNEL_PACKAGE_DELETE, + // cometdMessage); + // } catch (CometdException e) { + // LOG.error("publish delfinish cometdmsg fail.", e); + // } + // } + } - try { - InputStream fis = new BufferedInputStream(new FileInputStream(path)); - return Response - .ok(fis) - .header("Content-Disposition", - "attachment; filename=\"" + csarFile.getName() + "\"").build(); - } catch (Exception e) { - LOG.error("download vnf package fail.", e); - return RestUtil.getRestException(e.getMessage()); - } + /** + * update package status. + * @param csarId package id + * @param operationalState package operational state + * @param usageState package usage state + * @param onBoardState package onboard state + * @param processState package process state + * @param deletionPending package deletionPending status + * @return Response + */ + public Response updatePackageStatus(String csarId, String operationalState, String usageState, + String onBoardState, String processState, String deletionPending) { + LOG.info("update package status info.csarId:" + csarId + " operationalState:" + + operationalState); + if (ToolUtil.isEmptyString(csarId)) { + LOG.error("update csar status fail, csarid is null"); + return Response.serverError().build(); + } + try { + // UpdatePackageResponse result = new UpdatePackageResponse(); + PackageData packageInfo = new PackageData(); + if (operationalState != null) { + packageInfo.setOperationalState(operationalState); + } + if (usageState != null) { + packageInfo.setUsageState(usageState); + } + if (onBoardState != null) { + packageInfo.setOnBoardState(onBoardState); + } + if (processState != null) { + packageInfo.setProcessState(processState); + } + if (deletionPending != null) { + packageInfo.setDeletionPending(deletionPending); + } + SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String currentTime = sdf1.format(new Date()); + packageInfo.setModifyTime(currentTime); + PackageManager.getInstance().updatePackage(packageInfo, csarId); + // ArrayList pacackgeList = PackageWrapperUtil.getPackageInfoById(csarId); + // String finalUsageState = pacackgeList.get(0).getUsageState(); + // result.setUsageState(finalUsageState); + return Response.ok().build(); + } catch (CatalogResourceException e1) { + LOG.error("update package status by csarId from db error ! " + e1.getMessage()); + return RestUtil.getRestException(e1.getMessage()); } + } - public Response queryPackageListByCond(String name, String provider, String version, - String deletionPending, String type) { - ArrayList dbresult = new ArrayList(); - ArrayList result = new ArrayList(); - LOG.info("query package info.name:" + name + " provider:" + provider + " version" + version - + " deletionPending" + deletionPending + " type:" + type); - try { - dbresult = - PackageManager.getInstance().queryPackage(name, provider, version, - deletionPending, type); - result = PackageWrapperUtil.packageDataList2PackageMetaList(dbresult); - return Response.ok(result).build(); - } catch (CatalogResourceException e) { - LOG.error("query package by csarId from db error ! " + e.getMessage()); - return RestUtil.getRestException(e.getMessage()); - } + /** + * download package by package id. + * @param csarId package id + * @return Response + */ + public Response downloadCsarPackagesById(String csarId) { + ArrayList packageList = PackageWrapperUtil.getPackageInfoById(csarId); + String packageName = null; + if (null != packageList && packageList.size() > 0) { + packageName = packageList.get(0).getName(); + } + String path = ToolUtil.getCatalogueCsarPath() + File.separator + packageName; + File csarFile = new File(path); + if (!csarFile.exists()) { + return Response.status(Status.NOT_FOUND).build(); } - public Response getCsarFileUri(String csarId, String relativePath) { - try { - CsarFileUriResponse result = getCsarFileDownloadUri(csarId, relativePath); - return Response.ok(result).build(); - } catch (CatalogResourceException e) { - LOG.error("Query CSAR package by ID failed ! csarId = " + csarId); - } + try { + InputStream fis = new BufferedInputStream(new FileInputStream(path)); + return Response.ok(fis) + .header("Content-Disposition", "attachment; filename=\"" + csarFile.getName() + "\"") + .build(); + } catch (Exception e1) { + LOG.error("download vnf package fail.", e1); + return RestUtil.getRestException(e1.getMessage()); + } + } - return Response.serverError().build(); + /** + * query package list by condition. + * @param name package name + * @param provider package provider + * @param version package version + * @param deletionPending package deletionPending + * @param type package type + * @return Response + */ + public Response queryPackageListByCond(String name, String provider, String version, + String deletionPending, String type) { + ArrayList dbresult = new ArrayList(); + ArrayList result = new ArrayList(); + LOG.info("query package info.name:" + name + " provider:" + provider + " version" + version + + " deletionPending" + deletionPending + " type:" + type); + try { + dbresult = + PackageManager.getInstance().queryPackage(name, provider, version, deletionPending, type); + result = PackageWrapperUtil.packageDataList2PackageMetaList(dbresult); + return Response.ok(result).build(); + } catch (CatalogResourceException e1) { + LOG.error("query package by csarId from db error ! " + e1.getMessage()); + return RestUtil.getRestException(e1.getMessage()); } + } - public CsarFileUriResponse getCsarFileDownloadUri(String csarId, String relativePath) - throws CatalogResourceException { - CsarFileUriResponse result = new CsarFileUriResponse(); - String downloadUrl = null; - String downloadUri = null; - String localPath = null; - ArrayList packageList = - PackageManager.getInstance().queryPackageByCsarId(csarId); - if (packageList != null && packageList.size() != 0) { - String packageName = packageList.get(0).getName(); - String relativeUri = packageList.get(0).getDownloadUri() + packageName; - downloadUri = relativeUri + relativePath; - downloadUrl = PackageWrapperUtil.getUrl(downloadUri); - String httpUri = HttpServerPathConfig.getHttpServerPath() + downloadUri; - localPath = PackageWrapperUtil.getLocalPath(httpUri); - } - result.setDownloadUri(downloadUrl); - result.setLocalPath(localPath); - return result; + /** + * get package file uri. + * @param csarId package id + * @param relativePath file relative path + * @return Response + */ + public Response getCsarFileUri(String csarId, String relativePath) { + try { + CsarFileUriResponse result = getCsarFileDownloadUri(csarId, relativePath); + return Response.ok(result).build(); + } catch (CatalogResourceException e1) { + LOG.error("Query CSAR package by ID failed ! csarId = " + csarId); } - /** - * @param ftpUrl - * @param packageName - * @return - */ - public Response uploadPackageFromFtp(UploadPackageFromFtpRequest request) { - PackageBasicInfo basicInfo = new PackageBasicInfo(); - String tempDirName = null; - String fileName = ""; - UploadPackageResponse result = new UploadPackageResponse(); - basicInfo.setProvider("zte"); - basicInfo.setType(EnumType.NSAR); - basicInfo.setVersion("v1.0"); - PackageMeta packageMeta = new PackageMeta(); + return Response.serverError().build(); + } - try { - String ftpUrl = request.getFtpUrl(); - String packageName = PackageWrapperUtil.getPackageName(ftpUrl); - fileName = ToolUtil.processFileName(packageName); - tempDirName = ToolUtil.getTempDir(CommonConstant.CATALOG_CSAR_DIR_NAME, fileName); - PackageWrapperUtil.downPackageFromFtp(ftpUrl, tempDirName); - String path = - basicInfo.getType().toString() + File.separator + basicInfo.getProvider() - + File.separator + fileName.replace(".csar", "") + File.separator - + basicInfo.getVersion(); - LOG.info("dest path is : " + path); - packageMeta = PackageWrapperUtil.getPackageMeta(fileName, tempDirName, basicInfo); - String dowloadUri = File.separator + path + File.separator + fileName; - packageMeta.setDownloadUri(dowloadUri); - LOG.info("packageMeta = " + ToolUtil.objectToString(packageMeta)); - String destPath = File.separator + path; - boolean uploadResult = - FileManagerFactory.createFileManager().upload(tempDirName, destPath); - if (uploadResult == true) { - String newZipPath = tempDirName + fileName.replace(".csar", ".zip"); - ZipCompressor zc = new ZipCompressor(newZipPath); - String metadataPath = tempDirName + File.separator + CommonConstant.TOSCA_METADATA; - String definitions = tempDirName + File.separator + CommonConstant.DEFINITIONS; - zc.compress(metadataPath, definitions); - // 调袁虎的接口,将fileLocation 和 packageId传给他,由他去解析包,并向数据库存储数据 - String parseResult = - ModelParserFactory.getInstance().parse(packageMeta.getCsarId(), newZipPath, - EnumPackageFormat.valueOf(packageMeta.getFormat())); - PackageData packageData = PackageWrapperUtil.getPackageData(packageMeta); - PackageManager.getInstance().addPackage(packageData); - } - LOG.info("upload package file end, fileName:" + fileName); - result.setCsarId(packageMeta.getCsarId()); - return Response.ok(result).build(); - } catch (Exception e) { - LOG.error("upload package fail.", e); - String csarId = packageMeta.getCsarId(); - if (csarId != null) { - try { - PackageManager.getInstance().deletePackage(csarId); - } catch (CatalogResourceException e1) { - LOG.error("delete package failed !"); - } - } - return RestUtil.getRestException(e.getMessage()); - } finally { - if (tempDirName != null) { - ToolUtil.deleteDir(new File(tempDirName)); - } - } + /** + * get package file download uri. + * @param csarId package id + * @param relativePath package file relative path + * @return CsarFileUriResponse + * @throws CatalogResourceException + */ + public CsarFileUriResponse getCsarFileDownloadUri(String csarId, String relativePath) + throws CatalogResourceException { + CsarFileUriResponse result = new CsarFileUriResponse(); + String downloadUrl = null; + String downloadUri = null; + String localPath = null; + ArrayList packageList = PackageManager.getInstance().queryPackageByCsarId(csarId); + if (packageList != null && packageList.size() != 0) { + String packageName = packageList.get(0).getName(); + String relativeUri = packageList.get(0).getDownloadUri() + packageName; + downloadUri = relativeUri + relativePath; + downloadUrl = PackageWrapperUtil.getUrl(downloadUri); + String httpUri = HttpServerPathConfig.getHttpServerPath() + downloadUri; + localPath = PackageWrapperUtil.getLocalPath(httpUri); } + result.setDownloadUri(downloadUrl); + result.setLocalPath(localPath); + return result; + } - public Response getCsarPlansUri(String csarId) { - ArrayList fileLinks = new ArrayList(); - LOG.info("start query plans of package.csarId:" + csarId); - ArrayList packageList = new ArrayList(); + /** + * upload package from ftp. + * @param request package basic information + * @return Response + */ + public Response uploadPackageFromFtp(UploadPackageFromFtpRequest request) { + PackageBasicInfo basicInfo = new PackageBasicInfo(); + String tempDirName = null; + String fileName = ""; + UploadPackageResponse result = new UploadPackageResponse(); + basicInfo.setProvider("zte"); + basicInfo.setType(EnumType.NSAR); + basicInfo.setVersion("v1.0"); + PackageMeta packageMeta = new PackageMeta(); + + try { + String ftpUrl = request.getFtpUrl(); + String packageName = PackageWrapperUtil.getPackageName(ftpUrl); + fileName = ToolUtil.processFileName(packageName); + tempDirName = ToolUtil.getTempDir(CommonConstant.CATALOG_CSAR_DIR_NAME, fileName); + PackageWrapperUtil.downPackageFromFtp(ftpUrl, tempDirName); + String path = + basicInfo.getType().toString() + File.separator + basicInfo.getProvider() + + File.separator + fileName.replace(".csar", "") + File.separator + + basicInfo.getVersion(); + LOG.info("dest path is : " + path); + packageMeta = PackageWrapperUtil.getPackageMeta(fileName, tempDirName, basicInfo); + String dowloadUri = File.separator + path + File.separator + fileName; + packageMeta.setDownloadUri(dowloadUri); + LOG.info("packageMeta = " + ToolUtil.objectToString(packageMeta)); + String destPath = File.separator + path; + boolean uploadResult = FileManagerFactory.createFileManager().upload(tempDirName, destPath); + if (uploadResult == true) { + String newZipPath = tempDirName + fileName.replace(".csar", ".zip"); + ZipCompressor zc = new ZipCompressor(newZipPath); + String metadataPath = tempDirName + File.separator + CommonConstant.TOSCA_METADATA; + String definitions = tempDirName + File.separator + CommonConstant.DEFINITIONS; + zc.compress(metadataPath, definitions); + // 调袁虎的接口,将fileLocation 和 packageId传给他,由他去解析包,并向数据库存储数据 +// String parseResult = + ModelParserFactory.getInstance().parse(packageMeta.getCsarId(), newZipPath, + EnumPackageFormat.valueOf(packageMeta.getFormat())); + PackageData packageData = PackageWrapperUtil.getPackageData(packageMeta); + PackageManager.getInstance().addPackage(packageData); + } + LOG.info("upload package file end, fileName:" + fileName); + result.setCsarId(packageMeta.getCsarId()); + return Response.ok(result).build(); + } catch (Exception e1) { + LOG.error("upload package fail.", e1); + String csarId = packageMeta.getCsarId(); + if (csarId != null) { try { - packageList = PackageManager.getInstance().queryPackageByCsarId(csarId); - if (packageList != null && packageList.size() != 0) { - String downloadUri = packageList.get(0).getDownloadUri(); - fileLinks = FileManagerFactory.createFileManager().queryWorkFlow(downloadUri); - } - return Response.ok(fileLinks).build(); - } catch (CatalogResourceException e) { - LOG.error("Query plans of package by ID failed ! csarId = " + csarId); - return RestUtil.getRestException(e.getMessage()); + PackageManager.getInstance().deletePackage(csarId); + } catch (CatalogResourceException e2) { + LOG.error("delete package failed !"); } - // return Response.serverError().build(); + } + return RestUtil.getRestException(e1.getMessage()); + } finally { + if (tempDirName != null) { + ToolUtil.deleteDir(new File(tempDirName)); + } + } + } + + /** + * get csar plan uri. + * @param csarId package id + * @return Response + */ + public Response getCsarPlansUri(String csarId) { + ArrayList fileLinks = new ArrayList(); + LOG.info("start query plans of package.csarId:" + csarId); + ArrayList packageList = new ArrayList(); + try { + packageList = PackageManager.getInstance().queryPackageByCsarId(csarId); + if (packageList != null && packageList.size() != 0) { + String downloadUri = packageList.get(0).getDownloadUri(); + fileLinks = FileManagerFactory.createFileManager().queryWorkFlow(downloadUri); + } + return Response.ok(fileLinks).build(); + } catch (CatalogResourceException e1) { + LOG.error("Query plans of package by ID failed ! csarId = " + csarId); + return RestUtil.getRestException(e1.getMessage()); } + // return Response.serverError().build(); + } } diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/wrapper/PackageWrapperUtil.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/wrapper/PackageWrapperUtil.java index ed20c14c..9656cb6d 100644 --- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/wrapper/PackageWrapperUtil.java +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/wrapper/PackageWrapperUtil.java @@ -38,16 +38,16 @@ import org.openo.commontosca.catalog.entity.EnumType; import org.openo.commontosca.catalog.entity.request.PackageBasicInfo; import org.openo.commontosca.catalog.ftp.Ftp; import org.openo.commontosca.catalog.model.entity.ServiceTemplate; +import org.openo.commontosca.catalog.model.externalservice.entity.lifecycle.InstanceEntity; import org.openo.commontosca.catalog.model.externalservice.lifecycle.LifeCycleServiceConsumer; import org.openo.commontosca.catalog.common.ToolUtil; import org.openo.commontosca.catalog.db.entity.PackageData; -import org.openo.commontosca.catalog.entity.CSARPackage; +import org.openo.commontosca.catalog.entity.CsarPackage; import org.openo.commontosca.catalog.entity.EnumOnboardState; import org.openo.commontosca.catalog.entity.EnumOperationalState; import org.openo.commontosca.catalog.entity.EnumUsageState; import org.openo.commontosca.catalog.entity.response.PackageMeta; import org.openo.commontosca.catalog.ftp.FtpUtil; -import org.openo.commontosca.catalog.model.externalservice.entity.lifecycleEnity.InstanceEntity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -59,357 +59,356 @@ import com.google.gson.reflect.TypeToken; * */ public class PackageWrapperUtil { - private static final Logger LOG = LoggerFactory.getLogger(PackageWrapperUtil.class); + private static final Logger LOG = LoggerFactory.getLogger(PackageWrapperUtil.class); - public static List formJson2Packages(String packageJson) { - List packageList = - new Gson().fromJson(packageJson, new TypeToken>() {}.getType()); - if (null == packageList || packageList.size() == 0) { - throw new NotFoundException("Package do not exist"); - } - return packageList; + public static List formJson2Packages(String packageJson) { + List packageList = + new Gson().fromJson(packageJson, new TypeToken>() {}.getType()); + if (null == packageList || packageList.size() == 0) { + throw new NotFoundException("Package do not exist"); } + return packageList; + } - public static long getPacakgeSize(String fileLocation) { - File file = new File(fileLocation); - return file.length(); - } + public static long getPacakgeSize(String fileLocation) { + File file = new File(fileLocation); + return file.length(); + } - public static PackageData getPackageData(PackageMeta meta) { - PackageData packageData = new PackageData(); - packageData.setCreateTime(meta.getCreateTime()); - packageData.setDeletionPending(String.valueOf(meta.isDeletionPending())); - packageData.setDownloadUri(meta.getDownloadUri()); - packageData.setFormat(meta.getFormat()); - packageData.setModifyTime(meta.getModifyTime()); - packageData.setName(meta.getName()); - packageData.setCsarId(meta.getCsarId()); - packageData.setOperationalState(meta.getOperationalState().toString()); - packageData.setProvider(meta.getProvider()); - String fileSize = meta.getSize(); - packageData.setSize(fileSize); - packageData.setType(meta.getType()); - packageData.setUsageState(meta.getUsageState().toString()); - packageData.setVersion(meta.getVersion()); - packageData.setOnBoardState(meta.getOnBoardState()); - packageData.setProcessState(meta.getProcessState().toString()); - return packageData; - } + public static PackageData getPackageData(PackageMeta meta) { + PackageData packageData = new PackageData(); + packageData.setCreateTime(meta.getCreateTime()); + packageData.setDeletionPending(String.valueOf(meta.isDeletionPending())); + packageData.setDownloadUri(meta.getDownloadUri()); + packageData.setFormat(meta.getFormat()); + packageData.setModifyTime(meta.getModifyTime()); + packageData.setName(meta.getName()); + packageData.setCsarId(meta.getCsarId()); + packageData.setOperationalState(meta.getOperationalState().toString()); + packageData.setProvider(meta.getProvider()); + String fileSize = meta.getSize(); + packageData.setSize(fileSize); + packageData.setType(meta.getType()); + packageData.setUsageState(meta.getUsageState().toString()); + packageData.setVersion(meta.getVersion()); + packageData.setOnBoardState(meta.getOnBoardState()); + packageData.setProcessState(meta.getProcessState().toString()); + return packageData; + } - public static boolean isUploadEnd(String contentRange, String csarName) { - String range = contentRange; - range = range.replace("bytes", "").trim(); - range = range.substring(0, range.indexOf("/")); - String size = - contentRange.substring(contentRange.indexOf("/") + 1, contentRange.length()).trim(); - int fileSize = Integer.parseInt(size); - String[] ranges = range.split("-"); - int startPosition = Integer.parseInt(ranges[0]); - if (startPosition == 0) { - // delPackageBySync(csarName); - } - // index start from 0 - int endPosition = Integer.parseInt(ranges[1]) + 1; - if (endPosition >= fileSize) { - return true; - } - return false; + public static boolean isUploadEnd(String contentRange, String csarName) { + String range = contentRange; + range = range.replace("bytes", "").trim(); + range = range.substring(0, range.indexOf("/")); + String size = + contentRange.substring(contentRange.indexOf("/") + 1, contentRange.length()).trim(); + int fileSize = Integer.parseInt(size); + String[] ranges = range.split("-"); + int startPosition = Integer.parseInt(ranges[0]); + if (startPosition == 0) { + // delPackageBySync(csarName); } - - public static ArrayList getPackageInfoById(String csarId) { - ArrayList result = new ArrayList(); - try { - result = PackageManager.getInstance().queryPackageByCsarId(csarId); - } catch (CatalogResourceException e) { - LOG.error("query package by csarId from db error ! " + e.getMessage()); - } - return result; + // index start from 0 + int endPosition = Integer.parseInt(ranges[1]) + 1; + if (endPosition >= fileSize) { + return true; } + return false; + } - public static PackageMeta getPackageMeta(String fileName, String fileLocation, - PackageBasicInfo basic) { - PackageMeta packageMeta = new PackageMeta(); - long size = getPacakgeSize(fileLocation); - packageMeta.setFormat(basic.getFormat()); - String packageId = ToolUtil.generateId(); - packageMeta.setName(fileName.replace(CommonConstant.CSAR_SUFFIX, "")); - packageMeta.setCsarId(packageId); - packageMeta.setType(basic.getType().toString()); - packageMeta.setVersion(basic.getVersion()); - packageMeta.setProvider(basic.getProvider()); - packageMeta.setDeletionPending(false); - String sizeStr = ToolUtil.formatFileSize(size); - packageMeta.setSize(sizeStr); - SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - String currentTime = sdf1.format(new Date()); - packageMeta.setCreateTime(currentTime); - packageMeta.setModifyTime(currentTime); - packageMeta.setOperationalState(EnumOperationalState.Disabled); - packageMeta.setUsageState(EnumUsageState.NotInUse); - packageMeta.setOnBoardState(EnumOnboardState.nonOnBoarded.getValue()); - packageMeta.setProcessState(EnumProcessState.normal); - return packageMeta; + public static ArrayList getPackageInfoById(String csarId) { + ArrayList result = new ArrayList(); + try { + result = PackageManager.getInstance().queryPackageByCsarId(csarId); + } catch (CatalogResourceException e) { + LOG.error("query package by csarId from db error ! " + e.getMessage()); } + return result; + } - public static String getPackagePath(String csarId) { - ArrayList packageList = new ArrayList(); - String downloadUri = null; - try { - packageList = PackageManager.getInstance().queryPackageByCsarId(csarId); - downloadUri = packageList.get(0).getDownloadUri(); - } catch (CatalogResourceException e) { - LOG.error("Query CSAR package by ID failed ! csarId = " + csarId); - } - return downloadUri; + public static PackageMeta getPackageMeta(String fileName, String fileLocation, + PackageBasicInfo basic) { + PackageMeta packageMeta = new PackageMeta(); + long size = getPacakgeSize(fileLocation); + packageMeta.setFormat(basic.getFormat()); + String packageId = ToolUtil.generateId(); + packageMeta.setName(fileName.replace(CommonConstant.CSAR_SUFFIX, "")); + packageMeta.setCsarId(packageId); + packageMeta.setType(basic.getType().toString()); + packageMeta.setVersion(basic.getVersion()); + packageMeta.setProvider(basic.getProvider()); + packageMeta.setDeletionPending(false); + String sizeStr = ToolUtil.getFormatFileSize(size); + packageMeta.setSize(sizeStr); + SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String currentTime = sdf1.format(new Date()); + packageMeta.setCreateTime(currentTime); + packageMeta.setModifyTime(currentTime); + packageMeta.setOperationalState(EnumOperationalState.Disabled); + packageMeta.setUsageState(EnumUsageState.NotInUse); + packageMeta.setOnBoardState(EnumOnboardState.nonOnBoarded.getValue()); + packageMeta.setProcessState(EnumProcessState.normal); + return packageMeta; + } + + public static String getPackagePath(String csarId) { + ArrayList packageList = new ArrayList(); + String downloadUri = null; + try { + packageList = PackageManager.getInstance().queryPackageByCsarId(csarId); + downloadUri = packageList.get(0).getDownloadUri(); + } catch (CatalogResourceException e) { + LOG.error("Query CSAR package by ID failed ! csarId = " + csarId); } + return downloadUri; + } - public static HashSet instanceConvertToHashSet(ArrayList instancelist) { - HashSet result = new HashSet(); - if (instancelist != null) { - for (InstanceEntity instance : instancelist) { - result.add(instance.getServiceTemplateId()); - } - } - return result; + public static HashSet instanceConvertToHashSet(ArrayList instancelist) { + HashSet result = new HashSet(); + if (instancelist != null) { + for (InstanceEntity instance : instancelist) { + result.add(instance.getServiceTemplateId()); + } } + return result; + } - public static boolean isExistInstanceCSAR(String csarId) throws CometdException { - // 查询各O(GSO、NFVO、SDNO)的资源实例数据库,查询指定csarId对应的服务模版 - ArrayList templateList = queryAvailableTemplatesByCsar(csarId); - // 调生命周期的接口查询所有实例,查询实例中是否包含指定csarId对应的服务模析ID - HashSet templateSet = - instanceConvertToHashSet(LifeCycleServiceConsumer.getInstances()); - if (templateList != null && templateList.size() > 0 && templateSet.size() > 0) { - for (ServiceTemplate temp : templateList) { - if (templateSet.contains(temp.getServiceTemplateId())) { - return true; - } - } + public static boolean isExistInstanceCSAR(String csarId) throws CometdException { + // 查询各O(GSO、NFVO、SDNO)的资源实例数据库,查询指定csarId对应的服务模版 + ArrayList templateList = queryAvailableTemplatesByCsar(csarId); + // 调生命周期的接口查询所有实例,查询实例中是否包含指定csarId对应的服务模析ID + HashSet templateSet = instanceConvertToHashSet(LifeCycleServiceConsumer.getInstances()); + if (templateList != null && templateList.size() > 0 && templateSet.size() > 0) { + for (ServiceTemplate temp : templateList) { + if (templateSet.contains(temp.getServiceTemplateId())) { + return true; } - return false; + } } + return false; + } - public static ArrayList queryAvailableTemplatesByCsar(String csarId) { - return null; - // ArrayList resultlist = new ArrayList(); - // String filter = LDAPUtil.getObjectClassFilter(LDAPConstant.OBJECTCLASS_CSAR); - // String result = - // LDAPDataFactory.getInstance().queryData(EnumLDAPData.SERVICETEMPLATE, null, false, - // filter); - // Type type = new TypeToken>() {}.getType(); - // ArrayList templateList = new Gson().fromJson(result, type); - // for (ServiceTemplate temp : templateList) { - // if (temp.getCsarid().equals(csarId)) { - // resultlist.add(temp); - // } - // } - // return resultlist; - } - - // public static void publishDeletionPendingStatusCometdMessage(String csarid) { - // try { - // Map cometdMessage = new HashMap(); - // cometdMessage.put("csarid", csarid); - // cometdMessage.put("status", "deletionPending"); - // CometdService.getInstance().publish(CommonConstant.COMETD_CHANNEL_PACKAGE_DELETE, - // cometdMessage); - // } catch (CometdException e) { - // LOG.error("publish delfinish cometdmsg fail.", e); + public static ArrayList queryAvailableTemplatesByCsar(String csarId) { + return null; + // ArrayList resultlist = new ArrayList(); + // String filter = LDAPUtil.getObjectClassFilter(LDAPConstant.OBJECTCLASS_CSAR); + // String result = + // LDAPDataFactory.getInstance().queryData(EnumLDAPData.SERVICETEMPLATE, null, false, + // filter); + // Type type = new TypeToken>() {}.getType(); + // ArrayList templateList = new Gson().fromJson(result, type); + // for (ServiceTemplate temp : templateList) { + // if (temp.getCsarid().equals(csarId)) { + // resultlist.add(temp); // } // } + // return resultlist; + } - /** - * @param ftpUrl - * @return - */ - public static Ftp getFtpDetail(String ftpUrl) { - Ftp ftp = new Ftp(); - int index1 = ftpUrl.indexOf("ftp://"); - int index2 = ftpUrl.indexOf("@"); - String userPassSubString = ftpUrl.substring(index1, index2); - int index3 = userPassSubString.indexOf(":"); - String userName = userPassSubString.substring(0, index3); - String pass = userPassSubString.substring(index3 + 1); - String subString1 = ftpUrl.substring(index2 + 1); - int index4 = subString1.indexOf("/"); - String ipPortSubString = subString1.substring(0, index4); - int index5 = ipPortSubString.indexOf(":"); - String ip = ipPortSubString.substring(0, index5); - String port = ipPortSubString.substring(index5 + 1); - int index6 = ftpUrl.lastIndexOf("/"); - String path = ftpUrl.substring(0, index6); - ftp.setIpAddr(ip); - ftp.setPath(path); - ftp.setPort(Integer.valueOf(port)); - ftp.setPwd(pass); - ftp.setUserName(userName); - return ftp; - } + // public static void publishDeletionPendingStatusCometdMessage(String csarid) { + // try { + // Map cometdMessage = new HashMap(); + // cometdMessage.put("csarid", csarid); + // cometdMessage.put("status", "deletionPending"); + // CometdService.getInstance().publish(CommonConstant.COMETD_CHANNEL_PACKAGE_DELETE, + // cometdMessage); + // } catch (CometdException e) { + // LOG.error("publish delfinish cometdmsg fail.", e); + // } + // } - /** - * @param ftpUrl - * @return - */ - // public static String getFtpDir(String ftpUrl) { - // // TODO Auto-generated method stub - // return null; - // } + /** + * @param ftpUrl + * @return + */ + public static Ftp getFtpDetail(String ftpUrl) { + Ftp ftp = new Ftp(); + int index1 = ftpUrl.indexOf("ftp://"); + int index2 = ftpUrl.indexOf("@"); + String userPassSubString = ftpUrl.substring(index1, index2); + int index3 = userPassSubString.indexOf(":"); + String userName = userPassSubString.substring(0, index3); + String pass = userPassSubString.substring(index3 + 1); + String subString1 = ftpUrl.substring(index2 + 1); + int index4 = subString1.indexOf("/"); + String ipPortSubString = subString1.substring(0, index4); + int index5 = ipPortSubString.indexOf(":"); + String ip = ipPortSubString.substring(0, index5); + String port = ipPortSubString.substring(index5 + 1); + int index6 = ftpUrl.lastIndexOf("/"); + String path = ftpUrl.substring(0, index6); + ftp.setIpAddr(ip); + ftp.setPath(path); + ftp.setPort(Integer.valueOf(port)); + ftp.setPwd(pass); + ftp.setUserName(userName); + return ftp; + } - /** - * @param ftpUrl - * @return - */ - public static String getPackageName(String ftpUrl) { - int index = ftpUrl.lastIndexOf("/"); - String packageName = ftpUrl.substring(index); - return packageName; - } + /** + * @param ftpUrl + * @return + */ + // public static String getFtpDir(String ftpUrl) { + // // TODO Auto-generated method stub + // return null; + // } - public static void downPackageFromFtp(String ftpUrl, String tempDirName) { - Ftp ftp = new Ftp(); - ftp = PackageWrapperUtil.getFtpDetail(ftpUrl); - String remoteBaseDir = ftp.getPath(); - try { - FtpUtil.startDown(ftp, tempDirName, remoteBaseDir); - } catch (Exception e) { - LOG.error("Down package from ftp failed !"); - } - } + /** + * @param ftpUrl + * @return + */ + public static String getPackageName(String ftpUrl) { + int index = ftpUrl.lastIndexOf("/"); + String packageName = ftpUrl.substring(index); + return packageName; + } - /** - * @param dbResult - * @return - */ - public static ArrayList packageDataList2PackageMetaList( - ArrayList dbResult) { - ArrayList metas = new ArrayList(); - PackageMeta meta = new PackageMeta(); - for (int i = 0; i < dbResult.size(); i++) { - PackageData data = dbResult.get(i); - meta = packageData2PackageMeta(data); - metas.add(meta); - } - return metas; - } - - public static EnumOnboardState getEnumByValue(String value) { - if(value == "non-onBoarded") { - return EnumOnboardState.nonOnBoarded; - } else { - return EnumOnboardState.onBoarded; - } + public static void downPackageFromFtp(String ftpUrl, String tempDirName) { + Ftp ftp = new Ftp(); + ftp = PackageWrapperUtil.getFtpDetail(ftpUrl); + String remoteBaseDir = ftp.getPath(); + try { + FtpUtil.startDown(ftp, tempDirName, remoteBaseDir); + } catch (Exception e) { + LOG.error("Down package from ftp failed !"); } + } - private static PackageMeta packageData2PackageMeta(PackageData packageData) { - PackageMeta meta = new PackageMeta(); - meta.setCsarId(packageData.getCsarId()); - meta.setCreateTime(packageData.getCreateTime()); - meta.setDeletionPending(Boolean.getBoolean(packageData.getDeletionPending())); - String packageUri = - packageData.getDownloadUri() + packageData.getName() + CommonConstant.CSAR_SUFFIX; - String packageUrl = getUrl(packageUri); - meta.setDownloadUri(packageUrl); - meta.setFormat(packageData.getFormat()); - meta.setModifyTime(packageData.getModifyTime()); - meta.setName(packageData.getName()); - meta.setOperationalState(EnumOperationalState.valueOf(packageData.getOperationalState())); - meta.setProvider(packageData.getProvider()); - meta.setSize(packageData.getSize()); - meta.setType(packageData.getType()); - meta.setUsageState(EnumUsageState.valueOf(packageData.getUsageState())); - meta.setVersion(packageData.getVersion()); - meta.setOnBoardState(packageData.getOnBoardState()); - meta.setProcessState(EnumProcessState.valueOf(packageData.getProcessState())); - return meta; + /** + * @param dbResult + * @return + */ + public static ArrayList packageDataList2PackageMetaList( + ArrayList dbResult) { + ArrayList metas = new ArrayList(); + PackageMeta meta = new PackageMeta(); + for (int i = 0; i < dbResult.size(); i++) { + PackageData data = dbResult.get(i); + meta = packageData2PackageMeta(data); + metas.add(meta); } + return metas; + } - public static String getUrl(String uri) { - String url = null; - if ((MsbAddrConfig.getMsbAddress().endsWith("/")) && uri.startsWith("/")) { - url = MsbAddrConfig.getMsbAddress() + uri.substring(1); - } - url = MsbAddrConfig.getMsbAddress() + uri; - String urlresult = url.replace("\\", "/"); - return urlresult; + public static EnumOnboardState getEnumByValue(String value) { + if (value == "non-onBoarded") { + return EnumOnboardState.nonOnBoarded; + } else { + return EnumOnboardState.onBoarded; } + } - public static String getLocalPath(String uri) { - File srcDir = new File(uri); - String localPath = srcDir.getAbsolutePath(); - return localPath.replace("\\", "/"); + private static PackageMeta packageData2PackageMeta(PackageData packageData) { + PackageMeta meta = new PackageMeta(); + meta.setCsarId(packageData.getCsarId()); + meta.setCreateTime(packageData.getCreateTime()); + meta.setDeletionPending(Boolean.getBoolean(packageData.getDeletionPending())); + String packageUri = + packageData.getDownloadUri() + packageData.getName() + CommonConstant.CSAR_SUFFIX; + String packageUrl = getUrl(packageUri); + meta.setDownloadUri(packageUrl); + meta.setFormat(packageData.getFormat()); + meta.setModifyTime(packageData.getModifyTime()); + meta.setName(packageData.getName()); + meta.setOperationalState(EnumOperationalState.valueOf(packageData.getOperationalState())); + meta.setProvider(packageData.getProvider()); + meta.setSize(packageData.getSize()); + meta.setType(packageData.getType()); + meta.setUsageState(EnumUsageState.valueOf(packageData.getUsageState())); + meta.setVersion(packageData.getVersion()); + meta.setOnBoardState(packageData.getOnBoardState()); + meta.setProcessState(EnumProcessState.valueOf(packageData.getProcessState())); + return meta; + } + + public static String getUrl(String uri) { + String url = null; + if ((MsbAddrConfig.getMsbAddress().endsWith("/")) && uri.startsWith("/")) { + url = MsbAddrConfig.getMsbAddress() + uri.substring(1); } + url = MsbAddrConfig.getMsbAddress() + uri; + String urlresult = url.replace("\\", "/"); + return urlresult; + } - /** - * @param fileLocation - * @return - */ - public static PackageBasicInfo getPacageBasicInfo(String fileLocation) { - PackageBasicInfo basicInfo = new PackageBasicInfo(); - String unzipDir = ToolUtil.getUnzipDir(fileLocation); - boolean isXmlCsar = false; - try { - String tempfolder = unzipDir; - ArrayList unzipFiles = FileUtil.unzip(fileLocation, tempfolder); - if (unzipFiles.isEmpty()) { - isXmlCsar = true; - } - for (String unzipFile : unzipFiles) { - if (unzipFile.endsWith(CommonConstant.CSAR_META)) { - basicInfo = readCsarMeta(unzipFile); - } - if (ToolUtil.isYamlFile(new File(unzipFile))) { - isXmlCsar = false; - } - } - } catch (IOException e) { - LOG.error("judge package type error !"); + public static String getLocalPath(String uri) { + File srcDir = new File(uri); + String localPath = srcDir.getAbsolutePath(); + return localPath.replace("\\", "/"); + } + + /** + * @param fileLocation + * @return + */ + public static PackageBasicInfo getPacageBasicInfo(String fileLocation) { + PackageBasicInfo basicInfo = new PackageBasicInfo(); + String unzipDir = ToolUtil.getUnzipDir(fileLocation); + boolean isXmlCsar = false; + try { + String tempfolder = unzipDir; + ArrayList unzipFiles = FileUtil.unzip(fileLocation, tempfolder); + if (unzipFiles.isEmpty()) { + isXmlCsar = true; + } + for (String unzipFile : unzipFiles) { + if (unzipFile.endsWith(CommonConstant.CSAR_META)) { + basicInfo = readCsarMeta(unzipFile); } - if (isXmlCsar) { - basicInfo.setFormat(CommonConstant.PACKAGE_XML_FORMAT); - } else { - basicInfo.setFormat(CommonConstant.PACKAGE_YAML_FORMAT); + if (ToolUtil.isYamlFile(new File(unzipFile))) { + isXmlCsar = false; } - return basicInfo; + } + } catch (IOException e) { + LOG.error("judge package type error !"); + } + if (isXmlCsar) { + basicInfo.setFormat(CommonConstant.PACKAGE_XML_FORMAT); + } else { + basicInfo.setFormat(CommonConstant.PACKAGE_YAML_FORMAT); } + return basicInfo; + } - /** - * @param unzipFile - * @return - */ - private static PackageBasicInfo readCsarMeta(String unzipFile) { - PackageBasicInfo basicInfo = new PackageBasicInfo(); - File file = new File(unzipFile); - BufferedReader reader = null; + /** + * @param unzipFile + * @return + */ + private static PackageBasicInfo readCsarMeta(String unzipFile) { + PackageBasicInfo basicInfo = new PackageBasicInfo(); + File file = new File(unzipFile); + BufferedReader reader = null; + try { + reader = new BufferedReader(new FileReader(file)); + String tempString = null; + while ((tempString = reader.readLine()) != null) { + if (tempString.startsWith(CommonConstant.CSAR_TYPE_META)) { + int count = tempString.indexOf(":") + 1; + basicInfo.setType(EnumType.valueOf(tempString.substring(count))); + } + if (tempString.startsWith(CommonConstant.CSAR_PROVIDER_META)) { + int count = tempString.indexOf(":") + 1; + basicInfo.setProvider(tempString.substring(count)); + } + if (tempString.startsWith(CommonConstant.CSAR_VERSION_META)) { + int count = tempString.indexOf(":") + 1; + basicInfo.setVersion(tempString.substring(count)); + } + } + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (reader != null) { try { - reader = new BufferedReader(new FileReader(file)); - String tempString = null; - while ((tempString = reader.readLine()) != null) { - if (tempString.startsWith(CommonConstant.CSAR_TYPE_META)) { - int count = tempString.indexOf(":") + 1; - basicInfo.setType(EnumType.valueOf(tempString.substring(count))); - } - if (tempString.startsWith(CommonConstant.CSAR_PROVIDER_META)) { - int count = tempString.indexOf(":") + 1; - basicInfo.setProvider(tempString.substring(count)); - } - if (tempString.startsWith(CommonConstant.CSAR_VERSION_META)) { - int count = tempString.indexOf(":") + 1; - basicInfo.setVersion(tempString.substring(count)); - } - } - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException e1) { - } - } + reader.close(); + } catch (IOException e1) { } - return basicInfo; + } } + return basicInfo; + } } diff --git a/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/resource/IntegrationManager.java b/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/resource/IntegrationManager.java index 8e212103..f0b27bf6 100644 --- a/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/resource/IntegrationManager.java +++ b/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/resource/IntegrationManager.java @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.resource; -import java.util.ArrayList; import org.junit.After; import org.junit.AfterClass; @@ -23,156 +23,178 @@ import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.openo.commontosca.catalog.db.exception.CatalogResourceException; import org.openo.commontosca.catalog.db.dao.DaoManager; import org.openo.commontosca.catalog.db.entity.NodeTemplateData; import org.openo.commontosca.catalog.db.entity.PackageData; import org.openo.commontosca.catalog.db.entity.ServiceTemplateData; import org.openo.commontosca.catalog.db.entity.TemplateData; +import org.openo.commontosca.catalog.db.exception.CatalogResourceException; import org.openo.commontosca.catalog.db.util.H2DbServer; import org.openo.commontosca.catalog.db.util.HibernateSession; +import java.util.ArrayList; + public class IntegrationManager { - private static PackageManager packageManager; - private static TemplateManager templateManager; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - H2DbServer.startUp(); - DaoManager.getInstance().setSessionFactory(HibernateSession.init()); - packageManager = PackageManager.getInstance(); - templateManager = TemplateManager.getInstance(); - } + private static PackageManager packageManager; + private static TemplateManager templateManager; - @AfterClass - public static void tearDownAfterClass() throws Exception { - try { - HibernateSession.destory(); - DaoManager.getInstance().setDaoNull(); - H2DbServer.shutDown(); - } catch (Exception e) { - Assert.fail("Exception" + e.getMessage()); - } - } + /** + * startup H2DB session before class. + * @throws Exception e + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + H2DbServer.startUp(); + DaoManager.getInstance().setSessionFactory(HibernateSession.init()); + packageManager = PackageManager.getInstance(); + templateManager = TemplateManager.getInstance(); + } - @Before - public void setUp() { - initPackageInfo(); - initTemplateInfo(); + /** + * destory H2DB session after class. + * @throws Exception e + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + try { + HibernateSession.destory(); + DaoManager.getInstance().setDaoNull(); + H2DbServer.shutDown(); + } catch (Exception e1) { + Assert.fail("Exception" + e1.getMessage()); } + } - public void initPackageInfo() { - PackageData data = new PackageData(); - data.setCsarId("10001"); - data.setName("AG"); - data.setVersion("v1.0"); - data.setProvider("ZTE"); - try { - packageManager.addPackage(data); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - } + @Before + public void setUp() { + initPackageInfo(); + initTemplateInfo(); + } - public void deletePackageInfo() { - try { - packageManager.deletePackage("10001"); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } + /** + * init package information. + */ + public void initPackageInfo() { + PackageData data = new PackageData(); + data.setCsarId("10001"); + data.setName("AG"); + data.setVersion("v1.0"); + data.setProvider("ZTE"); + try { + packageManager.addPackage(data); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + } - public void initTemplateInfo() { - ServiceTemplateData serviceData = new ServiceTemplateData(); - TemplateData data = new TemplateData(); - ArrayList nodelist = new ArrayList(); - serviceData.setCsarId("10001"); - serviceData.setServiceTemplateId("20001"); - serviceData.setVendor("ZTE"); - serviceData.setVersion("v1.0"); - NodeTemplateData nodeData = new NodeTemplateData(); - nodeData.setName("node"); - nodeData.setNodeTemplateId("30001"); - nodeData.setServiceTemplateId("20001"); - nodelist.add(nodeData); - data.setServiceTemplate(serviceData); - data.setNodeTemplates(nodelist); - try { - templateManager.addServiceTemplate(data); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } + /** + * delete package information. + */ + public void deletePackageInfo() { + try { + packageManager.deletePackage("10001"); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + } - public void deleteTemplate() { - try { - templateManager.deleteServiceTemplateById("20001"); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } + /** + * init template information. + */ + public void initTemplateInfo() { + ServiceTemplateData serviceData = new ServiceTemplateData(); + serviceData.setCsarId("10001"); + serviceData.setServiceTemplateId("20001"); + serviceData.setVendor("ZTE"); + serviceData.setVersion("v1.0"); + NodeTemplateData nodeData = new NodeTemplateData(); + nodeData.setName("node"); + nodeData.setNodeTemplateId("30001"); + nodeData.setServiceTemplateId("20001"); + ArrayList nodelist = new ArrayList(); + nodelist.add(nodeData); + TemplateData data = new TemplateData(); + data.setServiceTemplate(serviceData); + data.setNodeTemplates(nodelist); + try { + templateManager.addServiceTemplate(data); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + } - @After - public void tearDown() { - deleteTemplate(); - deletePackageInfo(); + /** + * delete template. + */ + public void deleteTemplate() { + try { + templateManager.deleteServiceTemplateById("20001"); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + } - @Test - public void testDeletePackageByServiceTemplateId() { - try { - packageManager.deletePackageByServiceTemplateId("20001"); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - ArrayList list = new ArrayList(); - try { - list = packageManager.queryPackageByServiceTemplateId("20001"); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - Assert.assertTrue(list.size() == 0); + @After + public void tearDown() { + deleteTemplate(); + deletePackageInfo(); + } + + @Test + public void testDeletePackageByServiceTemplateId() { + try { + packageManager.deletePackageByServiceTemplateId("20001"); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); + } + ArrayList list = new ArrayList(); + try { + list = packageManager.queryPackageByServiceTemplateId("20001"); + } catch (CatalogResourceException e2) { + Assert.fail("Exception" + e2.getMessage()); } + Assert.assertTrue(list.size() == 0); + } - @Test - public void testQueryPackageByServiceTemplateId() { - ArrayList list = new ArrayList(); - try { - list = packageManager.queryPackageByServiceTemplateId("20001"); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - Assert.assertTrue(list.size() > 0); + @Test + public void testQueryPackageByServiceTemplateId() { + ArrayList list = new ArrayList(); + try { + list = packageManager.queryPackageByServiceTemplateId("20001"); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + Assert.assertTrue(list.size() > 0); + } - @Test - public void testDeleteServiceTemplateByCsarPackageInfo() { - PackageData data = new PackageData(); - data.setCsarId("10001"); - ArrayList list = new ArrayList(); - try { - templateManager.deleteServiceTemplateByCsarPackageInfo(data); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - try { - list = templateManager.queryServiceTemplateByCsarPackageInfo(data); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - Assert.assertTrue(list.size() == 0); + @Test + public void testDeleteServiceTemplateByCsarPackageInfo() { + PackageData data = new PackageData(); + data.setCsarId("10001"); + ArrayList list = new ArrayList(); + try { + templateManager.deleteServiceTemplateByCsarPackageInfo(data); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); + } + try { + list = templateManager.queryServiceTemplateByCsarPackageInfo(data); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + Assert.assertTrue(list.size() == 0); + } - @Test - public void testQueryServiceTemplateByCsarPackageInfo() { - PackageData data = new PackageData(); - data.setCsarId("10001"); - ArrayList list = new ArrayList(); - try { - list = templateManager.queryServiceTemplateByCsarPackageInfo(data); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - Assert.assertTrue(list.size() > 0); + @Test + public void testQueryServiceTemplateByCsarPackageInfo() { + PackageData data = new PackageData(); + data.setCsarId("10001"); + ArrayList list = new ArrayList(); + try { + list = templateManager.queryServiceTemplateByCsarPackageInfo(data); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + Assert.assertTrue(list.size() > 0); + } } diff --git a/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/resource/PackageManagerTest.java b/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/resource/PackageManagerTest.java index 52ec701f..fc847a60 100644 --- a/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/resource/PackageManagerTest.java +++ b/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/resource/PackageManagerTest.java @@ -13,13 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.resource; import static org.junit.Assert.assertTrue; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; import org.junit.After; import org.junit.AfterClass; @@ -28,138 +26,157 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.openo.commontosca.catalog.db.common.Parameters; -import org.openo.commontosca.catalog.db.exception.CatalogResourceException; import org.openo.commontosca.catalog.db.dao.DaoManager; import org.openo.commontosca.catalog.db.entity.PackageData; +import org.openo.commontosca.catalog.db.exception.CatalogResourceException; import org.openo.commontosca.catalog.db.util.H2DbServer; import org.openo.commontosca.catalog.db.util.HibernateSession; -public class PackageManagerTest { - private static PackageManager manager; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - H2DbServer.startUp(); - DaoManager.getInstance().setSessionFactory(HibernateSession.init()); - manager = PackageManager.getInstance(); - } - @AfterClass - public static void tearDownAfterClass() throws Exception { - try { - HibernateSession.destory(); - DaoManager.getInstance().setPackageDao(null); - H2DbServer.shutDown(); - } catch (Exception e) { - Assert.fail("Exception" + e.getMessage()); - } +public class PackageManagerTest { + private static PackageManager manager; + + /** + * startup db session before class. + * @throws Exception e + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + H2DbServer.startUp(); + DaoManager.getInstance().setSessionFactory(HibernateSession.init()); + manager = PackageManager.getInstance(); + } + + /** + * destory db session after class. + * @throws Exception e + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + try { + HibernateSession.destory(); + DaoManager.getInstance().setPackageDao(null); + H2DbServer.shutDown(); + } catch (Exception e1) { + Assert.fail("Exception" + e1.getMessage()); } - - @Before - public void setUp() { - PackageData data = new PackageData(); - data.setCsarId("10001"); - data.setName("AG"); - data.setVersion("v1.0"); - data.setProvider("ZTE"); - try { - manager.addPackage(data); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } + } + + /** + * create data before test. + */ + @Before + public void setUp() { + PackageData data = new PackageData(); + data.setCsarId("10001"); + data.setName("AG"); + data.setVersion("v1.0"); + data.setProvider("ZTE"); + try { + manager.addPackage(data); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } - - @After - public void tearDown() { - try { - manager.deletePackage("10001"); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } + } + + /** + * delete data after test. + */ + @After + public void tearDown() { + try { + manager.deletePackage("10001"); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } - - @Test - public void testAddPackageRepeat() { - PackageData data = new PackageData(); - data.setCsarId("10001"); - data.setName("AG"); - data.setVersion("v1.0"); - data.setProvider("ZTE"); - try { - manager.addPackage(data); - Assert.fail("no exception"); - } catch (CatalogResourceException e) { - Assert.assertTrue(true); - } - + } + + @Test + public void testAddPackageRepeat() { + PackageData data = new PackageData(); + data.setCsarId("10001"); + data.setName("AG"); + data.setVersion("v1.0"); + data.setProvider("ZTE"); + try { + manager.addPackage(data); + Assert.fail("no exception"); + } catch (CatalogResourceException e1) { + Assert.assertTrue(true); } - @Test - public void testQueryPackageByCsarId_exist() { - ArrayList list = new ArrayList(); - try { - list = manager.queryPackageByCsarId("10001"); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - Assert.assertTrue(list.size() > 0); - } + } - @Test - public void testQueryPackageByCsarId_not_exist() { - ArrayList list = new ArrayList(); - try { - list = manager.queryPackageByCsarId("10002"); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - Assert.assertTrue(list.size() == 0); + @Test + public void testQueryPackageByCsarId_exist() { + ArrayList list = new ArrayList(); + try { + list = manager.queryPackageByCsarId("10001"); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + Assert.assertTrue(list.size() > 0); + } + + @Test + public void testQueryPackageByCsarId_not_exist() { + ArrayList list = new ArrayList(); + try { + list = manager.queryPackageByCsarId("10002"); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); + } + Assert.assertTrue(list.size() == 0); + } - @Test - public void testQueryPackage_exist() { - - ArrayList list = new ArrayList(); - try { - list = manager.queryPackage("AG", "ZTE", "v1.0", null, null); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - Assert.assertTrue(list.size() > 0); + @Test + public void testQueryPackage_exist() { + ArrayList list = new ArrayList(); + try { + list = manager.queryPackage("AG", "ZTE", "v1.0", null, null); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + Assert.assertTrue(list.size() > 0); - @Test - public void testQueryPackage_not_exist() { + } - ArrayList list = new ArrayList(); - try { - list = manager.queryPackage("AG", "ZTE", "v2.0", null, null); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - Assert.assertTrue(list.size() == 0); + @Test + public void testQueryPackage_not_exist() { + ArrayList list = new ArrayList(); + try { + list = manager.queryPackage("AG", "ZTE", "v2.0", null, null); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } - - @Test - public void testUpdatePackage() { - PackageData data = new PackageData(); - data.setSize("20M"); - try { - manager.updatePackage(data, "10001"); - } catch (CatalogResourceException e1) { - Assert.fail("Exception" + e1.getMessage()); - } - Map queryParam = new HashMap(); - queryParam.put(Parameters.csarId.name(), "10001"); - ArrayList list = new ArrayList(); - try { - list = manager.queryPackageByCsarId("10001"); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - assertTrue(list.size() > 0 && list.get(0).getSize().equals("20M")); + Assert.assertTrue(list.size() == 0); + + } + + @Test + public void testUpdatePackage() { + PackageData data = new PackageData(); + data.setSize("20M"); + try { + manager.updatePackage(data, "10001"); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); + } + Map queryParam = new HashMap(); + queryParam.put(Parameters.csarId.name(), "10001"); + ArrayList list = new ArrayList(); + try { + list = manager.queryPackageByCsarId("10001"); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + assertTrue(list.size() > 0 && list.get(0).getSize().equals("20M")); + } } diff --git a/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/resource/TemplateManagerTest.java b/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/resource/TemplateManagerTest.java index 66b25048..41dcfab1 100644 --- a/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/resource/TemplateManagerTest.java +++ b/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/resource/TemplateManagerTest.java @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.resource; -import java.util.ArrayList; import org.junit.After; import org.junit.AfterClass; @@ -23,138 +23,154 @@ import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.openo.commontosca.catalog.db.exception.CatalogResourceException; import org.openo.commontosca.catalog.db.dao.DaoManager; import org.openo.commontosca.catalog.db.entity.NodeTemplateData; import org.openo.commontosca.catalog.db.entity.ServiceTemplateData; import org.openo.commontosca.catalog.db.entity.TemplateData; +import org.openo.commontosca.catalog.db.exception.CatalogResourceException; import org.openo.commontosca.catalog.db.util.H2DbServer; import org.openo.commontosca.catalog.db.util.HibernateSession; +import java.util.ArrayList; + public class TemplateManagerTest { - private static TemplateManager manager; + private static TemplateManager manager; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - H2DbServer.startUp(); - DaoManager.getInstance().setSessionFactory(HibernateSession.init()); - manager = TemplateManager.getInstance(); - } + /** + * startup db session before class. + * @throws Exception e + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + H2DbServer.startUp(); + DaoManager.getInstance().setSessionFactory(HibernateSession.init()); + manager = TemplateManager.getInstance(); + } - @AfterClass - public static void tearDownAfterClass() throws Exception { - try { - HibernateSession.destory(); - DaoManager.getInstance().setTemplateDao(null); - DaoManager.getInstance().setServiceTemplateDao(null); - DaoManager.getInstance().setNodeTemplateDao(null); - H2DbServer.shutDown(); - } catch (Exception e) { - Assert.fail("Exception" + e.getMessage()); - } + /** + * destory db session after class. + * @throws Exception e + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + try { + HibernateSession.destory(); + DaoManager.getInstance().setTemplateDao(null); + DaoManager.getInstance().setServiceTemplateDao(null); + DaoManager.getInstance().setNodeTemplateDao(null); + H2DbServer.shutDown(); + } catch (Exception e1) { + Assert.fail("Exception" + e1.getMessage()); } + } - @Before - public void setUp() { - ServiceTemplateData serviceData = new ServiceTemplateData(); - TemplateData data = new TemplateData(); - ArrayList nodelist = new ArrayList(); - serviceData.setCsarId("10001"); - serviceData.setServiceTemplateId("20001"); - serviceData.setRowData("EEEEEEWERWEREWRERWEREW"); - serviceData.setOperations("SDFSDFDSERWERWE"); - serviceData.setVendor("ZTE"); - serviceData.setVersion("v1.0"); - NodeTemplateData nodeData = new NodeTemplateData(); - nodeData.setName("node"); - nodeData.setNodeTemplateId("30001"); - nodeData.setServiceTemplateId("20001"); - nodelist.add(nodeData); - data.setServiceTemplate(serviceData); - data.setNodeTemplates(nodelist); - try { - manager.addServiceTemplate(data); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } + /** + * create data before test. + */ + @Before + public void setUp() { + ServiceTemplateData serviceData = new ServiceTemplateData(); + serviceData.setCsarId("10001"); + serviceData.setServiceTemplateId("20001"); + serviceData.setRowData("EEEEEEWERWEREWRERWEREW"); + serviceData.setOperations("SDFSDFDSERWERWE"); + serviceData.setVendor("ZTE"); + serviceData.setVersion("v1.0"); + NodeTemplateData nodeData = new NodeTemplateData(); + nodeData.setName("node"); + nodeData.setNodeTemplateId("30001"); + nodeData.setServiceTemplateId("20001"); + ArrayList nodelist = new ArrayList(); + nodelist.add(nodeData); + TemplateData data = new TemplateData(); + data.setServiceTemplate(serviceData); + data.setNodeTemplates(nodelist); + try { + manager.addServiceTemplate(data); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + } - @After - public void tearDown() { - try { - manager.deleteServiceTemplateById("20001"); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } + /** + * delete data after test. + */ + @After + public void tearDown() { + try { + manager.deleteServiceTemplateById("20001"); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + } - @Test - public void testAddServiceTemplateRepeat() { - ServiceTemplateData serviceData = new ServiceTemplateData(); - TemplateData data = new TemplateData(); - data.setServiceTemplate(serviceData); - ArrayList nodelist = new ArrayList(); - serviceData.setCsarId("10001"); - serviceData.setServiceTemplateId("20001"); - serviceData.setVendor("ZTE"); - serviceData.setVersion("v1.0"); - NodeTemplateData nodeData = new NodeTemplateData(); - nodeData.setName("node"); - nodeData.setServiceTemplateId("20001"); - nodelist.add(nodeData); - data.setNodeTemplates(nodelist); - try { - manager.addServiceTemplate(data); - Assert.fail("no exception"); - } catch (CatalogResourceException e) { - Assert.assertTrue(true); - } + @Test + public void testAddServiceTemplateRepeat() { + ServiceTemplateData serviceData = new ServiceTemplateData(); + TemplateData data = new TemplateData(); + data.setServiceTemplate(serviceData); + serviceData.setCsarId("10001"); + serviceData.setServiceTemplateId("20001"); + serviceData.setVendor("ZTE"); + serviceData.setVersion("v1.0"); + NodeTemplateData nodeData = new NodeTemplateData(); + nodeData.setName("node"); + nodeData.setServiceTemplateId("20001"); + ArrayList nodelist = new ArrayList(); + nodelist.add(nodeData); + data.setNodeTemplates(nodelist); + try { + manager.addServiceTemplate(data); + Assert.fail("no exception"); + } catch (CatalogResourceException e1) { + Assert.assertTrue(true); } + } - @Test - public void testQueryServiceTemplateById() { - ArrayList list = new ArrayList(); - try { - list = manager.queryServiceTemplateById("20001"); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - Assert.assertTrue(list.size() > 0); + @Test + public void testQueryServiceTemplateById() { + ArrayList list = new ArrayList(); + try { + list = manager.queryServiceTemplateById("20001"); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + Assert.assertTrue(list.size() > 0); + } - @Test - public void testQueryServiceTemplate() { - - ArrayList list = new ArrayList(); - try { - list = manager.queryServiceTemplate(null, "v1.0", "ZTE"); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - Assert.assertTrue(list.size() > 0); + @Test + public void testQueryServiceTemplate() { + ArrayList list = new ArrayList(); + try { + list = manager.queryServiceTemplate(null, "v1.0", "ZTE"); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + Assert.assertTrue(list.size() > 0); + + } - @Test - public void testQueryNodeTemplateBySeriviceTemplateId() { - ArrayList list = new ArrayList(); - try { - list = manager.queryNodeTemplateBySeriviceTemplateId("20001"); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - Assert.assertTrue(list.size() > 0); + @Test + public void testQueryNodeTemplateBySeriviceTemplateId() { + ArrayList list = new ArrayList(); + try { + list = manager.queryNodeTemplateBySeriviceTemplateId("20001"); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + Assert.assertTrue(list.size() > 0); + } - @Test - public void testQueryNodeTemplateById() { - ArrayList list = new ArrayList(); - try { - list = manager.queryNodeTemplateById("20001", null); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - Assert.assertTrue(list.size() > 0); + @Test + public void testQueryNodeTemplateById() { + ArrayList list = new ArrayList(); + try { + list = manager.queryNodeTemplateById("20001", null); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + Assert.assertTrue(list.size() > 0); + } } diff --git a/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/resource/TemplateMappingManagerTest.java b/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/resource/TemplateMappingManagerTest.java index 4f952e47..09c6d181 100644 --- a/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/resource/TemplateMappingManagerTest.java +++ b/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/resource/TemplateMappingManagerTest.java @@ -13,9 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.db.resource; -import java.util.ArrayList; +package org.openo.commontosca.catalog.db.resource; import org.junit.After; import org.junit.AfterClass; @@ -23,135 +22,152 @@ import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.openo.commontosca.catalog.db.exception.CatalogResourceException; import org.openo.commontosca.catalog.db.dao.DaoManager; import org.openo.commontosca.catalog.db.entity.ServiceTemplateMappingData; +import org.openo.commontosca.catalog.db.exception.CatalogResourceException; import org.openo.commontosca.catalog.db.util.H2DbServer; import org.openo.commontosca.catalog.db.util.HibernateSession; -public class TemplateMappingManagerTest { - private static TemplateManager manager; +import java.util.ArrayList; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - H2DbServer.startUp(); - DaoManager.getInstance().setSessionFactory(HibernateSession.init()); - manager = TemplateManager.getInstance(); - } - @AfterClass - public static void tearDownAfterClass() throws Exception { - try { - HibernateSession.destory(); - DaoManager.getInstance().setTemplateDao(null); - H2DbServer.shutDown(); - } catch (Exception e) { - Assert.fail("Exception" + e.getMessage()); - } +public class TemplateMappingManagerTest { + private static TemplateManager manager; + + /** + * startup db session before class. + * @throws Exception e + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + H2DbServer.startUp(); + DaoManager.getInstance().setSessionFactory(HibernateSession.init()); + manager = TemplateManager.getInstance(); + } + + /** + * destory db session after class. + * @throws Exception e + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + try { + HibernateSession.destory(); + DaoManager.getInstance().setTemplateDao(null); + H2DbServer.shutDown(); + } catch (Exception e1) { + Assert.fail("Exception" + e1.getMessage()); } - - @Before - public void setUp() { - ServiceTemplateMappingData serviceMappingData = new ServiceTemplateMappingData(); - serviceMappingData.setCapabilities("wsectdSDFSDFDSXCVFertregdDFGDFG"); - serviceMappingData.setRequirements("REWREWRWE#$#"); - serviceMappingData.setNodeType("NS"); - serviceMappingData.setServiceTemplateId("10020"); - serviceMappingData.setMappingId("10000"); - try { - manager.addServiceTemplateMapping(serviceMappingData); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } + } + + /** + * create data before test. + */ + @Before + public void setUp() { + ServiceTemplateMappingData serviceMappingData = new ServiceTemplateMappingData(); + serviceMappingData.setCapabilities("wsectdSDFSDFDSXCVFertregdDFGDFG"); + serviceMappingData.setRequirements("REWREWRWE#$#"); + serviceMappingData.setNodeType("NS"); + serviceMappingData.setServiceTemplateId("10020"); + serviceMappingData.setMappingId("10000"); + try { + manager.addServiceTemplateMapping(serviceMappingData); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } - - @After - public void tearDown() { - try { - manager.deleteServiceTemplateMappingById("10000"); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } + } + + /** + * delete data after test. + */ + @After + public void tearDown() { + try { + manager.deleteServiceTemplateMappingById("10000"); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } - - @Test - public void testAddServiceTemplateRepeat() { - ServiceTemplateMappingData serviceMappingData = new ServiceTemplateMappingData(); - serviceMappingData.setCapabilities("wsectdSDFSDFDSXCVFertregdDFGDFG"); - serviceMappingData.setRequirements("REWREWRWE#$#"); - serviceMappingData.setNodeType("NS"); - serviceMappingData.setServiceTemplateId("10020"); - serviceMappingData.setMappingId("10000"); - try { - manager.addServiceTemplateMapping(serviceMappingData); - Assert.fail("no exception"); - } catch (CatalogResourceException e) { - Assert.assertTrue(true); - } + } + + @Test + public void testAddServiceTemplateRepeat() { + ServiceTemplateMappingData serviceMappingData = new ServiceTemplateMappingData(); + serviceMappingData.setCapabilities("wsectdSDFSDFDSXCVFertregdDFGDFG"); + serviceMappingData.setRequirements("REWREWRWE#$#"); + serviceMappingData.setNodeType("NS"); + serviceMappingData.setServiceTemplateId("10020"); + serviceMappingData.setMappingId("10000"); + try { + manager.addServiceTemplateMapping(serviceMappingData); + Assert.fail("no exception"); + } catch (CatalogResourceException e1) { + Assert.assertTrue(true); } - - @Test - public void testServiceTemplateMappingById() { - ArrayList list = new ArrayList(); - try { - list = manager.queryServiceTemplateMappingById("10000"); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - Assert.assertTrue(list.size() > 0); + } + + @Test + public void testServiceTemplateMappingById() { + ArrayList list = new ArrayList(); + try { + list = manager.queryServiceTemplateMappingById("10000"); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + Assert.assertTrue(list.size() > 0); + } + + @Test + public void testQueryServiceTemplateMapping() { - @Test - public void testQueryServiceTemplateMapping() { - - ArrayList list = new ArrayList(); - try { - list = manager.queryServiceTemplateMapping("NS", "10020"); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - Assert.assertTrue(list.size() > 0); - try { - list = manager.queryServiceTemplateMapping("NS", ""); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - Assert.assertTrue(list.size() > 0); - try { - list = manager.queryServiceTemplateMapping("", "10020"); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - Assert.assertTrue(list.size() > 0); + ArrayList list = new ArrayList(); + try { + list = manager.queryServiceTemplateMapping("NS", "10020"); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + Assert.assertTrue(list.size() > 0); + try { + list = manager.queryServiceTemplateMapping("NS", ""); + } catch (CatalogResourceException e2) { + Assert.fail("Exception" + e2.getMessage()); + } + Assert.assertTrue(list.size() > 0); + try { + list = manager.queryServiceTemplateMapping("", "10020"); + } catch (CatalogResourceException e3) { + Assert.fail("Exception" + e3.getMessage()); + } + Assert.assertTrue(list.size() > 0); + } - @Test - public void testDeleteServiceTemplateMapping() { - - ArrayList list = new ArrayList(); - try { - manager.deleteServiceTemplateMapping("NS", "10020"); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - try { - list = manager.queryServiceTemplateMapping("NS", "10020"); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - Assert.assertTrue(list.size() == 0); + @Test + public void testDeleteServiceTemplateMapping() { + + ArrayList list = new ArrayList(); + try { + manager.deleteServiceTemplateMapping("NS", "10020"); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); + } + try { + list = manager.queryServiceTemplateMapping("NS", "10020"); + } catch (CatalogResourceException e2) { + Assert.fail("Exception" + e2.getMessage()); } + Assert.assertTrue(list.size() == 0); + } - @Test - public void testQueryAllServiceTemplateMapping() { + @Test + public void testQueryAllServiceTemplateMapping() { - ArrayList list = new ArrayList(); - try { - list = manager.queryServiceTemplateMapping("", ""); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - Assert.assertTrue(list.size() > 0); + ArrayList list = new ArrayList(); + try { + list = manager.queryServiceTemplateMapping("", ""); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + Assert.assertTrue(list.size() > 0); + } } diff --git a/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/resource/dao/PackageDaoTest.java b/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/resource/dao/PackageDaoTest.java index b61fde9e..4a552f1d 100644 --- a/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/resource/dao/PackageDaoTest.java +++ b/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/resource/dao/PackageDaoTest.java @@ -13,14 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.resource.dao; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; import org.junit.After; import org.junit.AfterClass; @@ -30,107 +28,127 @@ import org.junit.BeforeClass; import org.junit.Test; import org.openo.commontosca.catalog.db.common.Parameters; import org.openo.commontosca.catalog.db.dao.PackageDao; -import org.openo.commontosca.catalog.db.exception.CatalogResourceException; -import org.openo.commontosca.catalog.db.util.HqlFactory; import org.openo.commontosca.catalog.db.entity.PackageData; +import org.openo.commontosca.catalog.db.exception.CatalogResourceException; import org.openo.commontosca.catalog.db.util.H2DbServer; import org.openo.commontosca.catalog.db.util.HibernateSession; +import org.openo.commontosca.catalog.db.util.HqlFactory; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; public class PackageDaoTest { - private static PackageDao packageDao; + private static PackageDao packageDao; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - H2DbServer.startUp(); - packageDao = new PackageDao(HibernateSession.init()); + /** + * setup db session before class. + * @throws Exception e + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + H2DbServer.startUp(); + packageDao = new PackageDao(HibernateSession.init()); - } + } - @AfterClass - public static void tearDownAfterClass() throws Exception { - try { - HibernateSession.destory(); - H2DbServer.shutDown(); - } catch (Exception e) { - Assert.fail("Exception" + e.getMessage()); - } + /** + * shutdown db session before class. + * @throws Exception e + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + try { + HibernateSession.destory(); + H2DbServer.shutDown(); + } catch (Exception e1) { + Assert.fail("Exception" + e1.getMessage()); } + } - @Before - public void setUp() { - PackageData data = new PackageData(); - data.setCsarId("10001"); - data.setName("AG"); - try { - packageDao.create(data); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } + /** + * create data before test. + * @throws Exception e + */ + @Before + public void setUp() { + PackageData data = new PackageData(); + data.setCsarId("10001"); + data.setName("AG"); + try { + packageDao.create(data); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + } - @After - public void tearDown() { - PackageData data = new PackageData(); - data.setCsarId("10001"); - try { - packageDao.delete(data); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } + /** + * delete data after test. + * @throws Exception e + */ + @After + public void tearDown() { + PackageData data = new PackageData(); + data.setCsarId("10001"); + try { + packageDao.delete(data); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + } - @Test - public void testQueryPackageById() { - Map queryParam = new HashMap(); - queryParam.put(Parameters.csarId.name(), "10001"); - ArrayList list = new ArrayList(); - try { - list = (ArrayList) packageDao.query(queryParam); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - Assert.assertTrue(list.size() > 0); + @Test + public void testQueryPackageById() { + Map queryParam = new HashMap(); + queryParam.put(Parameters.csarId.name(), "10001"); + ArrayList list = new ArrayList(); + try { + list = (ArrayList) packageDao.query(queryParam); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + Assert.assertTrue(list.size() > 0); + } - @Test - public void testUpdatePackage() { - PackageData data = new PackageData(); - data.setSize("20M"); - try { - packageDao.update(data, HqlFactory.getOidFilter(Parameters.csarId.name(), "10001")); - } catch (CatalogResourceException e1) { - Assert.fail("Exception" + e1.getMessage()); - } - Map queryParam = new HashMap(); - queryParam.put(Parameters.csarId.name(), "10001"); - ArrayList list = new ArrayList(); - try { - list = (ArrayList) packageDao.query(queryParam); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - assertTrue(list.size() > 0 && list.get(0).getSize().equals("20M")); + @Test + public void testUpdatePackage() { + PackageData data = new PackageData(); + data.setSize("20M"); + try { + packageDao.update(data, HqlFactory.getOidFilter(Parameters.csarId.name(), "10001")); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); + } + Map queryParam = new HashMap(); + queryParam.put(Parameters.csarId.name(), "10001"); + ArrayList list = new ArrayList(); + try { + list = (ArrayList) packageDao.query(queryParam); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + assertTrue(list.size() > 0 && list.get(0).getSize().equals("20M")); + } - @Test - public void testDeleteByOid() { - PackageData data = new PackageData(); - data.setCsarId("10001"); - try { - packageDao.delete(data); - } catch (CatalogResourceException e1) { - Assert.fail("Exception" + e1.getMessage()); - } - Map queryParam = new HashMap(); - queryParam.put(Parameters.csarId.name(), "10001"); - ArrayList list = new ArrayList(); - try { - list = (ArrayList) packageDao.query(queryParam); - } catch (CatalogResourceException e) { - Assert.fail("Exception" + e.getMessage()); - } - assertEquals(list.size(), 0); + @Test + public void testDeleteByOid() { + PackageData data = new PackageData(); + data.setCsarId("10001"); + try { + packageDao.delete(data); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); + } + Map queryParam = new HashMap(); + queryParam.put(Parameters.csarId.name(), "10001"); + ArrayList list = new ArrayList(); + try { + list = (ArrayList) packageDao.query(queryParam); + } catch (CatalogResourceException e1) { + Assert.fail("Exception" + e1.getMessage()); } + assertEquals(list.size(), 0); + } } diff --git a/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/util/CatalogDbUtilTest.java b/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/util/CatalogDbUtilTest.java index cd923160..8172d26c 100644 --- a/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/util/CatalogDbUtilTest.java +++ b/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/util/CatalogDbUtilTest.java @@ -13,46 +13,50 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.util; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +//import static org.junit.Assert.*; import org.junit.Test; public class CatalogDbUtilTest { - @Test - public void when_generate_id_is_not_null() { - String actual_uuid = CatalogDbUtil.generateId(); - assertNotNull(actual_uuid); - } - - @Test - public void when_input_empty_string_output_false() { - boolean expect = false; - boolean actual = CatalogDbUtil.isNotEmpty(""); - assertEquals(expect, actual); - } - - @Test - public void when_input_blan_string_output_true() { - boolean expect = true; - boolean actual = CatalogDbUtil.isNotEmpty(" "); - assertEquals(expect, actual); - } - - @Test - public void when_input_null_string_output_false() { - boolean expect = false; - boolean actual = CatalogDbUtil.isNotEmpty(null); - assertEquals(expect, actual); - } - - @Test - public void when_input_str_string_output_true() { - boolean expect = true; - boolean actual = CatalogDbUtil.isNotEmpty("str"); - assertEquals(expect, actual); - } + @Test + public void when_generate_id_is_not_null() { + String actualUuid = CatalogDbUtil.generateId(); + assertNotNull(actualUuid); + } + + @Test + public void when_input_empty_string_output_false() { + boolean expect = false; + boolean actual = CatalogDbUtil.isNotEmpty(""); + assertEquals(expect, actual); + } + + @Test + public void when_input_blan_string_output_true() { + boolean expect = true; + boolean actual = CatalogDbUtil.isNotEmpty(" "); + assertEquals(expect, actual); + } + + @Test + public void when_input_null_string_output_false() { + boolean expect = false; + boolean actual = CatalogDbUtil.isNotEmpty(null); + assertEquals(expect, actual); + } + + @Test + public void when_input_str_string_output_true() { + boolean expect = true; + boolean actual = CatalogDbUtil.isNotEmpty("str"); + assertEquals(expect, actual); + } } diff --git a/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/util/H2DbServer.java b/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/util/H2DbServer.java index ceb3c7c0..ee62a306 100644 --- a/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/util/H2DbServer.java +++ b/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/util/H2DbServer.java @@ -13,39 +13,45 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.util; +import org.h2.tools.Server; + import java.sql.SQLException; -import org.h2.tools.Server; public class H2DbServer { - private static Server h2DbWebServer; - private static Server h2DbTcpServer; - - public static void startUp() { - try { - h2DbWebServer = - Server.createWebServer(new String[] {"-web", "-webAllowOthers", "-webPort", - "8206"}); - h2DbWebServer.start(); - - h2DbTcpServer = - Server.createTcpServer(new String[] {"-tcp", "-tcpAllowOthers", "-tcpPort", - "8205"}); - h2DbTcpServer.start(); - } catch (SQLException e) { - e.printStackTrace(); - } + private static Server h2DbWebServer; + private static Server h2DbTcpServer; + + /** + * start up db service. + */ + public static void startUp() { + try { + h2DbWebServer = + Server.createWebServer(new String[] {"-web", "-webAllowOthers", "-webPort", "8206"}); + h2DbWebServer.start(); + + h2DbTcpServer = + Server.createTcpServer(new String[] {"-tcp", "-tcpAllowOthers", "-tcpPort", "8205"}); + h2DbTcpServer.start(); + } catch (SQLException e1) { + e1.printStackTrace(); } + } - public static void shutDown() { - if (h2DbWebServer.isRunning(true)) { - h2DbWebServer.shutdown(); - } - if (h2DbTcpServer.isRunning(true)) { - h2DbTcpServer.shutdown(); - } + /** + * shut down db service. + */ + public static void shutDown() { + if (h2DbWebServer.isRunning(true)) { + h2DbWebServer.shutdown(); + } + if (h2DbTcpServer.isRunning(true)) { + h2DbTcpServer.shutdown(); } + } } diff --git a/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/util/H2DbServerUtil.java b/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/util/H2DbServerUtil.java index 033e49f2..b10c377f 100644 --- a/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/util/H2DbServerUtil.java +++ b/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/util/H2DbServerUtil.java @@ -13,46 +13,53 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.db.util; -import java.io.File; -import java.net.URISyntaxException; +package org.openo.commontosca.catalog.db.util; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.SQLExec; import org.apache.tools.ant.types.EnumeratedAttribute; +import java.io.File; +import java.net.URISyntaxException; + public class H2DbServerUtil { - private static String resourcePath; + private static String resourcePath; - public static void initTable() { - init(); - SQLExec sqlExec = new SQLExec(); - // set db connetc parameter - sqlExec.setDriver("org.h2.Driver"); - sqlExec.setUrl("jdbc:h2:tcp://localhost:8205/" + resourcePath + "db/catalog"); - sqlExec.setUserid("catalog"); - sqlExec.setPassword("catalog"); - // execute sql - sqlExec.setSrc(new File(resourcePath + "sql/catalog-resource-createObj-mysql.sql")); - sqlExec.setOnerror((SQLExec.OnError) (EnumeratedAttribute.getInstance( - SQLExec.OnError.class, "abort"))); - sqlExec.setPrint(true); // set print - sqlExec.setProject(new Project()); - sqlExec.execute(); - } + /** + * init data table. + */ + public static void initTable() { + init(); + SQLExec sqlExec = new SQLExec(); + // set db connetc parameter + sqlExec.setDriver("org.h2.Driver"); + sqlExec.setUrl("jdbc:h2:tcp://localhost:8205/" + resourcePath + "db/catalog"); + sqlExec.setUserid("catalog"); + sqlExec.setPassword("catalog"); + // execute sql + sqlExec.setSrc(new File(resourcePath + "sql/catalog-resource-createObj-mysql.sql")); + sqlExec.setOnerror((SQLExec.OnError) (EnumeratedAttribute.getInstance(SQLExec.OnError.class, + "abort"))); + sqlExec.setPrint(true); // set print + sqlExec.setProject(new Project()); + sqlExec.execute(); + } - private static void init() { - try { - resourcePath = HibernateSession.class.getResource("/").toURI().getPath(); - } catch (URISyntaxException e) { - e.printStackTrace(); - } + private static void init() { + try { + resourcePath = HibernateSession.class.getResource("/").toURI().getPath(); + } catch (URISyntaxException e1) { + e1.printStackTrace(); } + } - public static void main(String args[]) { - H2DbServer.startUp(); - H2DbServerUtil.initTable(); - H2DbServer.shutDown(); - } + /** + * test. + */ + public static void main() { + H2DbServer.startUp(); + H2DbServerUtil.initTable(); + H2DbServer.shutDown(); + } } diff --git a/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/util/HibernateSession.java b/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/util/HibernateSession.java index 0b031a7a..ded139a7 100644 --- a/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/util/HibernateSession.java +++ b/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/util/HibernateSession.java @@ -13,67 +13,71 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.db.util; -import java.io.File; -import java.net.URISyntaxException; +package org.openo.commontosca.catalog.db.util; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; +import java.io.File; +import java.net.URISyntaxException; + public class HibernateSession { - private static File cfgfile = null; + private static File cfgfile = null; - private static ServiceRegistry serviceRegistry = null; - private static Configuration configuration = null; - private static SessionFactory sessionFactory = null; - private static String resourcePath; + private static ServiceRegistry serviceRegistry = null; + private static Configuration configuration = null; + private static SessionFactory sessionFactory = null; + private static String resourcePath; - /** - * Get a hibernate sessionFactory. - */ - public static SessionFactory init() { - initConfigure(); - configuration = new Configuration().configure(cfgfile); - configuration.setProperty("hibernate.connection.url", "jdbc:h2:tcp://localhost:8205/" - + resourcePath + "db/catalog"); - serviceRegistry = - new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) - .build(); - sessionFactory = configuration.buildSessionFactory(serviceRegistry); - return sessionFactory; - } + /** + * Get a hibernate sessionFactory. + */ + public static SessionFactory init() { + initConfigure(); + configuration = new Configuration().configure(cfgfile); + configuration.setProperty("hibernate.connection.url", "jdbc:h2:tcp://localhost:8205/" + + resourcePath + "db/catalog"); + serviceRegistry = + new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); + sessionFactory = configuration.buildSessionFactory(serviceRegistry); + return sessionFactory; + } - private static void initConfigure() { - try { - resourcePath = HibernateSession.class.getResource("/").toURI().getPath(); - } catch (URISyntaxException e) { - e.printStackTrace(); - } - final String filename = "Hibernate.cfg.xml"; - cfgfile = new File(resourcePath + filename); + private static void initConfigure() { + try { + resourcePath = HibernateSession.class.getResource("/").toURI().getPath(); + } catch (URISyntaxException e1) { + e1.printStackTrace(); } + final String filename = "Hibernate.cfg.xml"; + cfgfile = new File(resourcePath + filename); + } - /** - * Destory a hibernate sessionFactory. - */ - public static void destory() { - sessionFactory.close(); - } + /** + * Destory a hibernate sessionFactory. + */ + public static void destory() { + sessionFactory.close(); + } - /* Maybe you don't need it. */ - private static void removeCfgFile() { - if (cfgfile.exists()) { - cfgfile.deleteOnExit(); - } + /* Maybe you don't need it. */ + private static void removeCfgFile() { + if (cfgfile.exists()) { + cfgfile.deleteOnExit(); } + } - public static void main(String[] args) { - // createCfgFile(); - // removeCfgFile(); + /** + * test. + * @param args param + */ + public static void main(String[] args) { + // createCfgFile(); + // removeCfgFile(); - } + } } diff --git a/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/util/HqlFactoryTest.java b/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/util/HqlFactoryTest.java index d1070180..23a5f5ea 100644 --- a/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/util/HqlFactoryTest.java +++ b/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/db/util/HqlFactoryTest.java @@ -13,9 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.openo.commontosca.catalog.db.util; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Test; import org.openo.commontosca.catalog.db.entity.PackageData; @@ -23,92 +24,95 @@ import org.openo.commontosca.catalog.db.entity.ServiceTemplateData; public class HqlFactoryTest { - @Test - public void when_input_entity_output_udatehql() { - PackageData data = new PackageData(); - String filter = "csarId='xd03dsfsdfsfsdfsd'"; - data.setName("csarName"); - data.setType("NS"); - String expect = - "update PackageData set name='csarName',type='NS' where csarId='xd03dsfsdfsfsdfsd'"; - String actual = HqlFactory.getUpdateHql(data, null, filter); - assertEquals(expect, actual); - } + @Test + public void when_input_entity_output_udatehql() { + PackageData data = new PackageData(); + String filter = "csarId='xd03dsfsdfsfsdfsd'"; + data.setName("csarName"); + data.setType("NS"); + String expect = + "update PackageData set name='csarName',type='NS' where csarId='xd03dsfsdfsfsdfsd'"; + String actual = HqlFactory.getUpdateHql(data, null, filter); + assertEquals(expect, actual); + } - @Test - public void when_input_null_testContain_output_false() { - boolean expect = false; - boolean actual = HqlFactory.contain(null, "name"); - assertEquals(expect, actual); - String[] src = new String[0]; - actual = HqlFactory.contain(src, "name"); - assertEquals(expect, actual); - src = new String[1]; - actual = HqlFactory.contain(src, null); - assertEquals(expect, actual); - } + @Test + public void when_input_null_testContain_output_false() { + boolean expect = false; + boolean actual = HqlFactory.contain(null, "name"); + assertEquals(expect, actual); + String[] src = new String[0]; + actual = HqlFactory.contain(src, "name"); + assertEquals(expect, actual); + src = new String[1]; + actual = HqlFactory.contain(src, null); + assertEquals(expect, actual); + } - @Test - public void when_input_src_contain_target_testContain_output_true() { - boolean expect = true; - String src[] = {"name", "type"}; - String target = "name"; - boolean actual = HqlFactory.contain(src, target); - assertEquals(expect, actual); - } + @Test + public void when_input_src_contain_target_testContain_output_true() { + boolean expect = true; + String[] src = {"name", "type"}; + String target = "name"; + boolean actual = HqlFactory.contain(src, target); + assertEquals(expect, actual); + } - @Test - public void when_input_src_not_contain_target_testContain_output_false() { - boolean expect = false; - String src[] = {"name", "type"}; - String target = "version"; - boolean actual = HqlFactory.contain(src, target); - assertEquals(expect, actual); - } + @Test + public void when_input_src_not_contain_target_testContain_output_false() { + boolean expect = false; + String[] src = {"name", "type"}; + String target = "version"; + boolean actual = HqlFactory.contain(src, target); + assertEquals(expect, actual); + } - @Test - public void testGetOidFilter() { - // fail("Not yet implemented"); - String key = "csarId"; - String value = "xd03dsfsdfsfsdfsd"; - String expect = "csarId= 'xd03dsfsdfsfsdfsd'"; - String actual = HqlFactory.getOidFilter(key, value); - assertEquals(expect, actual); - } + @Test + public void testGetOidFilter() { + // fail("Not yet implemented"); + String key = "csarId"; + String value = "xd03dsfsdfsfsdfsd"; + String expect = "csarId= 'xd03dsfsdfsfsdfsd'"; + String actual = HqlFactory.getOidFilter(key, value); + assertEquals(expect, actual); + } - @Test - public void when_input_entity_output_queryhql() { - PackageData data = new PackageData(); - String filter = "csarId"; - data.setName("csarName"); - data.setType("NS"); - String expect = - "select q.csarId from PackageData as q where q.name='csarName' and q.type='NS'"; - String actual = HqlFactory.getQueryHql(data, filter); - assertEquals(expect, actual); - } + @Test + public void when_input_entity_output_queryhql() { + PackageData data = new PackageData(); + String filter = "csarId"; + data.setName("csarName"); + data.setType("NS"); + String expect = "select q.csarId from PackageData as q where q.name='csarName' and q.type='NS'"; + String actual = HqlFactory.getQueryHql(data, filter); + assertEquals(expect, actual); + } - @Test - public void when_input_entity_output_getQueryHqlByFilter() { - PackageData data = new PackageData(); - String filter = "csarId"; - data.setName("csarName"); - data.setType("NS"); - String expect = - " from ServiceTemplateData as a where a.csarId in(select q.csarId from PackageData as q where q.name='csarName' and q.type='NS')"; - String actual = HqlFactory.getQueryHqlByFilter(ServiceTemplateData.class, data, filter); - assertEquals(expect, actual); - } + @Test + public void when_input_entity_output_getQueryHqlByFilter() { + PackageData data = new PackageData(); + String filter = "csarId"; + data.setName("csarName"); + data.setType("NS"); + String expect = + " from ServiceTemplateData as a where a.csarId " + + "in(select q.csarId from PackageData as q " + + "where q.name='csarName' and q.type='NS')"; + String actual = HqlFactory.getQueryHqlByFilter(ServiceTemplateData.class, data, filter); + assertEquals(expect, actual); + } - @Test - public void when_input_entity_output_getDeleteHqlByFilter() { - PackageData data = new PackageData(); - String filter = "csarId"; - data.setName("csarName"); - data.setType("NS"); - String expect = - "delete from ServiceTemplateData as b where b.csarId in(select q.csarId from PackageData as q where q.name='csarName' and q.type='NS')"; - String actual = HqlFactory.getDeleteHqlByFilter(ServiceTemplateData.class, data, filter); - assertEquals(expect, actual); - } + @Test + public void when_input_entity_output_getDeleteHqlByFilter() { + PackageData data = new PackageData(); + String filter = "csarId"; + data.setName("csarName"); + data.setType("NS"); + String expect = + "delete from ServiceTemplateData as b where b.csarId " + + "in(select q.csarId from PackageData as q " + + "where q.name='csarName' and q.type='NS')"; + String actual = HqlFactory.getDeleteHqlByFilter(ServiceTemplateData.class, data, filter); + assertEquals(expect, actual); + } } diff --git a/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/wrapper/PackageWrapperTest.java b/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/wrapper/PackageWrapperTest.java index f41a8cf7..20a0d355 100644 --- a/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/wrapper/PackageWrapperTest.java +++ b/catalog-core/catalog-mgr/src/test/java/org/openo/commontosca/catalog/wrapper/PackageWrapperTest.java @@ -13,16 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.openo.commontosca.catalog.wrapper; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.net.URISyntaxException; -import java.util.ArrayList; +package org.openo.commontosca.catalog.wrapper; -import javax.ws.rs.core.Response; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.junit.After; @@ -34,14 +29,13 @@ import org.junit.Ignore; import org.junit.Test; import org.openo.commontosca.catalog.CatalogAppConfiguration; import org.openo.commontosca.catalog.common.Config; -import org.openo.commontosca.catalog.common.MsbAddrConfig; -import org.openo.commontosca.catalog.db.exception.CatalogResourceException; -import org.openo.commontosca.catalog.db.resource.PackageManager; -import org.openo.commontosca.catalog.filemanage.entity.FileLink; import org.openo.commontosca.catalog.common.HttpServerAddrConfig; import org.openo.commontosca.catalog.common.HttpServerPathConfig; +import org.openo.commontosca.catalog.common.MsbAddrConfig; import org.openo.commontosca.catalog.db.dao.DaoManager; import org.openo.commontosca.catalog.db.entity.PackageData; +import org.openo.commontosca.catalog.db.exception.CatalogResourceException; +import org.openo.commontosca.catalog.db.resource.PackageManager; import org.openo.commontosca.catalog.db.util.H2DbServer; import org.openo.commontosca.catalog.db.util.HibernateSession; import org.openo.commontosca.catalog.entity.EnumOnboardState; @@ -50,270 +44,288 @@ import org.openo.commontosca.catalog.entity.EnumProcessState; import org.openo.commontosca.catalog.entity.EnumUsageState; import org.openo.commontosca.catalog.entity.response.CsarFileUriResponse; import org.openo.commontosca.catalog.entity.response.PackageMeta; +import org.openo.commontosca.catalog.filemanage.entity.FileLink; -import static org.junit.Assert.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.net.URISyntaxException; +import java.util.ArrayList; -/** - * @author 00164331 - * - */ -public class PackageWrapperTest { - private static String resourcePath; +import javax.ws.rs.core.Response; - static { - MsbAddrConfig.setMsbAddress("http://127.0.0.1:80"); - } - static { - HttpServerAddrConfig.setHttpServerAddress("http://127.0.0.1:8080"); - } - static { - HttpServerPathConfig.setHttpServerPath("../tomcat/webapps/ROOT/"); - } +public class PackageWrapperTest { + private static String resourcePath; - // @Mock - private static PackageManager manager; + static { + MsbAddrConfig.setMsbAddress("http://127.0.0.1:80"); + } + + static { + HttpServerAddrConfig.setHttpServerAddress("http://127.0.0.1:8080"); + } + + static { + HttpServerPathConfig.setHttpServerPath("../tomcat/webapps/ROOT/"); + } + private static PackageManager manager; - @BeforeClass - public static void setUpBeforeClass() throws CatalogResourceException { - CatalogAppConfiguration configuration = new CatalogAppConfiguration(); - H2DbServer.startUp(); - DaoManager.getInstance().setSessionFactory(HibernateSession.init()); - manager = PackageManager.getInstance(); - Config.setConfigration(configuration); - System.out.println("Set up before class"); - } - @Before - public void setUp() throws Exception { - ArrayList packageList = manager.queryPackage(null, null, null, null, null); - if (packageList != null && packageList.size() > 0) { - for (int i = 0; i < packageList.size(); i++) { - String package_oid = packageList.get(i).getCsarId(); - manager.deletePackage(package_oid); - } - } + /** + * startup db session before class. + * @throws Exception e + */ + @BeforeClass + public static void setUpBeforeClass() throws CatalogResourceException { + H2DbServer.startUp(); + DaoManager.getInstance().setSessionFactory(HibernateSession.init()); + manager = PackageManager.getInstance(); + CatalogAppConfiguration configuration = new CatalogAppConfiguration(); + Config.setConfigration(configuration); + System.out.println("Set up before class"); + } - // PowerMockito.mockStatic(PackageManager.class); - // PowerMockito.when(manager.addPackage(packageData)).thenReturn(packageData); - // PowerMock.replayAll(); - PackageData packageData = new PackageData(); - packageData = getPackageData(); - manager.addPackage(packageData); + /** + * create data before test. + */ + @Before + public void setUp() throws Exception { + ArrayList packageList = manager.queryPackage(null, null, null, null, null); + if (packageList != null && packageList.size() > 0) { + for (int i = 0; i < packageList.size(); i++) { + String packageOid = packageList.get(i).getCsarId(); + manager.deletePackage(packageOid); + } } - // @Ignore - @Test - public void testUploadPackage() throws Exception { - InputStream ins = null; - Response result = null; - Response result1 = null; - Response result2 = null; - // PackageData packageData = new PackageData(); - // packageData = getPackageData(); + // PowerMockito.mockStatic(PackageManager.class); + // PowerMockito.when(manager.addPackage(packageData)).thenReturn(packageData); + // PowerMock.replayAll(); + PackageData packageData = new PackageData(); + packageData = getPackageData(); + manager.addPackage(packageData); + } - FormDataContentDisposition fileDetail = - FormDataContentDisposition.name("fileName").fileName("NanocellGW.csar").build(); + // @Ignore + @Test + public void testUploadPackage() throws Exception { + InputStream ins = null; + Response result = null; + Response result1 = null; + Response result2 = null; + // PackageData packageData = new PackageData(); + // packageData = getPackageData(); - try { - resourcePath = HibernateSession.class.getResource("/").toURI().getPath(); - } catch (URISyntaxException e) { - e.printStackTrace(); - } - final String filename = "NanocellGW.csar"; - File packageFile = new File(resourcePath + filename); - try { - ins = new FileInputStream(packageFile); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - if (ins != null) { - try { - result = PackageWrapper.getInstance().uploadPackage(ins, fileDetail, null); - } catch (Exception e) { - e.printStackTrace(); - } - } - assertEquals(200, result.getStatus()); - assertNotNull(result.getEntity()); + FormDataContentDisposition fileDetail = + FormDataContentDisposition.name("fileName").fileName("NanocellGW.csar").build(); + + try { + resourcePath = HibernateSession.class.getResource("/").toURI().getPath(); + } catch (URISyntaxException e1) { + e1.printStackTrace(); + } + final String filename = "NanocellGW.csar"; + File packageFile = new File(resourcePath + filename); + try { + ins = new FileInputStream(packageFile); + } catch (FileNotFoundException e2) { + e2.printStackTrace(); + } + if (ins != null) { + try { + result = PackageWrapper.getInstance().uploadPackage(ins, fileDetail, null); + } catch (Exception e3) { + e3.printStackTrace(); + } + } + assertEquals(200, result.getStatus()); + assertNotNull(result.getEntity()); - try { - result1 = PackageWrapper.getInstance().uploadPackage(null, fileDetail, null); - } catch (Exception e) { - e.printStackTrace(); - } - assertEquals(500, result1.getStatus()); + try { + result1 = PackageWrapper.getInstance().uploadPackage(null, fileDetail, null); + } catch (Exception e4) { + e4.printStackTrace(); + } + assertEquals(500, result1.getStatus()); - try { - result2 = PackageWrapper.getInstance().uploadPackage(ins, null, null); - } catch (Exception e) { - e.printStackTrace(); - } - assertEquals(500, result2.getStatus()); + try { + result2 = PackageWrapper.getInstance().uploadPackage(ins, null, null); + } catch (Exception e5) { + e5.printStackTrace(); } + assertEquals(500, result2.getStatus()); + } - @Test - public void testQueryPackageById() throws Exception { - ArrayList metas = new ArrayList(); - metas = getPackageMetaList(); - // PackageManager packageManager = mock(PackageManager.class); - // when(packageManager.queryPackageByCsarId(anyString())).thenThrow(new Exception()); - // PowerMockito.whenNew(PackageManager.class).withNoArguments().thenReturn(packageManager); - // PowerMockito.mockStatic(PackageManager.class); - // PowerMockito.when(PackageManager.getInstance()).thenReturn(manager); - // PowerMock.replayAll(); - // when(manager.queryPackageByCsarId(anyString())).thenThrow(new Exception()); - // PowerMockito.whenNew(PackageManager.class).withNoArguments().thenReturn(manager); + @Test + public void testQueryPackageById() throws Exception { + ArrayList metas = new ArrayList(); + metas = getPackageMetaList(); + // PackageManager packageManager = mock(PackageManager.class); + // when(packageManager.queryPackageByCsarId(anyString())).thenThrow(new Exception()); + // PowerMockito.whenNew(PackageManager.class).withNoArguments().thenReturn(packageManager); + // PowerMockito.mockStatic(PackageManager.class); + // PowerMockito.when(PackageManager.getInstance()).thenReturn(manager); + // PowerMock.replayAll(); + // when(manager.queryPackageByCsarId(anyString())).thenThrow(new Exception()); + // PowerMockito.whenNew(PackageManager.class).withNoArguments().thenReturn(manager); - Response result = PackageWrapper.getInstance().queryPackageById("1"); - assertEquals(200, result.getStatus()); - assertEquals(metas, result.getEntity()); + Response result = PackageWrapper.getInstance().queryPackageById("1"); + assertEquals(200, result.getStatus()); + assertEquals(metas, result.getEntity()); - } + } - @Test - public void testQueryPackageByCond() { - ArrayList metas = new ArrayList(); - metas = getPackageMetaList(); - System.out.println("Test query package by Id"); - Response result = - PackageWrapper.getInstance().queryPackageListByCond("NanocellGW", "ZTE", "V1.0", - "false", "NSAR"); - assertEquals(200, result.getStatus()); - assertEquals(metas, result.getEntity()); - } + @Test + public void testQueryPackageByCond() { + ArrayList metas = new ArrayList(); + metas = getPackageMetaList(); + System.out.println("Test query package by Id"); + Response result = + PackageWrapper.getInstance().queryPackageListByCond("NanocellGW", "ZTE", "V1.0", "false", + "NSAR"); + assertEquals(200, result.getStatus()); + assertEquals(metas, result.getEntity()); + } - @Test - public void testUpdatePackageStatus() { - System.out.println("Test update package status"); - Response result = - PackageWrapper.getInstance().updatePackageStatus("1", "Enabled", "NotInUse", - "true", "onBoarding", "true"); - assertEquals(200, result.getStatus()); - } + @Test + public void testUpdatePackageStatus() { + System.out.println("Test update package status"); + Response result = + PackageWrapper.getInstance().updatePackageStatus("1", "Enabled", "NotInUse", "true", + "onBoarding", "true"); + assertEquals(200, result.getStatus()); + } - @Test - public void testGetCsarFileUri() { - System.out.println("Test get csar file uri "); - CsarFileUriResponse expectResult = new CsarFileUriResponse(); - String csarFileUri = - MsbAddrConfig.getMsbAddress() - + "/NSAR/ZTE/NanocellGW/v1.0/NanocellGW/images/segw.img"; - String localUri = - HttpServerPathConfig.getHttpServerPath() - + "NSAR/ZTE/NanocellGW/v1.0/NanocellGW/images/segw.img"; - File srcDir = new File(localUri); - String localPath = srcDir.getAbsolutePath().replace("\\", "/"); + @Test + public void testGetCsarFileUri() { + System.out.println("Test get csar file uri "); + CsarFileUriResponse expectResult = new CsarFileUriResponse(); + String csarFileUri = + MsbAddrConfig.getMsbAddress() + "/NSAR/ZTE/NanocellGW/v1.0/NanocellGW/images/segw.img"; + String localUri = + HttpServerPathConfig.getHttpServerPath() + + "NSAR/ZTE/NanocellGW/v1.0/NanocellGW/images/segw.img"; + File srcDir = new File(localUri); + String localPath = srcDir.getAbsolutePath().replace("\\", "/"); - expectResult.setDownloadUri(csarFileUri); - expectResult.setLocalPath(localPath); - Response result = PackageWrapper.getInstance().getCsarFileUri("1", "/images/segw.img"); - assertEquals(200, result.getStatus()); - assertEquals(expectResult, result.getEntity()); - } + expectResult.setDownloadUri(csarFileUri); + expectResult.setLocalPath(localPath); + Response result = PackageWrapper.getInstance().getCsarFileUri("1", "/images/segw.img"); + assertEquals(200, result.getStatus()); + assertEquals(expectResult, result.getEntity()); + } - @Ignore - @Test - public void testGetPlansUri() { - System.out.println("Test get csar plans uri "); - ArrayList expectResult = new ArrayList(); - FileLink fileLink1 = new FileLink(); - FileLink fileLink2 = new FileLink(); - fileLink1.setFileName("init.zip"); - fileLink1.setDownloadUri(MsbAddrConfig.getMsbAddress() - + "/NSAR/ZTE/NanocellGW/v1.0/Plans/init.zip"); - expectResult.add(fileLink1); - fileLink2.setFileName("delete.zip"); - fileLink2.setDownloadUri(MsbAddrConfig.getMsbAddress() - + "/NSAR/ZTE/NanocellGW/v1.0/Plans/delete.zip"); - expectResult.add(fileLink2); - Response result = PackageWrapper.getInstance().getCsarPlansUri("1"); - assertEquals(200, result.getStatus()); - assertEquals(expectResult, result.getEntity()); - } + @Ignore + @Test + public void testGetPlansUri() { + System.out.println("Test get csar plans uri "); + ArrayList expectResult = new ArrayList(); + FileLink fileLink1 = new FileLink(); + fileLink1.setFileName("init.zip"); + fileLink1.setDownloadUri(MsbAddrConfig.getMsbAddress() + + "/NSAR/ZTE/NanocellGW/v1.0/Plans/init.zip"); + expectResult.add(fileLink1); + FileLink fileLink2 = new FileLink(); + fileLink2.setFileName("delete.zip"); + fileLink2.setDownloadUri(MsbAddrConfig.getMsbAddress() + + "/NSAR/ZTE/NanocellGW/v1.0/Plans/delete.zip"); + expectResult.add(fileLink2); + Response result = PackageWrapper.getInstance().getCsarPlansUri("1"); + assertEquals(200, result.getStatus()); + assertEquals(expectResult, result.getEntity()); + } - @Test - public void testDelPackage() { - System.out.println("Test delete package "); - Response result = PackageWrapper.getInstance().delPackage("1"); - assertEquals(204, result.getStatus()); - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } + @Test + public void testDelPackage() { + System.out.println("Test delete package "); + Response result = PackageWrapper.getInstance().delPackage("1"); + assertEquals(204, result.getStatus()); + try { + Thread.sleep(5000); + } catch (InterruptedException e1) { + e1.printStackTrace(); } + } - @After - public void tearDown() throws Exception { - ArrayList packageList = manager.queryPackageByCsarId("1"); - if (packageList != null && packageList.size() != 0) { - manager.deletePackage("1"); - } else { - return; - } - System.out.println("Tear down"); + /** + * delete data after test. + */ + @After + public void tearDown() throws Exception { + ArrayList packageList = manager.queryPackageByCsarId("1"); + if (packageList != null && packageList.size() != 0) { + manager.deletePackage("1"); + } else { + return; } + System.out.println("Tear down"); + } - @AfterClass - public static void tearDownAfterClass() { - try { - HibernateSession.destory(); - DaoManager.getInstance().setDaoNull(); - H2DbServer.shutDown(); - } catch (Exception e) { - Assert.fail("Exception" + e.getMessage()); - } + /** + * destory db session after class. + * @throws Exception e + */ + @AfterClass + public static void tearDownAfterClass() { + try { + HibernateSession.destory(); + DaoManager.getInstance().setDaoNull(); + H2DbServer.shutDown(); + } catch (Exception e1) { + Assert.fail("Exception" + e1.getMessage()); } + } - private PackageData getPackageData() { - PackageData packageData = new PackageData(); - packageData.setCsarId("1"); - packageData.setCreateTime("2016-06-29 03:33:15"); - packageData.setDeletionPending("false"); - packageData.setDownloadUri("/NSAR/ZTE/NanocellGW/v1.0/"); - packageData.setFormat("yml"); - packageData.setModifyTime("2016-06-29 03:33:15"); - packageData.setName("NanocellGW"); - packageData.setOnBoardState("non-onBoarded"); - packageData.setOperationalState("Disabled"); - packageData.setProvider("ZTE"); - packageData.setSize("0.93M"); - packageData.setType("NSAR"); - packageData.setUsageState("InUse"); - packageData.setVersion("V1.0"); - packageData.setProcessState("normal"); - return packageData; - } + private PackageData getPackageData() { + PackageData packageData = new PackageData(); + packageData.setCsarId("1"); + packageData.setCreateTime("2016-06-29 03:33:15"); + packageData.setDeletionPending("false"); + packageData.setDownloadUri("/NSAR/ZTE/NanocellGW/v1.0/"); + packageData.setFormat("yml"); + packageData.setModifyTime("2016-06-29 03:33:15"); + packageData.setName("NanocellGW"); + packageData.setOnBoardState("non-onBoarded"); + packageData.setOperationalState("Disabled"); + packageData.setProvider("ZTE"); + packageData.setSize("0.93M"); + packageData.setType("NSAR"); + packageData.setUsageState("InUse"); + packageData.setVersion("V1.0"); + packageData.setProcessState("normal"); + return packageData; + } - private ArrayList getPackageDataList() { - ArrayList packageDataList = new ArrayList(); - PackageData packageData = new PackageData(); - packageData = getPackageData(); - packageDataList.add(packageData); - return packageDataList; - } + private ArrayList getPackageDataList() { + ArrayList packageDataList = new ArrayList(); + PackageData packageData = new PackageData(); + packageData = getPackageData(); + packageDataList.add(packageData); + return packageDataList; + } - private ArrayList getPackageMetaList() { - ArrayList metas = new ArrayList(); - PackageMeta meta = new PackageMeta(); - meta.setCreateTime("2016-06-29 03:33:15"); - meta.setCsarId("1"); - meta.setDeletionPending(false); - meta.setDownloadUri(MsbAddrConfig.getMsbAddress() - + "/NSAR/ZTE/NanocellGW/v1.0/NanocellGW.csar"); - meta.setFormat("yml"); - meta.setModifyTime("2016-06-29 03:33:15"); - meta.setName("NanocellGW"); - meta.setOperationalState(EnumOperationalState.valueOf("Disabled")); - meta.setProvider("ZTE"); - meta.setSize("0.93M"); - meta.setType("NSAR"); - meta.setUsageState(EnumUsageState.valueOf("InUse")); - meta.setVersion("V1.0"); - meta.setOnBoardState(EnumOnboardState.nonOnBoarded.getValue()); - meta.setProcessState(EnumProcessState.valueOf("normal")); - metas.add(meta); - return metas; - } + private ArrayList getPackageMetaList() { + PackageMeta meta = new PackageMeta(); + meta.setCreateTime("2016-06-29 03:33:15"); + meta.setCsarId("1"); + meta.setDeletionPending(false); + meta.setDownloadUri(MsbAddrConfig.getMsbAddress() + + "/NSAR/ZTE/NanocellGW/v1.0/NanocellGW.csar"); + meta.setFormat("yml"); + meta.setModifyTime("2016-06-29 03:33:15"); + meta.setName("NanocellGW"); + meta.setOperationalState(EnumOperationalState.valueOf("Disabled")); + meta.setProvider("ZTE"); + meta.setSize("0.93M"); + meta.setType("NSAR"); + meta.setUsageState(EnumUsageState.valueOf("InUse")); + meta.setVersion("V1.0"); + meta.setOnBoardState(EnumOnboardState.nonOnBoarded.getValue()); + meta.setProcessState(EnumProcessState.valueOf("normal")); + ArrayList metas = new ArrayList(); + metas.add(meta); + return metas; + } } -- cgit 1.2.3-korg