diff options
Diffstat (limited to 'catalog-core/catalog-mgr/src/main/java')
135 files changed, 12606 insertions, 0 deletions
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 new file mode 100644 index 00000000..0b97867d --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/CatalogApp.java @@ -0,0 +1,168 @@ +/**
+ * 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;
+
+import io.dropwizard.Application;
+import io.dropwizard.assets.AssetsBundle;
+import io.dropwizard.db.DataSourceFactory;
+import io.dropwizard.hibernate.HibernateBundle;
+import io.dropwizard.migrations.MigrationsBundle;
+import io.dropwizard.server.SimpleServerFactory;
+import io.dropwizard.setup.Bootstrap;
+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.MsbAddrConfig;
+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;
+
+public class CatalogApp extends Application<CatalogAppConfiguration> {
+
+ 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<CatalogAppConfiguration> bundle =
+ new HibernateBundle<CatalogAppConfiguration>(ServiceTemplateData.class,
+ PackageData.class, NodeTemplateData.class, ServiceTemplateMappingData.class) {
+ @Override
+ public DataSourceFactory getDataSourceFactory(CatalogAppConfiguration configuration) {
+ return configuration.getDataSourceFactory();
+ }
+ };
+
+ @Override
+ public void initialize(Bootstrap<CatalogAppConfiguration> 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<CatalogAppConfiguration> bootstrap) {
+ bootstrap.addBundle(bundle);
+ bootstrap.addBundle(new MigrationsBundle<CatalogAppConfiguration>() {
+ @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);
+ 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);
+ }
+
+ /**
+ * 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
+ }
+}
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 new file mode 100644 index 00000000..1f74f61b --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/CatalogAppConfiguration.java @@ -0,0 +1,210 @@ +/**
+ * 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;
+
+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;
+ }
+
+}
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 new file mode 100644 index 00000000..0a84ce3e --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/cometd/CometdException.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.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;
+ }
+}
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 new file mode 100644 index 00000000..9af11450 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/cometd/CometdService.java @@ -0,0 +1,110 @@ +/**
+ * 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.cometd;
+
+import java.io.IOException;
+
+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
+ *
+ */
+public class CometdService {
+ private BayeuxServer bayeux;
+ private LocalSession session;
+
+ /**
+ * meta channel.
+ */
+ private static final String bayeuxChannel = "/meta/";
+
+ /**
+ * service channel.
+ */
+ private static final String serviceChannel = "/service/";
+
+ private static CometdService cometdService = null;
+
+ 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);
+ }
+
+ private void checkBayeuxServer() throws CometdException {
+ if (this.bayeux == null) {
+ throw new CometdException(CometdException.ERROR_CODE_BAYEUX, "bayeux is null.");
+ }
+ }
+
+ 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.");
+ }
+ }
+}
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 new file mode 100644 index 00000000..6b69542a --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/cometd/CometdServlet.java @@ -0,0 +1,95 @@ +/**
+ * 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.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;
+
+import org.cometd.annotation.Listener;
+import org.cometd.annotation.ServerAnnotationProcessor;
+import org.cometd.annotation.Service;
+import org.cometd.bayeux.Message;
+import org.cometd.bayeux.server.BayeuxServer;
+import org.cometd.bayeux.server.ServerChannel;
+import org.cometd.bayeux.server.ServerMessage;
+import org.cometd.bayeux.server.ServerSession;
+import org.cometd.server.authorizer.GrantAuthorizer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * @author 10189609
+ *
+ */
+public class CometdServlet extends GenericServlet {
+
+ private static final long serialVersionUID = 1L;
+
+ 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!");
+ }
+
+ // Allow anybody to handshake
+ bayeux.getChannel(ServerChannel.META_HANDSHAKE)
+ .addAuthorizer(GrantAuthorizer.GRANT_PUBLISH);
+
+ // start server processor
+ ServerAnnotationProcessor processor = new ServerAnnotationProcessor(bayeux);
+ processor.process(new Monitor());
+
+ CometdUtil.setBayeuxServer(bayeux);
+ }
+
+ @Override
+ public void service(ServletRequest paramServletRequest, ServletResponse paramServletResponse)
+ throws ServletException, IOException {
+ ((HttpServletResponse) paramServletResponse).sendError(503);
+ }
+
+ @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());
+ }
+ }
+}
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 new file mode 100644 index 00000000..6955451c --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/cometd/CometdUtil.java @@ -0,0 +1,65 @@ +/**
+ * 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.
+ */
+/**
+* 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 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;
+
+ public static BayeuxServer getBayeuxServer() {
+ return bayeuxServer;
+ }
+
+ 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);
+ }
+}
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 new file mode 100644 index 00000000..08741619 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/CommonConstant.java @@ -0,0 +1,50 @@ +/** + * 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; + +public class CommonConstant { + + + 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 final static String CATALOG_CSAR_DIR_NAME = "/csar"; + + public static final String PACKAGE_YAML_FORMAT = "yaml"; + + // host image progress + + public static final String TOSCA_METADATA = "TOSCA-Metadata"; + + public static final String CSAR_VERSION_META = "version"; + + public static final String CSAR_TYPE_META = "type"; + + public static final String CSAR_PROVIDER_META = "provider"; + + public static final String DEFINITIONS = "Definitions"; + + public static final String CSAR_META = "csar.meta"; + + public static final String CSAR_SUFFIX = ".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 new file mode 100644 index 00000000..c260b923 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/CommonErrorResponse.java @@ -0,0 +1,49 @@ +/**
+ * 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;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+/**
+ * @author 00164331
+ *
+ */
+
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+public class CommonErrorResponse {
+
+ private String code;
+
+ private String message;
+
+ /**
+ * @param message2
+ * @return
+ */
+ public static Object failure(String message) {
+ return 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 new file mode 100644 index 00000000..b0799017 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/Config.java @@ -0,0 +1,31 @@ +/**
+ * 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;
+
+import org.openo.commontosca.catalog.CatalogAppConfiguration;
+
+
+public class Config {
+ private static CatalogAppConfiguration configration;
+
+ public static CatalogAppConfiguration getConfigration() {
+ return configration;
+ }
+
+ 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 new file mode 100644 index 00000000..41c38672 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/DateTimeUtil.java @@ -0,0 +1,33 @@ +/** + * 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; + +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 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); + } +} 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 new file mode 100644 index 00000000..0c811bde --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/EnumUploadStatus.java @@ -0,0 +1,20 @@ +/** + * 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; + +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 +} 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 new file mode 100644 index 00000000..ce90f34c --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/FileUtil.java @@ -0,0 +1,177 @@ +/**
+ * 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;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+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);
+
+ private static final int BUFFER_SIZE = 2 * 1024 * 1024;
+
+ private static final int TRY_COUNT = 3;
+
+ 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();
+ }
+
+ 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;
+ }
+
+ /**
+ * unzip zip file
+ *
+ * @param zipFileName
+ * @param unzip dir
+ * @throws IOException
+ */
+ public static ArrayList<String> unzip(String zipFileName, String extPlace) throws IOException {
+ ZipFile zipFile = null;
+ ArrayList<String> unzipFileNams = new ArrayList<String>();
+
+ 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);
+ }
+ }
+ } finally {
+ closeZipFile(zipFile);
+ }
+ return unzipFileNams;
+ }
+
+ /**
+ * close InputStream
+ *
+ * @param inputStream
+ */
+ private static void closeInputStream(InputStream inputStream) {
+ try {
+ if (inputStream != null) {
+ inputStream.close();
+ }
+ } catch (Exception e) {
+ 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 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!");
+ }
+ }
+}
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 new file mode 100644 index 00000000..a7a9e37b --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/FtpClient.java @@ -0,0 +1,190 @@ +/** + * 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; + +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 + */ +public class FtpClient { + private FTPClient ftpClient; + + 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); + } + + 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(); + } + + 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(); + } + + public void delete(String filePath) throws IOException { + ftpClient.dele(filePath); + } + + /** + * 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 + * @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; + } + } + } + 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; + } + } +} 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 new file mode 100644 index 00000000..e8f27b56 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/HttpServerAddrConfig.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.common;
+
+/**
+ * @author 00164331
+ *
+ */
+public class HttpServerAddrConfig {
+
+ protected static String httpServerAddress;
+
+ public static String getHttpServerAddress() {
+ return 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 new file mode 100644 index 00000000..6a538713 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/HttpServerPathConfig.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.common;
+
+/**
+ * @author 00164331
+ *
+ */
+public class HttpServerPathConfig {
+ protected static String httpServerPath;
+
+ public static String getHttpServerPath() {
+ return 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 new file mode 100644 index 00000000..357d1943 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/MSBUtil.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.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 new file mode 100644 index 00000000..5fcf6849 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/MsbAddrConfig.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.common;
+
+/**
+ * @author 00164331
+ *
+ */
+public class MsbAddrConfig {
+
+ protected static String msbAddress;
+
+ public static String getMsbAddress() {
+ return 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/RestUtil.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/RestUtil.java new file mode 100644 index 00000000..f754974e --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/RestUtil.java @@ -0,0 +1,35 @@ +/**
+ * 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;
+
+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();
+ }
+
+}
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 new file mode 100644 index 00000000..60a08583 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/ToolUtil.java @@ -0,0 +1,295 @@ +/** + * 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; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.text.DecimalFormat; +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 + * + */ +public class ToolUtil { + private static final Logger LOG = LoggerFactory.getLogger(ToolUtil.class); + + public final static String CATALOGUE_CSAR_DIR_NAME = "csar"; + + public final static 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 boolean isTrimedEmptyArray(String[] val) { + return val == null || val.length == 0; + } + + public static String[] TrimedStringArray(String[] val) { + if (isTrimedEmptyArray(val)) { + return val; + } + + String[] rets = new String[val.length]; + for (int i = 0; i < val.length; i++) { + rets[i] = val[i].trim(); + } + return rets; + } + + public static boolean isEmptyCollection(Collection<?> coll) { + return null == coll || coll.isEmpty(); + } + + /** + * 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); + LOG.info("tmpDir.getAbsolutePath() = " + tmpDir.getAbsolutePath()); + if (!tmpDir.exists()) { + tmpDir.mkdirs(); + } + + File file = new File(tmpDir.getAbsolutePath() + 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 String getTempDir(String dirName, String fileName) { + // File tmpDir = new File(File.separator + dirName); + return dirName + File.separator + fileName.replace(".csar", ""); + } + + public static String getUnzipDir(String dirName) { + File tmpDir = new File(File.separator + dirName); + return tmpDir.getAbsolutePath().replace(".csar", ""); + } + + 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; + } + + 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; + } + + 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; + } + + 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<String> 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<String> 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; + } + 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 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()); + } + + public static String processFileName(String fileName) { + int index = fileName.indexOf(".zip"); + if (index == -1) { + return fileName; + } + + return addCSARSuffix(fileName.replaceAll(".zip", "")); + } + + public static String objectToString(Object o) { + if (o == null) + return ""; + Gson gson = new Gson(); + String str = gson.toJson(o); + return str; + } + + public static String generateId() { + return UUID.randomUUID().toString(); + } + + 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); + } + + + /** + * + * @param jsonString + * @param tClass + * @return + */ + public static <T> T fromJson(String jsonString, Class<T> tClass) { + Gson gson = new Gson(); + return gson.fromJson(jsonString, tClass); + } + + /** + * + * @param t + * @return + */ + public static <T> String toJson(T t) { + Gson gson = new Gson(); + return gson.toJson(t); + } +} 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 new file mode 100644 index 00000000..8d24eac9 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/common/ZipCompressor.java @@ -0,0 +1,119 @@ +/**
+ * 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;
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.util.zip.CRC32;
+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;
+
+ private File zipFile;
+
+ 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);
+ }
+ }
+
+ 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);
+ }
+ }
+
+ 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 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() + "/");
+ }
+ }
+
+ /** 压缩一个文件 */
+ 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);
+ }
+ }
+}
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 new file mode 100644 index 00000000..6a12ffef --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/common/CatalogResuorceType.java @@ -0,0 +1,27 @@ +/** + * 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.db.common; + +/** + ** @author 10159474 + */ +public enum CatalogResuorceType { + SERVICETEMPLATE, PACKAGE, NODETEMPLATE, TEMPLATE, SERVICETEMPLATEMAPPING; + + 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 new file mode 100644 index 00000000..ddd414b8 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/common/Parameters.java @@ -0,0 +1,24 @@ +/** + * 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.db.common; + +/** + * *@author 10159474 + * + */ +public enum Parameters { + 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 new file mode 100644 index 00000000..f6b4d48b --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/BaseDao.java @@ -0,0 +1,194 @@ +/** + * 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.db.dao; + +import java.util.List; +import java.util.Map; + +import org.hibernate.Criteria; +import org.hibernate.HibernateException; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +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; + +/** + * a base class for Hibernate DAO classes + * + * provide the common methods to create,delete,update and query data + * + * *@author 10159474 + * + * @param <T> + */ +public class BaseDao<T> extends AbstractDAO<T> { + + 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; + } + + /** + * @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(); + } + } + + /** + * @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(); + } + } + + /** + * @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; + } + + public List<T> unionQuery(String unionHql) throws CatalogResourceException { + List<T> 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; + } + + 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; + } + + /** + * @param queryParams the condition map used to query objects + * @return + * @throws CatalogResourceException + */ + @SuppressWarnings("unchecked") + public List<T> query(Map<String, String> queryParams) throws CatalogResourceException { + List<T> 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<T>) 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 closeTransaction() { + this.session.getTransaction().commit(); + } + + protected void closeSession() { + this.session.close(); + } + + 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 new file mode 100644 index 00000000..6c9a5333 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/DaoManager.java @@ -0,0 +1,125 @@ +/** + * 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.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 + * + * + */ +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; + } + } + + public void setSessionFactory(SessionFactory sessionFactory) { + this.sessionFactory = sessionFactory; + } + + public SessionFactory getSessionFactory() { + return sessionFactory; + } + + public ServiceTemplateDao getServiceTemplateDao() { + if (serviceTemplateDao == null) + serviceTemplateDao = new ServiceTemplateDao(sessionFactory); + return serviceTemplateDao; + } + + public void setServiceTemplateDao(ServiceTemplateDao serviceTemplateDao) { + this.serviceTemplateDao = serviceTemplateDao; + } + + public PackageDao getPackageDao() { + if (packageDao == null) + packageDao = new PackageDao(sessionFactory); + return packageDao; + } + + 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; + } + 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 new file mode 100644 index 00000000..41253d96 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/NodeTemplateDao.java @@ -0,0 +1,35 @@ +/** + * 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.db.dao; + +import org.hibernate.SessionFactory; +import org.openo.commontosca.catalog.db.entity.NodeTemplateData; + + +/** + * host DAO class + * + * *@author 10159474 + * + */ +public class NodeTemplateDao extends BaseDao<NodeTemplateData> { + + 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 new file mode 100644 index 00000000..7f8a5036 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/PackageDao.java @@ -0,0 +1,35 @@ +/** + * 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.db.dao; + +import org.hibernate.SessionFactory; +import org.openo.commontosca.catalog.db.entity.PackageData; + + +/** + * host DAO class + * + * *@author 10159474 + * + */ +public class PackageDao extends BaseDao<PackageData> { + + 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 new file mode 100644 index 00000000..e2a5f3c2 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/ServiceTemplateDao.java @@ -0,0 +1,37 @@ +/** + * 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.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 + * + */ +public class ServiceTemplateDao extends BaseDao<ServiceTemplateData> { + private static final Logger logger = LoggerFactory.getLogger(ServiceTemplateDao.class); + + 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 new file mode 100644 index 00000000..558ce13a --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/ServiceTemplateMappingDao.java @@ -0,0 +1,37 @@ +/** + * 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.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 + * + */ +public class ServiceTemplateMappingDao extends BaseDao<ServiceTemplateMappingData> { + private static final Logger logger = LoggerFactory.getLogger(ServiceTemplateMappingDao.class); + + 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 new file mode 100644 index 00000000..5c39a9e8 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/dao/TemplateDao.java @@ -0,0 +1,77 @@ +/** + * 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.db.dao; + +import org.hibernate.HibernateException; +import org.hibernate.SessionFactory; +import org.openo.commontosca.catalog.db.entity.NodeTemplateData; +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; + +/** + * DAO class + * + * *@author 10159474 + * + */ +public class TemplateDao extends BaseDao<TemplateData> { + private static final Logger logger = LoggerFactory.getLogger(TemplateDao.class); + + 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; + } + + 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 ."); + } +} 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 new file mode 100644 index 00000000..99fe14ec --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/BaseData.java @@ -0,0 +1,20 @@ +/** + * 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.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 new file mode 100644 index 00000000..aeef00b9 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/NodeTemplateData.java @@ -0,0 +1,98 @@ +/** + * 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.db.entity; + +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; + + @Column(name = "SERVICETEMPLATEID") + private String serviceTemplateId; + + @Column(name = "TYPE") + private String type; + + @Column(name = "PROPERTIES") + private String properties; + + @Column(name = "RELATIONSHIPS") + private String relationShips; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getServiceTemplateId() { + return serviceTemplateId; + } + + public void setServiceTemplateId(String serviceTemplateId) { + this.serviceTemplateId = serviceTemplateId; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getProperties() { + return properties; + } + + public void setProperties(String properties) { + this.properties = properties; + } + + public String getRelationShips() { + return relationShips; + } + + public void setRelationShips(String relationShips) { + this.relationShips = relationShips; + } + + public void setNodeTemplateId(String nodeTemplateId) { + this.nodeTemplateId = 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 new file mode 100644 index 00000000..6c4a8110 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/PackageData.java @@ -0,0 +1,187 @@ +/** + * 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.db.entity; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "catalog_package_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; + } + + public void setCreateTime(String createTime) { + this.createTime = createTime; + } + + public void setCsarId(String csarId) { + this.csarId = csarId; + } + + public String getCsarId() { + return csarId; + } + + public String getProcessState() { + return 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 new file mode 100644 index 00000000..6e5963aa --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/ServiceTemplateData.java @@ -0,0 +1,138 @@ +/** + * 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.db.entity; + +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; + + @Column(name = "TYPE") + private String type; + + @Column(name = "VENDOR") + private String vendor; + + @Column(name = "VERSION") + private String version; + + @Column(name = "CSARID") + private String csarId; + + @Column(name = "INPUTS") + private String inputs; + + @Column(name = "DOWNLOADURI") + private String downloadUri; + + @Column(name = "ROWDATA") + private String rowData; + @Column(name = "OPERATIONS") + private String operations; + + public String getRowData() { + return rowData; + } + + public void setRowData(String rowData) { + this.rowData = rowData; + } + + public String getOperations() { + return operations; + } + + public void setOperations(String operations) { + this.operations = operations; + } + + public String getTemplateName() { + return templateName; + } + + public void setTemplateName(String templateName) { + this.templateName = templateName; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + 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 getCsarId() { + return csarId; + } + + public void setCsarId(String csarId) { + this.csarId = csarId; + } + + public String getInputs() { + return inputs; + } + + public void setInputs(String inputs) { + this.inputs = inputs; + } + + public String getDownloadUri() { + return downloadUri; + } + + public void setDownloadUri(String downloadUri) { + this.downloadUri = downloadUri; + } + + public void setServiceTemplateId(String serviceTemplateId) { + this.serviceTemplateId = 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 new file mode 100644 index 00000000..a0a632c5 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/ServiceTemplateMappingData.java @@ -0,0 +1,86 @@ +/** + * 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.db.entity; + +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; + + @Column(name = "NODETYPE") + private String nodeType; + + @Column(name = "SERVICETEMPLATEID") + private String serviceTemplateId; + + @Column(name = "REQUIREMENTS") + private String requirements; + + @Column(name = "CAPABILITIES") + private String capabilities; + + public String getMappingId() { + return mappingId; + } + + public void setMappingId(String mappingId) { + this.mappingId = mappingId; + } + + public String getNodeType() { + return nodeType; + } + + public void setNodeType(String nodeType) { + this.nodeType = nodeType; + } + + public String getServiceTemplateId() { + return serviceTemplateId; + } + + public void setServiceTemplateId(String serviceTemplateId) { + this.serviceTemplateId = serviceTemplateId; + } + + public String getRequirements() { + return requirements; + } + + public void setRequirements(String requirements) { + this.requirements = requirements; + } + + public String getCapabilities() { + return 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 new file mode 100644 index 00000000..ff139b1e --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/entity/TemplateData.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.db.entity; + +import java.util.ArrayList; + +public class TemplateData extends BaseData { + private ServiceTemplateData serviceTemplate; + private ArrayList<NodeTemplateData> nodeTemplates = new ArrayList<NodeTemplateData>(); + + public ServiceTemplateData getServiceTemplate() { + return serviceTemplate; + } + + public void setServiceTemplate(ServiceTemplateData serviceTemplate) { + this.serviceTemplate = serviceTemplate; + } + + public ArrayList<NodeTemplateData> getNodeTemplates() { + return nodeTemplates; + } + + public void setNodeTemplates(ArrayList<NodeTemplateData> 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 new file mode 100644 index 00000000..5a858d31 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/exception/CatalogResourceException.java @@ -0,0 +1,73 @@ +/** + * 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.db.exception; + +/** + * + */ +public class CatalogResourceException extends ErrorCodeException { + private static final long serialVersionUID = 5699508780537383310L; + + + public CatalogResourceException(int errcode) { + super(errcode, ""); + } + + + public CatalogResourceException(int errcode, Throwable cause) { + super(cause, errcode); + } + + + public CatalogResourceException(int errcode, String message, Throwable cause) { + super(cause, errcode, message); + } + + + public CatalogResourceException() { + super(9999999, null); + } + + + public CatalogResourceException(String message) { + super(9999999, message); + } + + + public CatalogResourceException(Throwable cause) { + super(cause, 9999999); + } + + + 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); + } + + public CatalogResourceException(Throwable source, int category, int code, String debugMessage, + String[] arguments) { + super(source, category, code, debugMessage, arguments); + } + + 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 new file mode 100644 index 00000000..33e6d9fa --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/exception/ErrorCodeException.java @@ -0,0 +1,132 @@ +/** + * 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.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; + } + + + public ErrorCodeException(int code, String debugMessage) { + this(code, debugMessage, null); + } + + + public ErrorCodeException(int code, String debugMessage, String[] arguments) { + super(debugMessage); + this.errorCode = code; + this.arguments = arguments; + } + + + public ErrorCodeException(Throwable source, int code) { + this(source, code, (String[]) null); + } + + + public ErrorCodeException(Throwable source, int code, String[] arguments) { + super(source); + 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, String debugMessage, String[] arguments) { + super(debugMessage, source); + this.errorCode = code; + this.arguments = arguments; + } + + + public ErrorCodeException(int category, int code, String debugMessage) { + this(category, code, debugMessage, 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) { + this(source, category, code, (String[]) 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) { + this(source, category, code, debugMessage, null); + } + + + 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 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 new file mode 100644 index 00000000..124fc358 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/resource/PackageManager.java @@ -0,0 +1,127 @@ +/** + * 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.db.resource; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import org.openo.commontosca.catalog.db.common.Parameters; +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; + +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 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; + } + + public ArrayList<PackageData> queryPackageByCsarId(String package_csarId) + throws CatalogResourceException { + Map<String, String> queryParam = new HashMap<String, String>(); + queryParam.put(Parameters.csarId.name(), package_csarId); + LOGGER.info("start query package info by csarid." + package_csarId); + ArrayList<PackageData> data = handler.query(queryParam); + LOGGER.info("query package info end.size:" + data.size() + "detail:" + + CatalogDbUtil.objectToString(data)); + return data; + } + + public ArrayList<PackageData> 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<String, String> queryParam = new HashMap<String, String>(); + 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<PackageData> data = handler.query(queryParam); + LOGGER.info("query package info end.size:" + data.size() + "detail:" + + CatalogDbUtil.objectToString(data)); + return data; + } + + 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); + } + + 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); + } + + public ArrayList<PackageData> 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<PackageData> data = handler.unionQuery(filter); + LOGGER.info("query package info end.size:" + data.size() + "detail:" + + CatalogDbUtil.objectToString(data)); + return data; + } + + 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 new file mode 100644 index 00000000..564116d8 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/resource/TemplateManager.java @@ -0,0 +1,207 @@ +/** + * 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.db.resource; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import org.openo.commontosca.catalog.db.common.Parameters; +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.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; + +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 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; + } + + 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<ServiceTemplateMappingData> queryServiceTemplateMappingById(String id) + throws CatalogResourceException { + Map<String, String> queryParam = new HashMap<String, String>(); + queryParam.put(Parameters.mappingId.name(), id); + LOGGER.info("start query serviceTemplateMapping info by id." + id); + ArrayList<ServiceTemplateMappingData> 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 { + + 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<String, String> delParam = new HashMap<String, String>(); + 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 "); + } + + public ArrayList<ServiceTemplateMappingData> queryServiceTemplateMapping(String nodeType, + String serviceTemplateId) throws CatalogResourceException { + Map<String, String> queryParam = new HashMap<String, String>(); + 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<ServiceTemplateMappingData> data = mappingHandler.query(queryParam); + LOGGER.info("query serviceTemplateMapping info end.size:" + data.size() + "detail:" + + CatalogDbUtil.objectToString(data)); + return data; + } + + public ArrayList<ServiceTemplateData> queryServiceTemplateById(String id) + throws CatalogResourceException { + Map<String, String> queryParam = new HashMap<String, String>(); + queryParam.put(Parameters.serviceTemplateId.name(), id); + LOGGER.info("start query serviceTemplate info by id." + id); + ArrayList<ServiceTemplateData> data = handler.query(queryParam); + LOGGER.info("query serviceTemplate info end.size:" + data.size() + "detail:" + + CatalogDbUtil.objectToString(data)); + return data; + } + + public ArrayList<ServiceTemplateData> queryServiceTemplate(String type, String version, + String vendor) throws CatalogResourceException { + LOGGER.info("start query serviceTemplate info.type:" + type + " vendor:" + vendor + + " version:" + version); + Map<String, String> queryParam = new HashMap<String, String>(); + 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<ServiceTemplateData> data = handler.query(queryParam); + LOGGER.info("query serviceTemplate info end.size:" + data.size() + "detail:" + + CatalogDbUtil.objectToString(data)); + return data; + } + + public ArrayList<NodeTemplateData> queryNodeTemplateBySeriviceTemplateId( + String serviceTemplateId) throws CatalogResourceException { + LOGGER.info("start query NodeTemplate info.serviceTemplateId:" + serviceTemplateId); + Map<String, String> queryParam = new HashMap<String, String>(); + queryParam.put(Parameters.serviceTemplateId.name(), serviceTemplateId); + ArrayList<NodeTemplateData> data = nodeTemplateHandler.query(queryParam); + LOGGER.info("query NodeTemplate info end.size:" + data.size() + "detail:" + + CatalogDbUtil.objectToString(data)); + return data; + } + + public ArrayList<NodeTemplateData> queryNodeTemplateById(String serviceTemplateId, + String nodeTemplateId) throws CatalogResourceException { + LOGGER.info("start query NodeTemplate info.serviceTemplateId:" + serviceTemplateId + + "nodeTemplateId:" + nodeTemplateId); + Map<String, String> queryParam = new HashMap<String, String>(); + if (CatalogDbUtil.isNotEmpty(serviceTemplateId)) + queryParam.put(Parameters.serviceTemplateId.name(), serviceTemplateId); + if (CatalogDbUtil.isNotEmpty(nodeTemplateId)) + queryParam.put(Parameters.nodeTemplateId.name(), nodeTemplateId); + ArrayList<NodeTemplateData> data = nodeTemplateHandler.query(queryParam); + LOGGER.info("query NodeTemplate info end.size:" + data.size() + "detail:" + + CatalogDbUtil.objectToString(data)); + return data; + } + + public ArrayList<ServiceTemplateData> 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<ServiceTemplateData> data = handler.unionQuery(filter); + 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<NodeTemplateData> nodeTemplateList = + queryNodeTemplateBySeriviceTemplateId(serviceTemplateId); + templateHandler.delete(serviceTemplateId, nodeTemplateList); + LOGGER.info(" delete serviceTemplate info end id." + serviceTemplateId); + } + + public void deleteServiceTemplateByCsarPackageInfo(PackageData packageInfo) + throws CatalogResourceException { + LOGGER.info("start delete serviceTemplate info by package.package:" + + CatalogDbUtil.objectToString(packageInfo)); + + ArrayList<ServiceTemplateData> 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 new file mode 100644 index 00000000..6924a305 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/util/CatalogDbUtil.java @@ -0,0 +1,44 @@ +/** + * 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.db.util; + +import java.util.UUID; + +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); + + public static String generateId() { + return UUID.randomUUID().toString(); + } + + public static boolean isNotEmpty(String s) { + return s != null && !"".equals(s) && s.length() > 0; + } + + 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 new file mode 100644 index 00000000..c7db51bf --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/util/HqlFactory.java @@ -0,0 +1,189 @@ +/** + * 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.db.util; + +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 + * + */ +public class HqlFactory { + + private final static 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); + } + } + } + + 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; + } + } + return false; + } + + public static <T> 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 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); + } + } + String sql = hql.toString(); + sql = sql.substring(0, sql.lastIndexOf("and")); + + logger.info("query hql is : " + sql); + return sql.trim(); + } + + 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 new file mode 100644 index 00000000..d5840930 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/BaseHandler.java @@ -0,0 +1,167 @@ +/** + * 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.db.wrapper; + +import java.util.List; +import java.util.Map; + +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; + +/** + * an abstract class for NFV wrapper class + * + * provide the common methods to process the CRUD rest request + * + * *@author 10159474 + * + * @param <T> + */ +public abstract class BaseHandler<T extends BaseData> { + 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; + } + + @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"); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public void delete(Map<String, String> queryParam, String resouceType) + throws CatalogResourceException { + logger.info("BaseHandler:start delete data by condition.info:" + + CatalogDbUtil.objectToString(queryParam)); + List<T> 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; + } + + } + + @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 "); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public List<T> query(Map<String, String> queryParam, String resouceType) + throws CatalogResourceException { + logger.info("BaseHandler:start query data .info:" + + CatalogDbUtil.objectToString(queryParam)); + List<T> 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; + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public List<T> unionQuery(String filter, String resouceType) throws CatalogResourceException { + logger.info("BaseHandler:start union query data.fliter:" + filter); + List<T> 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; + } + + @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; + } + + /** + * check if the related object id exists in the system + * + * @param data + * @throws CatalogResourceException + */ + 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 new file mode 100644 index 00000000..a96e9371 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/NodeTemplateHandler.java @@ -0,0 +1,53 @@ +/** + * 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.db.wrapper; + +import java.util.ArrayList; +import java.util.Map; + +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.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + ** @author 10159474 + */ +public class NodeTemplateHandler extends BaseHandler<NodeTemplateData> { + private static final Logger logger = LoggerFactory.getLogger(NodeTemplateHandler.class); + + public ArrayList<NodeTemplateData> query(Map<String, String> queryParam) + throws CatalogResourceException { + logger.info("NodeTemplateHandler query nodeTemplate info."); + ArrayList<NodeTemplateData> data = new ArrayList<NodeTemplateData>(); + Object result = query(queryParam, CatalogResuorceType.NODETEMPLATE.name()); + if (result != null) + data = (ArrayList<NodeTemplateData>) 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 { + + } + +} 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 new file mode 100644 index 00000000..8fd4d04c --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/PackageHandler.java @@ -0,0 +1,120 @@ +/** + * 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.db.wrapper; + +import java.util.ArrayList; +import java.util.Map; + +import org.openo.commontosca.catalog.db.common.CatalogResuorceType; +import org.openo.commontosca.catalog.db.common.Parameters; +import org.openo.commontosca.catalog.db.entity.PackageData; +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.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + ** @author 10159474 + */ +public class PackageHandler extends BaseHandler<PackageData> { + 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())) { + + 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; + } + + 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 delete(Map<String, String> queryParam) throws CatalogResourceException { + logger.info("packageHandler:start delete package info."); + delete(queryParam, 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."); + } + + 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<PackageData> unionQuery(String filter) throws CatalogResourceException { + logger.info("packageHandler query package info by union.filter:" + filter); + ArrayList<PackageData> data = new ArrayList<PackageData>(); + Object result = unionQuery(filter, CatalogResuorceType.PACKAGE.name()); + if (result != null) + data = data = (ArrayList<PackageData>) result; + else + logger.info("packageHandler: query package info is null."); + logger.info("packageHandler: query package info end"); + return data; + } + + public ArrayList<PackageData> query(Map<String, String> queryParam) + throws CatalogResourceException { + logger.info("packageHandler:start query package info."); + ArrayList<PackageData> data = new ArrayList<PackageData>(); + Object result = query(queryParam, CatalogResuorceType.PACKAGE.name()); + if (result != null) + data = (ArrayList<PackageData>) 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 { + + } + +} 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 new file mode 100644 index 00000000..4412dee3 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/ServiceTemplateHandler.java @@ -0,0 +1,78 @@ +/** + * 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.db.wrapper; + +import java.util.ArrayList; +import java.util.Map; + +import org.openo.commontosca.catalog.db.common.CatalogResuorceType; +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.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + ** @author 10159474 + */ +public class ServiceTemplateHandler extends BaseHandler<TemplateData> { + private static final Logger logger = LoggerFactory.getLogger(ServiceTemplateHandler.class); + + @Override + public void check(TemplateData data) throws CatalogResourceException { + // TODO Auto-generated method stub + + } + + public ArrayList<ServiceTemplateData> query(Map<String, String> queryParam) + throws CatalogResourceException { + logger.info("ServiceTemplateHandler query serviceTemplate info."); + ArrayList<ServiceTemplateData> data = new ArrayList<ServiceTemplateData>(); + Object result = query(queryParam, CatalogResuorceType.SERVICETEMPLATE.name()); + if (result != null) + data = (ArrayList<ServiceTemplateData>) result; + else + logger.info("ServiceTemplateHandler: query serviceTemplate info is null."); + logger.info("ServiceTemplateHandler: query serviceTemplate info end."); + return data; + } + + public ArrayList<ServiceTemplateData> unionQuery(String filter) throws CatalogResourceException { + logger.info("ServiceTemplateHandler query serviceTemplate info by union.filter:" + filter); + ArrayList<ServiceTemplateData> data = new ArrayList<ServiceTemplateData>(); + Object result = unionQuery(filter, CatalogResuorceType.SERVICETEMPLATE.name()); + if (result != null) + data = (ArrayList<ServiceTemplateData>) 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; + } + +} 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 new file mode 100644 index 00000000..25f7982e --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/ServiceTemplateMappingHandler.java @@ -0,0 +1,93 @@ +/** + * 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.db.wrapper; + +import java.util.ArrayList; +import java.util.Map; + +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.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + ** @author 10159474 + */ +public class ServiceTemplateMappingHandler extends BaseHandler<ServiceTemplateMappingData> { + 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; + } + + 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 void delete(Map<String, String> delParam) throws CatalogResourceException { + logger.info("ServiceTemplateMappingHandler:start delete mapping info."); + delete(delParam, CatalogResuorceType.SERVICETEMPLATEMAPPING.name()); + logger.info("ServiceTemplateMappingHandler:delete mapping info end."); + } + + public ArrayList<ServiceTemplateMappingData> query(Map<String, String> queryParam) + throws CatalogResourceException { + logger.info("ServiceTemplateMappingHandler:start query mapping info."); + ArrayList<ServiceTemplateMappingData> data = new ArrayList<ServiceTemplateMappingData>(); + Object result = query(queryParam, CatalogResuorceType.SERVICETEMPLATEMAPPING.name()); + if (result != null) + data = (ArrayList<ServiceTemplateMappingData>) 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 + + } + + + +} 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 new file mode 100644 index 00000000..714dd06b --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/db/wrapper/TemplateHandler.java @@ -0,0 +1,76 @@ +/** + * 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.db.wrapper; + +import java.util.ArrayList; + +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.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + ** @author 10159474 + */ +public class TemplateHandler extends BaseHandler<TemplateData> { + 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; + } + + @Override + public void check(TemplateData data) throws CatalogResourceException { + // TODO Auto-generated method stub + + } + + public void delete(String serviceTemplateId, ArrayList<NodeTemplateData> 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 new file mode 100644 index 00000000..671a8514 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/CSARPackage.java @@ -0,0 +1,101 @@ +/** + * 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..a9c43e4c --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/CSARQueryCondition.java @@ -0,0 +1,38 @@ +/**
+ * 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/EnumOperationalState.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumOperationalState.java new file mode 100644 index 00000000..b1f16ec6 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumOperationalState.java @@ -0,0 +1,20 @@ +/**
+ * 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 enum EnumOperationalState {
+ 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 new file mode 100644 index 00000000..62dab552 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumProcessState.java @@ -0,0 +1,24 @@ +/**
+ * 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;
+
+/**
+ * @author 00164331
+ *
+ */
+public enum EnumProcessState {
+ 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 new file mode 100644 index 00000000..7a25d748 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumType.java @@ -0,0 +1,20 @@ +/**
+ * 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 enum EnumType {
+ 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 new file mode 100644 index 00000000..e2ffed13 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/EnumUsageState.java @@ -0,0 +1,20 @@ +/**
+ * 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 enum EnumUsageState {
+ 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 new file mode 100644 index 00000000..2d3e80c4 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/VnfPackage.java @@ -0,0 +1,100 @@ +/**
+ * 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 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;
+ }
+}
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 new file mode 100644 index 00000000..998c2121 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/request/PackageBasicInfo.java @@ -0,0 +1,38 @@ +/**
+ * 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.request;
+
+import org.openo.commontosca.catalog.entity.EnumType;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+public class PackageBasicInfo {
+
+ private String provider;
+
+ private EnumType type;
+
+ private String version;
+
+ 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 new file mode 100644 index 00000000..c3a7850b --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/request/UploadPackageFromFtpRequest.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.entity.request;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import org.openo.commontosca.catalog.entity.EnumType;
+
+/**
+ * @author 00164331
+ *
+ */
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+public class UploadPackageFromFtpRequest {
+
+ private String provider;
+
+ private EnumType type;
+
+ private String version;
+
+ 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 new file mode 100644 index 00000000..a418cc75 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/response/CsarFileUriResponse.java @@ -0,0 +1,35 @@ +/**
+ * 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.response;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+
+/**
+ * @author 00164331
+ *
+ */
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+public class CsarFileUriResponse {
+
+ private String downloadUri;
+
+ 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 new file mode 100644 index 00000000..e727c3e6 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/response/PackageMeta.java @@ -0,0 +1,61 @@ +/**
+ * 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.response;
+
+import org.openo.commontosca.catalog.entity.EnumProcessState;
+import org.openo.commontosca.catalog.entity.EnumOperationalState;
+import org.openo.commontosca.catalog.entity.EnumUsageState;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+public class PackageMeta {
+
+ private String csarId;
+
+ private String name;
+
+ private String downloadUri;
+
+ private String size;
+
+ private String version;
+
+ private String provider;
+
+ private String type;
+
+ private String format;
+
+ private boolean deletionPending;
+
+ private String createTime;
+
+ private String modifyTime;
+
+ private EnumOperationalState operationalState;
+
+ private EnumUsageState usageState;
+
+ private String onBoardState;
+
+ 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 new file mode 100644 index 00000000..6c7beb73 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/response/UpdatePackageResponse.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.entity.response;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+public class UpdatePackageResponse {
+
+ 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 new file mode 100644 index 00000000..3542155f --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/entity/response/UploadPackageResponse.java @@ -0,0 +1,30 @@ +/**
+ * 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.response;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+public class UploadPackageResponse {
+
+ private String csarId;
+
+}
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 new file mode 100644 index 00000000..69870d0c --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/FileManager.java @@ -0,0 +1,36 @@ +/** + * 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.filemanage; + +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); + + boolean download(String srcPath, String dstPath); + + boolean delete(String srcPath); + + ArrayList<FileLink> 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 new file mode 100644 index 00000000..b8e4ba90 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/FileManagerFactory.java @@ -0,0 +1,48 @@ +/** + * 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.filemanage; + +import org.openo.commontosca.catalog.filemanage.http.HttpFileManagerImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class FileManagerFactory { + private static final Logger logger = LoggerFactory.getLogger(FileManagerFactory.class); + + private static FileManager getHttpFileManager() { + return new HttpFileManagerImpl(); + } + + 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; + } +} 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 new file mode 100644 index 00000000..eab0ee3f --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/FileManagerType.java @@ -0,0 +1,23 @@ +/** + * 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.filemanage; + +public enum FileManagerType { + 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 new file mode 100644 index 00000000..9149d529 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/entity/FileLink.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.filemanage.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class FileLink { + 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 new file mode 100644 index 00000000..c323f11a --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/http/HttpFileManagerImpl.java @@ -0,0 +1,85 @@ +/** + * 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.filemanage.http; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; + +import org.openo.commontosca.catalog.filemanage.FileManager; +import org.openo.commontosca.catalog.filemanage.entity.FileLink; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HttpFileManagerImpl implements FileManager { + 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()); + try { + ToolUtil.copyDirectory(srcPath, ToolUtil.getHttpServerPath() + dstPath, true); + } catch (IOException e) { + flag = false; + LOGGER.error("copy file failed.errorMsg:" + e.getMessage()); + } + LOGGER.info("upload file success!"); + 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<FileLink> queryWorkFlow(String path) { + LOGGER.info("start query workFlow from http server.path:" + path); + File workFlowRoot = new File(ToolUtil.getHttpServerPath() + path); + ArrayList<FileLink> fileLinks = new ArrayList<FileLink>(); + 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; + } + +} 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 new file mode 100644 index 00000000..c90e6dbe --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/filemanage/http/ToolUtil.java @@ -0,0 +1,164 @@ +/** + * 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.filemanage.http; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +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; + } + + 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; + } + } + 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; + } + + 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; + } + } + } + + 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(); + } + } + } + + 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; + } + } + } + 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 new file mode 100644 index 00000000..74b30662 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/ftp/Ftp.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.ftp;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+
+/**
+ * @author 00164331
+ *
+ */
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+public class Ftp {
+
+ private String ipAddr;
+
+ private Integer port;
+
+ private String userName;
+
+ private String pwd;
+
+ 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 new file mode 100644 index 00000000..cec4d30f --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/ftp/FtpUtil.java @@ -0,0 +1,212 @@ +/**
+ * 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.ftp;
+
+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 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;
+ }
+
+ /**
+ * 关闭ftp连接
+ */
+ public static void closeFtp() {
+ if (ftp != null && ftp.isConnected()) {
+ try {
+ ftp.logout();
+ ftp.disconnect();
+ } catch (IOException e) {
+ e.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();
+ }
+ }
+ } else {
+ File file2 = new File(f.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)) {
+
+ 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("下载过程中出现异常");
+ }
+ } else {
+ logger.error("链接失败!");
+ }
+
+ }
+
+
+ /**
+ *
+ * 下载FTP文件 当你需要下载FTP文件的时候,调用此方法 根据<b>获取的文件名,本地地址,远程地址</b>进行下载
+ *
+ * @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);
+ }
+ }
+ }
+}
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 new file mode 100644 index 00000000..b517bc8b --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/health/ConsoleHealthCheck.java @@ -0,0 +1,35 @@ +/**
+ * 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.health;
+
+import com.codahale.metrics.health.HealthCheck;
+
+public class ConsoleHealthCheck extends HealthCheck {
+ private final String 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();
+ }
+}
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 new file mode 100644 index 00000000..0627d743 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/common/EnumToscaNodeTypeDefinition.java @@ -0,0 +1,60 @@ +/**
+ * 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.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;
+ }
+}
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 new file mode 100644 index 00000000..2aecf42c --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/common/EnumToscaRelationShipDefinition.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.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();
+
+}
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 new file mode 100644 index 00000000..859ea522 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/common/TemplateDataHelper.java @@ -0,0 +1,246 @@ +/** + * 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.common; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.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<NodeTemplate> 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<NodeTemplateData> convert2NodeTemplateDataList( + List<NodeTemplate> ntList, String serviceTemplateId) { + ArrayList<NodeTemplateData> 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<ServiceTemplateData> stdList) { + List<ServiceTemplate> stList = new ArrayList<>(); + for (ServiceTemplateData std : stdList) { + stList.add(convert2ServiceTemplate(std)); + } + + 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<NodeTemplateData> ntdList) { + List<NodeTemplate> 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<RelationShip> relationShips = convert2RelationShipList(ntd + .getRelationShips()); + return new NodeTemplate(ntd.getNodeTemplateId(), ntd.getName(), + ntd.getType(), convert2Property(ntd.getProperties()), + relationShips); + } + + /** + * @param sRelationShips + * @return + */ + private static List<RelationShip> convert2RelationShipList( + String sRelationShips) { + RelationShip[] relationShips = ToolUtil.fromJson(sRelationShips, + RelationShip[].class); + return Arrays.asList(relationShips); + } + + /** + * @param properties + * @return + */ + private static Map<String, Object> convert2Property(String properties) { + JsonObject jsonObject = new Gson().fromJson(properties, + JsonObject.class); + return parseMapValue(jsonObject); + } + + private static Map<String, Object> parseMapValue(JsonObject jsonObject) { + Map<String, Object> map = new HashMap<>(); + + Iterator<Entry<String, JsonElement>> iterator = jsonObject.entrySet() + .iterator(); + while (iterator.hasNext()) { + Entry<String, JsonElement> 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()); + } + +} 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 new file mode 100644 index 00000000..3bafbbef --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/EnumDataType.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.entity; + +import lombok.AllArgsConstructor; + +/** + * @author 10090474 + * + */ +@AllArgsConstructor +public enum EnumDataType { + STRING("String"), INTEGER("Integer"), FLOAT("Float"), BOOLEAN("Boolean"); + + private String value; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = 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 new file mode 100644 index 00000000..1f8a1b49 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/InputParameter.java @@ -0,0 +1,36 @@ +/** + * 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; + +/** + * @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; +} 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 new file mode 100644 index 00000000..b582b876 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/KeyValuePair.java @@ -0,0 +1,28 @@ +/** + * 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 KeyValuePair { + 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 new file mode 100644 index 00000000..ab606621 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/NfvTemplate.java @@ -0,0 +1,33 @@ +/** + * 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 java.util.List; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class NfvTemplate { + private List<NodeTemplate> vduNodes; + private List<NodeTemplate> networkNodes; + private List<NodeTemplate> vnfcNodes; + private List<NodeTemplate> 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 new file mode 100644 index 00000000..f2a8ca34 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/NodeTemplate.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 java.util.List; +import java.util.Map; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class NodeTemplate { + private String id; + private String name; + private String type; + private Map<String, Object> properties; + private List<RelationShip> relationShips; +} 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 new file mode 100644 index 00000000..6eff7437 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/QueryRawDataCondition.java @@ -0,0 +1,33 @@ +/** + * 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; + +/** + * @author 10090474 + * + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class QueryRawDataCondition { + 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 new file mode 100644 index 00000000..a65e74d4 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/RelationShip.java @@ -0,0 +1,31 @@ +/** + * 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 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 new file mode 100644 index 00000000..703103b3 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/ServiceTemplate.java @@ -0,0 +1,35 @@ +/** + * 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 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; +} 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 new file mode 100644 index 00000000..dab206c2 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/ServiceTemplateOperation.java @@ -0,0 +1,30 @@ +/** + * 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 ServiceTemplateOperation { + private String name; + private String description; + 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 new file mode 100644 index 00000000..351f74e4 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/ServiceTemplateRawData.java @@ -0,0 +1,27 @@ +/** + * 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 ServiceTemplateRawData { + 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 new file mode 100644 index 00000000..56223381 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/entity/SubstitutionMapping.java @@ -0,0 +1,66 @@ +/** + * 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 java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @author 10090474 + * + */ + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class SubstitutionMapping { + private String serviceTemplateId; + private String node_type; + private List<Map<String, String[]>> requirements = new ArrayList<>(); + private Map<String, String[]> capabilities = new HashMap<String, String[]>(); + + /** + * @param key + * @param value + * @return + */ + public boolean putRequirement(String key, String[] value) { + Map<String, String[]> requirement = new HashMap<>(); + requirement.put(key, value); + return this.requirements.add(requirement); + } + + /** + * @param key + * @param value + * @return + */ + 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; + } +} 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 new file mode 100644 index 00000000..e6a6423c --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerSelfServiceProvider.java @@ -0,0 +1,66 @@ +/** + * 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.container; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.MessageBodyReader; +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; + + +/** + * The opentosca container self service returns data to the entity + * @author 10189609 + * + */ +public class ContainerSelfServiceProvider implements + MessageBodyReader<ContainerSelfService> { + + @Override + public boolean isReadable(Class<?> type, Type genericType, + Annotation[] annotations, MediaType mediaType) { + return ContainerSelfService.class.isAssignableFrom(type); + } + + @Override + public ContainerSelfService readFrom(Class<ContainerSelfService> type, + Type genericType, Annotation[] annotations, MediaType mediaType, + MultivaluedMap<String, String> 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; + } + +} 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 new file mode 100644 index 00000000..d6f70d0c --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerServiceConsumer.java @@ -0,0 +1,232 @@ +/** + * 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.container; + +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; + +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.media.multipart.BodyPart; +import org.glassfish.jersey.media.multipart.FormDataBodyPart; +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.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.eclipsesource.jaxrs.consumer.ConsumerFactory; +import com.google.gson.JsonObject; + +/** + * 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); + } + + /** + * 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; + } + } + } + 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<ContainerSelfServiceOption> 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(); + } + + /** + * 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; + } + + /** + * 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(); + } + + /** + * 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); + } + + /** + * 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(); + } + + /** + * http://127.0.0.1:1337 + * + * @return + */ + 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 new file mode 100644 index 00000000..daf57c28 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerServiceNodeTemplateProvider.java @@ -0,0 +1,76 @@ +/** + * 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.container; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.MessageBodyReader; +import javax.xml.bind.JAXBContext; +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 + * @author 10189609 + * + */ +public class ContainerServiceNodeTemplateProvider implements + MessageBodyReader<ContainerServiceNodeTemplateList> { + + @Override + public boolean isReadable(Class<?> type, Type genericType, + Annotation[] annotations, MediaType mediaType) { + return ContainerServiceNodeTemplateList.class.isAssignableFrom(type); + } + + @Override + public ContainerServiceNodeTemplateList readFrom( + Class<ContainerServiceNodeTemplateList> type, Type genericType, + Annotation[] annotations, MediaType mediaType, + MultivaluedMap<String, String> 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; + } + +} 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 new file mode 100644 index 00000000..5cb25499 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerServicePackageProvider.java @@ -0,0 +1,66 @@ +/** + * 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.container; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.MessageBodyReader; +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; + +/** + * The opentosca container service returns data to the package entity + * @author 10189609 + * + */ +public class ContainerServicePackageProvider implements MessageBodyReader<ContainerServicePackageList> { + + @Override + public boolean isReadable(Class<?> type, Type genericType, + Annotation[] annotations, MediaType mediaType) { + return ContainerServicePackageList.class.isAssignableFrom(type); + } + + @Override + public ContainerServicePackageList readFrom( + Class<ContainerServicePackageList> type, Type genericType, + Annotation[] annotations, MediaType mediaType, + MultivaluedMap<String, String> 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; + } + +} 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 new file mode 100644 index 00000000..38a66ddd --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/ContainerServiceTemplateProvider.java @@ -0,0 +1,68 @@ +/** + * 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.container; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.MessageBodyReader; +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; + +/** + * The opentosca container self service returns data to the service template entity + * @author 10189609 + * + */ +public class ContainerServiceTemplateProvider implements + MessageBodyReader<ContainerServiceTemplateList> { + + @Override + public boolean isReadable(Class<?> type, Type genericType, + Annotation[] annotations, MediaType mediaType) { + return ContainerServiceTemplateList.class.isAssignableFrom( type ); + } + + @Override + public ContainerServiceTemplateList readFrom(Class<ContainerServiceTemplateList> type, + Type genericType, Annotation[] annotations, MediaType mediaType, + MultivaluedMap<String, String> 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; + } + +} 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 new file mode 100644 index 00000000..e471ea16 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/IContainerExtPackageRest.java @@ -0,0 +1,48 @@ +/** + * 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.container; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +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 org.openo.commontosca.catalog.model.externalservice.entity.containerEntity.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); +} 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 new file mode 100644 index 00000000..a12c0a1b --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/IContainerPortabilityRest.java @@ -0,0 +1,33 @@ +/** + * 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.container; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +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); +} 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 new file mode 100644 index 00000000..29a59f99 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/IContainerSelfServiceRest.java @@ -0,0 +1,47 @@ +/** + * 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.container; + +import javax.ws.rs.GET; +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; + +/** + * 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); +} 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 new file mode 100644 index 00000000..5573d996 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/IContainerTemplateRest.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.container; + +import javax.ws.rs.GET; +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 org.openo.commontosca.catalog.model.externalservice.entity.containerEntity.ContainerServiceNodeTemplateList; +import org.openo.commontosca.catalog.model.externalservice.entity.containerEntity.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); +} 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 new file mode 100644 index 00000000..4f71996e --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/NamespaceFilter.java @@ -0,0 +1,96 @@ +/**
+ * 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.container;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.XMLFilterImpl;
+
+/**
+ * NamespaceFilter
+ * @author 10189609
+ *
+ */
+public class NamespaceFilter extends XMLFilterImpl {
+
+ private String usedNamespaceUri;
+ private boolean addNamespace;
+
+ //State variable
+ private boolean addedNamespace = false;
+
+ public NamespaceFilter(String namespaceUri,
+ boolean addNamespace) {
+ super();
+
+ 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 startElement(String arg0, String arg1, String arg2,
+ Attributes arg3) throws SAXException {
+
+ super.startElement(this.usedNamespaceUri, arg1, arg2, arg3);
+ }
+
+ @Override
+ public void endElement(String arg0, String arg1, String arg2)
+ 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!
+ }
+
+ }
+
+ 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);
+
+ //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 new file mode 100644 index 00000000..6eb9b95c --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/container/StringProvider.java @@ -0,0 +1,49 @@ +/** + * 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.container; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.MessageBodyReader; + +/** + * The opentosca container service returns data directly. + * @author 10189609 + * + */ +public class StringProvider implements MessageBodyReader<String> { + + @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<String> type, Type genericType, + Annotation[] annotations, MediaType mediaType, + MultivaluedMap<String, String> 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/containerEntity/ContainerSelfService.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerSelfService.java new file mode 100644 index 00000000..c01dee6b --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerSelfService.java @@ -0,0 +1,87 @@ +/** + * 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<ContainerSelfServiceOption> 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<ContainerSelfServiceOption> getOptionList() { + return optionList; + } + + public void setOptionList(List<ContainerSelfServiceOption> 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 new file mode 100644 index 00000000..ee5794df --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerSelfServiceOption.java @@ -0,0 +1,82 @@ +/** + * 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 new file mode 100644 index 00000000..3be5de90 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceCommonParam.java @@ -0,0 +1,45 @@ +/** + * 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 new file mode 100644 index 00000000..de4a6cd0 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceNodeTemplate.java @@ -0,0 +1,320 @@ +/** + * 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<ContainerServiceCommonParam> properties; + + @XmlElementWrapper(name = "relationshipInfos") + @XmlElement(name = "relationship") + private List<ContainerServiceRelationShip> 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<ContainerServiceCommonParam> getProperties() { + return properties; + } + + public void setProperties(List<ContainerServiceCommonParam> properties) { + this.properties = properties; + } + + public List<ContainerServiceRelationShip> getRelationShips() { + return relationShips; + } + + public void setRelationShips( + List<ContainerServiceRelationShip> relationShips) { + this.relationShips = relationShips; + } + + @XmlRootElement + @XmlAccessorType(XmlAccessType.NONE) + public static class Capablitiies { + @XmlElement(name = "Capability") + private List<ContainerServiceNodeTemplate.Capability> capabilityList; + + public List<ContainerServiceNodeTemplate.Capability> getCapabilityList() { + return capabilityList; + } + + public void setCapabilityList( + List<ContainerServiceNodeTemplate.Capability> 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<NTFlavor> getNTFlavorList() { + if (null == this.capabilities + || ToolUtil.isEmptyCollection(capabilities.getCapabilityList())) { + return null; + } + + List<NTFlavor> ntFlavors = new ArrayList<NTFlavor>(); + List<Capability> 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 new file mode 100644 index 00000000..096da0e6 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceNodeTemplateList.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.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<ContainerServiceNodeTemplate> nodeTemplate; + + public List<ContainerServiceNodeTemplate> getNodeTemplate() { + return nodeTemplate; + } + + public void setNodeTemplate(List<ContainerServiceNodeTemplate> 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 new file mode 100644 index 00000000..215b3ed5 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceOperationParameter.java @@ -0,0 +1,24 @@ +/** + * 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 new file mode 100644 index 00000000..c91b6e1e --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServicePackage.java @@ -0,0 +1,53 @@ +/** + * 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 new file mode 100644 index 00000000..c3b7dd73 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServicePackageList.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.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<ContainerServicePackage> packageList; + + public List<ContainerServicePackage> getPackageList() { + return packageList; + } + + public void setPackageList(List<ContainerServicePackage> 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 new file mode 100644 index 00000000..08b238fc --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceRelationShip.java @@ -0,0 +1,79 @@ +/** + * 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 new file mode 100644 index 00000000..f7165c12 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceTemplate.java @@ -0,0 +1,336 @@ +/** + * 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<STFlavor> getStFlavor() { + return stFlavor; + } + + public void setStFlavor(List<STFlavor> 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> 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> 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<STFlavorConstituent> getStFlavorConstituent() { + return stFlavorConstituent; + } + + public void setStFlavorConstituent( + List<STFlavorConstituent> 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<STFlavor> 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 new file mode 100644 index 00000000..81021f52 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/containerEntity/ContainerServiceTemplateList.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.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<ContainerServiceTemplate> serviceTemplateList; + + public List<ContainerServiceTemplate> getServiceTemplateList() { + return serviceTemplateList; + } + + public void setServiceTemplateList(List<ContainerServiceTemplate> optionList) { + this.serviceTemplateList = optionList; + } +} 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 new file mode 100644 index 00000000..3d317c6d --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/lifecycleEnity/InstanceEntity.java @@ -0,0 +1,28 @@ +/** + * 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/roEntity/ResourceResponseEntity.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/roEntity/ResourceResponseEntity.java new file mode 100644 index 00000000..d98bb87c --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/roEntity/ResourceResponseEntity.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.roEntity; + +import java.util.ArrayList; + +public class ResourceResponseEntity +{ + ArrayList <VimEntity> data=new ArrayList<VimEntity>(); + String operationResult; + + public String getOperationResult() + { + return operationResult; + } + + public void setOperationResult(String operationResult) + { + this.operationResult = operationResult; + } + public ArrayList <VimEntity> getData() + { + return data; + } + public void setData(ArrayList <VimEntity> 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 new file mode 100644 index 00000000..98f59200 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/entity/roEntity/VimEntity.java @@ -0,0 +1,63 @@ +/** + * 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 new file mode 100644 index 00000000..df87a529 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/lifecycle/ILifeCycleServiceRest.java @@ -0,0 +1,33 @@ +/**
+ * 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.lifecycle;
+
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+
+/**
+ * The lifecycle interface.
+ * @author 10189609
+ *
+ */
+@Path("/appinstances")
+public interface ILifeCycleServiceRest {
+ @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 new file mode 100644 index 00000000..f3bed0a0 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/lifecycle/LifeCycleServiceConsumer.java @@ -0,0 +1,61 @@ +/**
+ * 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.lifecycle;
+
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+
+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.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.eclipsesource.jaxrs.consumer.ConsumerFactory;
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+
+/**
+ * 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<InstanceEntity> 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<ArrayList<InstanceEntity>>() {}.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 new file mode 100644 index 00000000..d4075abe --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/ro/IResourceServiceRest.java @@ -0,0 +1,35 @@ +/**
+ * 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.ro;
+
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+
+/**
+ * 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;
+}
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 new file mode 100644 index 00000000..65431a2b --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/externalservice/ro/ResourceServiceConsumer.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.ro;
+
+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.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);
+ }
+}
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 new file mode 100644 index 00000000..22780a31 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/AbstractModelParser.java @@ -0,0 +1,30 @@ +/**
+ * 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.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;
+
+}
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 new file mode 100644 index 00000000..10f60b99 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/EnumPackageFormat.java @@ -0,0 +1,25 @@ +/**
+ * 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.parser;
+
+/**
+ * enum data.
+ * @author 10189609
+ *
+ */
+public enum EnumPackageFormat {
+ 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 new file mode 100644 index 00000000..e84bc871 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/EnumTemplateType.java @@ -0,0 +1,20 @@ +/**
+ * 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.parser;
+
+public enum EnumTemplateType {
+ 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 new file mode 100644 index 00000000..74c2e2c1 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/ModelParserFactory.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.parser;
+
+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 Map<EnumPackageFormat, AbstractModelParser> pkgType2ParseMap = new HashMap<EnumPackageFormat, AbstractModelParser>();
+
+ private ModelParserFactory() {
+ // PackageParseMap.put(EnumPackageFormat.TOSCA_XML, new
+ // ToscaXmlModelParser());
+ pkgType2ParseMap.put(EnumPackageFormat.TOSCA_YAML, new ToscaYamlModelParser());
+ }
+
+ /**
+ *
+ * @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);
+ }
+}
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 new file mode 100644 index 00000000..17932538 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/ToscaYamlModelParser.java @@ -0,0 +1,372 @@ +/**
+ * 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.parser;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+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<String, String> 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<NodeTemplate> 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));
+ }
+
+ return st.getServiceTemplateId();
+ }
+
+ /**
+ * @param fileLocation
+ * @return
+ * @throws CatalogResourceException
+ */
+ @SuppressWarnings("resource")
+ private Map<String, String> parseToscaMeta(String fileLocation)
+ throws CatalogResourceException {
+ Map<String, String> 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;
+ }
+ }
+
+ } catch (IOException e) {
+ throw new CatalogResourceException("Parse Tosca Meta Fail.", e);
+ } finally {
+ closeStreamAndReader(zin, br);
+ }
+
+ return toscaMeta;
+ }
+
+ 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) {
+ }
+ }
+ }
+
+ private ParseYamlRequestParemeter comboRequest(String fileLocation) {
+ ParseYamlRequestParemeter request = new ParseYamlRequestParemeter();
+ request.setPath(fileLocation);
+ return request;
+ }
+
+ /**
+ * @param serviceTemplateId
+ * @param result
+ * @return
+ */
+ private SubstitutionMapping parseSubstitutionMapping(
+ String serviceTemplateId, ParseYamlResult result) {
+ String type = getSubstitutionMappingType(result);
+ if (ToolUtil.isTrimedEmptyString(type)) {
+ return null;
+ }
+
+ 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));
+ ServiceTemplateOperation[] operations = parseOperations(result
+ .getPlanList());
+ st.setOperations(operations);
+ return st;
+ }
+
+ /**
+ * @param planList
+ * @return
+ */
+ private ServiceTemplateOperation[] parseOperations(List<ParseYamlResult.Plan> planList) {
+ if (planList == null || planList.isEmpty()) {
+ return new ServiceTemplateOperation[0];
+ }
+
+ List<ServiceTemplateOperation> 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);
+
+ opList.add(op);
+
+ }
+ return opList.toArray(new ServiceTemplateOperation[0]);
+ }
+
+ /**
+ * @param inputList
+ * @return
+ */
+ private InputParameter[] parsePlanInputs(List<ParseYamlResult.Plan.PlanValue.PlanInput> inputList) {
+ if (inputList == null || inputList.isEmpty()) {
+ return new InputParameter[0];
+ }
+
+ List<InputParameter> 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 InputParameter[] parseInputs(ParseYamlResult result) {
+ List<ParseYamlResult.TopologyTemplate.Input> inputList = result.getTopologyTemplate().getInputs();
+ if(inputList == null){
+ return null;
+ }
+ ArrayList<InputParameter> retList = new ArrayList<InputParameter>();
+ 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]);
+ }
+
+ /**
+ * @param type
+ * @return
+ */
+ private EnumDataType getEnumDataType(String type) {
+ if (EnumDataType.INTEGER.toString().equalsIgnoreCase(type)) {
+ return EnumDataType.INTEGER;
+ }
+
+ if (EnumDataType.FLOAT.toString().equalsIgnoreCase(type)) {
+ return EnumDataType.FLOAT;
+ }
+
+ if (EnumDataType.BOOLEAN.toString().equalsIgnoreCase(type)) {
+ return EnumDataType.BOOLEAN;
+ }
+
+ return EnumDataType.STRING;
+ }
+
+ /**
+ * @param csarId
+ * @param templateId
+ * @param result
+ * @return
+ */
+ private List<NodeTemplate> parseNodeTemplates(String csarId,
+ String templateId, ParseYamlResult result) {
+ List<ParseYamlResult.TopologyTemplate.NodeTemplate> nodetemplateList = result.getTopologyTemplate().getNodeTemplates();
+ if(nodetemplateList == null){
+ return null;
+ }
+
+ List<NodeTemplate> 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<RelationShip> relationShipList = parseNodeTemplateRelationShip(nodeTemplate
+ .getRelationships());
+ ret.setRelationShips(relationShipList);
+
+ retList.add(ret);
+ }
+
+ return retList;
+ }
+
+
+ private List<RelationShip> parseNodeTemplateRelationShip(
+ List<ParseYamlResult.TopologyTemplate.NodeTemplate.Relationship> relationshipList) {
+ List<RelationShip> 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);
+ }
+
+ return retList;
+ }
+
+ private EnumTemplateType getTemplateType(ParseYamlResult result,
+ List<NodeTemplate> ntList) {
+ String type = getSubstitutionMappingType(result);
+ if (isNSType(type)) {
+ return EnumTemplateType.NS;
+ }
+
+ if (isVNFType(type)) {
+ return EnumTemplateType.VNF;
+ }
+
+ return getTemplateTypeFromNodeTemplates(ntList);
+ }
+
+ private String getSubstitutionMappingType(ParseYamlResult result) {
+ if (result.getTopologyTemplate().getSubstitutionMappings() == null) {
+ return null;
+ }
+ return result.getTopologyTemplate().getSubstitutionMappings()
+ .getNode_type();
+ }
+
+ /**
+ * @param ntList
+ * @return
+ */
+ private EnumTemplateType getTemplateTypeFromNodeTemplates(
+ List<NodeTemplate> ntList) {
+ for (NodeTemplate nt : ntList) {
+ if (isNSType(nt.getType()) || isVNFType(nt.getType())) {
+ return EnumTemplateType.NS;
+ }
+ }
+
+ 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");
+ }
+}
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 new file mode 100644 index 00000000..8d24a606 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/IYamlParseRest.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.parser.yaml;
+
+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;
+}
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 new file mode 100644 index 00000000..5942a8bd --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/YamlParseServiceConsumer.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.parser.yaml;
+
+import org.glassfish.jersey.client.ClientConfig;
+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 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);
+ }
+
+ }
+}
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 new file mode 100644 index 00000000..ea9fe998 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/entity/EnumYamlServiceTemplateInfo.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.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();
+}
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 new file mode 100644 index 00000000..49d6f4cb --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/entity/ParseYamlRequestParemeter.java @@ -0,0 +1,61 @@ +/**
+ * 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.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<Extension> extensionList;
+
+ public String getPath() {
+ return path;
+ }
+
+ public void setPath(String path) {
+ this.path = path;
+ }
+
+ public List<Extension> getExtensionList() {
+ return extensionList;
+ }
+
+ public void setExtensionList(List<Extension> 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 setName(String name) {
+ this.name = name;
+ }
+ 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/parser/yaml/entity/ParseYamlResult.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/entity/ParseYamlResult.java new file mode 100644 index 00000000..fa9cdf7b --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/parser/yaml/entity/ParseYamlResult.java @@ -0,0 +1,843 @@ +/**
+ * 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.parser.yaml.entity;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+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 description;
+ private JsonObject nodeTypes;
+ private JsonObject capabilityTypes;
+ private JsonObject relationshipTypes;
+ private JsonObject policyTypes;
+ private TopologyTemplate topologyTemplate;
+ private Map<String, String> 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;
+ }
+
+ /**
+ * @return
+ */
+ public List<NodeType> getNodeTypeList() {
+ return jsonObject2NodeTypes(nodeTypes);
+ }
+
+ private ArrayList<NodeType> jsonObject2NodeTypes(JsonObject nodeTypes) {
+ ArrayList<NodeType> nodeTypeList = new ArrayList<NodeType>();
+ Iterator<Entry<String, JsonElement>> iterator = nodeTypes.entrySet().iterator();
+ while (iterator.hasNext()) {
+ NodeType type = new NodeType();
+ Entry<String, JsonElement> 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<RelationshipType> getRelationshipTypeList() {
+ return jsonObject2RelationshipTypes(relationshipTypes);
+ }
+
+ /**
+ * @param relationshipTypes
+ * @return
+ */
+ private ArrayList<RelationshipType> jsonObject2RelationshipTypes(JsonObject relationshipTypes) {
+ ArrayList<RelationshipType> relationshipTypeList = new ArrayList<RelationshipType>();
+ Iterator<Entry<String, JsonElement>> iterator = relationshipTypes.entrySet().iterator();
+ while (iterator.hasNext()) {
+ RelationshipType type = new RelationshipType();
+ Entry<String, JsonElement> 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<String, String> getMetadata() {
+ return metadata;
+ }
+
+ public void setMetadata(Map<String, String> metadata) {
+ this.metadata = metadata;
+ }
+
+ public JsonObject getPlans() {
+ return plans;
+ }
+
+ public void setPlans(JsonObject plans) {
+ this.plans = plans;
+ }
+
+ public List<Plan> getPlanList() {
+ return jsonObject2PlanList(this.plans);
+ }
+
+ /**
+ * @param plans
+ * @return
+ */
+ private List<Plan> jsonObject2PlanList(JsonObject plans) {
+ List<Plan> retList = new ArrayList<Plan>();
+ Iterator<Entry<String, JsonElement>> iterator = plans.entrySet()
+ .iterator();
+ while (iterator.hasNext()) {
+ Plan ret = new Plan();
+ Entry<String, JsonElement> 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 List<Input> inputs;
+ private List<NodeTemplate> nodeTemplates;
+ private SubstitutionMapping substitutionMappings;
+
+ public String getDescription() {
+ return description;
+ }
+ public void setDescription(String description) {
+ this.description = description;
+ }
+ public List<Input> getInputs() {
+ return inputs;
+ }
+ public void setInputs(List<Input> inputs) {
+ this.inputs = inputs;
+ }
+ public List<NodeTemplate> getNodeTemplates() {
+ return nodeTemplates;
+ }
+ public void setNodeTemplates(List<NodeTemplate> 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<Relationship> 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<String, Object> getPropertyList() {
+ return jsonObject2Properties(properties);
+ }
+
+ private Map<String, Object> jsonObject2Properties(
+ JsonObject properties) {
+ Map<String, Object> ret = new HashMap<>();
+ Iterator<Entry<String, JsonElement>> iterator = properties
+ .entrySet().iterator();
+ while (iterator.hasNext()) {
+ Entry<String, JsonElement> 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<Relationship> getRelationships() {
+ return relationships;
+ }
+
+ public void setRelationships(List<Relationship> 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<Map<String, String[]>> getRequirementList() {
+ return jsonObjects2Requirements(this.requirements);
+ }
+
+ private List<Map<String, String[]>> jsonObjects2Requirements(
+ JsonObject[] requirements) {
+ List<Map<String, String[]>> retList = new ArrayList<>();
+ for (JsonObject requirement : requirements) {
+ Iterator<Entry<String, JsonElement>> iterator = requirement
+ .entrySet().iterator();
+ while (iterator.hasNext()) {
+ Entry<String, JsonElement> next = iterator.next();
+ Map<String, String[]> ret = new HashMap<String, String[]>();
+ 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<String, String[]> getCapabilityList() {
+ return jsonObject2Capabilities(this.capabilities);
+ }
+
+ private Map<String, String[]> jsonObject2Capabilities(
+ JsonObject capabilities) {
+ Map<String, String[]> ret = new HashMap<String, String[]>();
+
+ Iterator<Entry<String, JsonElement>> iterator = capabilities
+ .entrySet().iterator();
+ while (iterator.hasNext()) {
+ Entry<String, JsonElement> 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<String, Object> getPropertyList() {
+ return jsonObject2Properties(properties);
+ }
+
+ private Map<String, Object> jsonObject2Properties(
+ JsonObject properties) {
+ Map<String, Object> ret = new HashMap<>();
+ Iterator<Entry<String, JsonElement>> iterator = properties.entrySet().iterator();
+ while (iterator.hasNext()) {
+ Entry<String, JsonElement> 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 setType(String type) {
+ this.type = type;
+ }
+
+ public RelationshipValue getValue() {
+ return value;
+ }
+
+ public void setValue(RelationshipValue value) {
+ this.value = value;
+ }
+
+ public class RelationshipValue{
+ private String derived_from;
+ private String[] valid_target_types;
+
+ public String getDerived_from() {
+ return derived_from;
+ }
+
+ 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 class NodeType {
+ private String type;
+ private NodeTypeValue value;
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ 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<NodeTypeProperty> getPropertyList() {
+ return jsonObject2Properties(properties);
+ }
+
+ private List<NodeTypeProperty> jsonObject2Properties(JsonObject properties) {
+ List<NodeTypeProperty> propertieList = new ArrayList<NodeTypeProperty>();
+ Iterator<Entry<String, JsonElement>> iterator = properties.entrySet().iterator();
+ while (iterator.hasNext()) {
+ NodeTypeProperty type = new NodeTypeProperty();
+ Entry<String, JsonElement> 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 {
+ private String name;
+ private PlanValue value;
+
+ public String getName() {
+ return name;
+ }
+ 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<PlanValue.PlanInput> 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<PlanInput> getInputList() {
+ return jsonObject2PlanInputList(inputs);
+
+ }
+
+ /**
+ * @param inputs
+ * @return
+ */
+ private List<PlanInput> jsonObject2PlanInputList(JsonObject inputs) {
+ List<PlanInput> retList = new ArrayList<PlanInput>();
+ Iterator<Entry<String, JsonElement>> iterator = inputs
+ .entrySet().iterator();
+ while (iterator.hasNext()) {
+ PlanInput ret = new PlanInput();
+ Entry<String, JsonElement> next = iterator.next();
+ ret.setName(next.getKey());
+ ret.setValue(new Gson().fromJson(next.getValue(),
+ PlanInput.PlanInputValue.class));
+ retList.add(ret);
+ }
+ return retList;
+ }
+
+ public class PlanInput {
+ private String name;
+ private PlanInputValue value;
+
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getType() {
+ return value.getType();
+ }
+
+ public String getDescription() {
+ return value.getDescription();
+ }
+
+ public String getDefault() {
+ return value.getDefault();
+ }
+
+ 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;
+ }
+ }
+ }
+ }
+ }
+}
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..9f1706a3 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/IWSO2RestService.java @@ -0,0 +1,63 @@ +/**
+ * 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/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..114e9d21 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/WSO2ServiceConsumer.java @@ -0,0 +1,123 @@ +/**
+ * 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<String, Object> 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/entity/DeletePackageResponse.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/entity/DeletePackageResponse.java new file mode 100644 index 00000000..b905ee61 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/entity/DeletePackageResponse.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.plan.wso2.entity; + +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 int status; + private String message; + private String exception; + + 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 new file mode 100644 index 00000000..3e171445 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/entity/DeployPackageResponse.java @@ -0,0 +1,44 @@ +/** + * 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.entity; + +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 int status; + private String message; + private String packageName; + private String processId; + private String exception; + + 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 new file mode 100644 index 00000000..da9aefb5 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/entity/StartProcessRequest.java @@ -0,0 +1,37 @@ +/** + * 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.entity; + +import java.util.Map; + +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 StartProcessRequest { + private String processId; + private Map<String, Object> 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 new file mode 100644 index 00000000..73c9fad2 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/plan/wso2/entity/StartProcessResponse.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.plan.wso2.entity; + +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 int status; + private String message; + private String response; + private String exception; + + public boolean isSuccess() { + return this.status == STATUS_SUCCESS; + } +} 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 new file mode 100644 index 00000000..039d64b4 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/model/wrapper/ServiceTemplateWrapper.java @@ -0,0 +1,351 @@ +/**
+ * 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.wrapper;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+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;
+import org.openo.commontosca.catalog.db.entity.ServiceTemplateData;
+import org.openo.commontosca.catalog.db.entity.ServiceTemplateMappingData;
+import org.openo.commontosca.catalog.db.exception.CatalogResourceException;
+import org.openo.commontosca.catalog.db.resource.TemplateManager;
+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.QueryRawDataCondition;
+import org.openo.commontosca.catalog.model.entity.ServiceTemplate;
+import org.openo.commontosca.catalog.model.entity.ServiceTemplateRawData;
+import org.openo.commontosca.catalog.model.entity.SubstitutionMapping;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ *
+ * @author 10090474
+ *
+ */
+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;
+ }
+
+ /**
+ *
+ * @param serviceTemplateId
+ * @return
+ * @throws CatalogResourceException
+ */
+ public ServiceTemplate getServiceTemplateById(String serviceTemplateId)
+ throws CatalogResourceException {
+ logger.info("getServiceTemplateById. serviceTemplateId = "
+ + serviceTemplateId);
+
+ List<ServiceTemplateData> 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));
+ }
+
+
+ /**
+ *
+ * @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<ServiceTemplateData> stdList = TemplateManager.getInstance()
+ .queryServiceTemplateByCsarPackageInfo(pd);
+
+ return TemplateDataHelper.convert2ServiceTemplates(stdList);
+ }
+
+
+ /**
+ * @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;
+ }
+
+ /**
+ * @param nodeTypeId
+ * @return
+ * @throws CatalogResourceException
+ */
+ private SubstitutionMapping getSubstitutionMappingsByNodeTypeId(
+ String nodeTypeId) throws CatalogResourceException {
+ List<ServiceTemplateMappingData> stmDataList = TemplateManager
+ .getInstance().queryServiceTemplateMapping(nodeTypeId, null);
+ if (stmDataList == null || stmDataList.isEmpty()) {
+ return null;
+ }
+
+ return TemplateDataHelper.convert2SubstitutionMapping(stmDataList
+ .get(0));
+ }
+
+
+ /**
+ * @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<ServiceTemplateData> 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());
+ }
+
+ /**
+ *
+ * @param serviceTemplateId
+ * @return
+ * @throws CatalogResourceException
+ */
+ public InputParameter[] getServiceTemplateParameters(
+ String serviceTemplateId) throws CatalogResourceException {
+ ServiceTemplate st = getServiceTemplateById(serviceTemplateId);
+ return st.getInputs();
+ }
+
+ /**
+ *
+ * @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();
+ }
+
+ /**
+ * @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.");
+ }
+
+
+ /**
+ * @param serviceTemplateId
+ * @param nodeTemplateId
+ * @return
+ * @throws CatalogResourceException
+ */
+ public NodeTemplate getNodeTemplateById(String serviceTemplateId,
+ String nodeTemplateId) throws CatalogResourceException {
+ List<NodeTemplateData> ntdList = TemplateManager.getInstance()
+ .queryNodeTemplateById(serviceTemplateId, nodeTemplateId);
+
+ if (ntdList == null || ntdList.isEmpty()) {
+ throw new CatalogResourceException("Can't find this node template.");
+ }
+
+ return TemplateDataHelper.convert2NodeTemplate(ntdList.get(0));
+ }
+
+ /**
+ * @param serviceTemplateId
+ * @param types
+ * @return
+ * @throws CatalogResourceException
+ */
+ public NodeTemplate[] getNodeTemplates(String serviceTemplateId,
+ String[] types) throws CatalogResourceException {
+ List<NodeTemplateData> 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<NodeTemplate> ntList = new ArrayList<>();
+ for (String type : types) {
+ if (!ToolUtil.isTrimedEmptyString(type)) {
+ List<NodeTemplateData> typedNtdList = filterNodeTemplateDataListByType(
+ ntdList, type);
+ ntList.addAll(Arrays
+.asList(TemplateDataHelper
+ .convert2NodeTemplates(typedNtdList)));
+ }
+ }
+ return ntList.toArray(new NodeTemplate[0]);
+ }
+
+ /**
+ * @param ntdList
+ * @param type
+ * @return
+ */
+ private List<NodeTemplateData> filterNodeTemplateDataListByType(
+ List<NodeTemplateData> ntdList, String type) {
+ List<NodeTemplateData> retList = new ArrayList<>();
+ for (NodeTemplateData ntd : ntdList) {
+ if (type.equals(ntd.getType())) {
+ retList.add(ntd);
+ }
+ }
+ return retList;
+ }
+
+
+ /**
+ * @param serviceTemlateId
+ * @return
+ * @throws CatalogResourceException
+ */
+ public NfvTemplate getNfvTemplate(String serviceTemlateId)
+ throws CatalogResourceException {
+ NodeTemplate[] nts = getNodeTemplates(serviceTemlateId, null);
+
+ List<NodeTemplate> vduNodes = new ArrayList<>();
+ List<NodeTemplate> networkNodes = new ArrayList<>();
+ List<NodeTemplate> vnfcNodes = new ArrayList<>();
+ List<NodeTemplate> 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);
+ }
+
+ /**
+ * @param type
+ * @return
+ */
+ private boolean isVnfNode(String type) {
+ return type.toUpperCase().indexOf(".VNF") > 0;
+ }
+
+ /**
+ * @param type
+ * @return
+ */
+ private boolean isVnfcNode(String type) {
+ return type.toUpperCase().indexOf(".VNFC") > 0;
+ }
+
+ /**
+ * @param type
+ * @return
+ */
+ private boolean isNetworkNode(String type) {
+ return type.toUpperCase().indexOf(".VL") > 0
+ || type.toUpperCase().indexOf(".VIRTUALLINK") > 0;
+ }
+
+ /**
+ * @param type
+ * @return
+ */
+ 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 new file mode 100644 index 00000000..17ec7cd6 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/resources/CatalogBadRequestException.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.resources; + +import org.openo.commontosca.catalog.db.exception.ErrorCodeException; + +/** + * + */ +public class CatalogBadRequestException extends ErrorCodeException { + private static final long serialVersionUID = 5699508780537383310L; + + + public CatalogBadRequestException(int errcode) { + super(errcode, ""); + } + + + public CatalogBadRequestException(int errcode, Throwable cause) { + super(cause, errcode); + } + + + public CatalogBadRequestException(int errcode, String message, Throwable cause) { + super(cause, errcode, message); + } + + + public CatalogBadRequestException() { + super(9999999, null); + } + + + public CatalogBadRequestException(String message) { + super(9999999, message); + } + + + public CatalogBadRequestException(Throwable cause) { + super(cause, 9999999); + } + + + 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 category, int code, + String debugMessage, String[] arguments) { + super(source, category, code, debugMessage, arguments); + } + + 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 new file mode 100644 index 00000000..0fd61f77 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/resources/PackageResource.java @@ -0,0 +1,268 @@ +/** + * 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.resources; + +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 javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +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. + * + * @author 10189609 + * + */ +@Path("/") +@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); + // } +} 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 new file mode 100644 index 00000000..62335bca --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/resources/RestUtils.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.resources;
+
+import javax.ws.rs.BadRequestException;
+import javax.ws.rs.InternalServerErrorException;
+import javax.ws.rs.core.Response;
+
+import org.openo.commontosca.catalog.common.CommonErrorResponse;
+import org.openo.commontosca.catalog.db.exception.CatalogResourceException;
+
+
+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);
+ }
+
+ /**
+ * @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);
+ }
+}
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 new file mode 100644 index 00000000..ea1c21e4 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/resources/TemplateResource.java @@ -0,0 +1,435 @@ +/** + * 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.resources; + +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.model.entity.InputParameter; +import org.openo.commontosca.catalog.model.entity.NodeTemplate; +import org.openo.commontosca.catalog.model.entity.QueryRawDataCondition; +import org.openo.commontosca.catalog.model.entity.ServiceTemplate; +import org.openo.commontosca.catalog.model.entity.ServiceTemplateRawData; +import org.openo.commontosca.catalog.model.parser.ToscaYamlModelParser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.codahale.metrics.annotation.Timed; + +/** + * @author 10090474 + * + */ +@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); + } + + } + + /** + * @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); + } + } + + /** + * @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); + } + } + + + /** + * @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); + } + + } + + /** + * @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); + } + + } + + /** + * @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); + } + + } + + /** + * @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); + } + + } + + + private String[] getSplitedTypes(String types) { + if (ToolUtil.isTrimedEmptyString(types)) { + return new String[0]; + } + + return types.split(","); + } + + /** + * @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); + } + + } + + // /** + // * @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); + } + } + + +} 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 new file mode 100644 index 00000000..8ded7bba --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/wrapper/PackageWrapper.java @@ -0,0 +1,462 @@ +/**
+ * 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.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;
+
+import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
+import org.openo.commontosca.catalog.common.CommonConstant;
+import org.openo.commontosca.catalog.common.HttpServerPathConfig;
+import org.openo.commontosca.catalog.common.RestUtil;
+import org.openo.commontosca.catalog.common.ToolUtil;
+import org.openo.commontosca.catalog.common.ZipCompressor;
+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.resource.TemplateManager;
+import org.openo.commontosca.catalog.entity.EnumType;
+import org.openo.commontosca.catalog.entity.request.PackageBasicInfo;
+import org.openo.commontosca.catalog.entity.request.UploadPackageFromFtpRequest;
+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.filemanage.FileManagerFactory;
+import org.openo.commontosca.catalog.filemanage.entity.FileLink;
+import org.openo.commontosca.catalog.model.parser.EnumPackageFormat;
+import org.openo.commontosca.catalog.model.parser.ModelParserFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * @author 10189609
+ *
+ */
+public class PackageWrapper {
+ 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;
+ }
+
+ public Response queryPackageById(String csarId) {
+ ArrayList<PackageData> dbResult = new ArrayList<PackageData>();
+ ArrayList<PackageMeta> result = new ArrayList<PackageMeta>();
+ 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();
+ }
+
+ 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();
+
+ 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));
+ }
+ }
+ }
+
+ 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());
+ }
+ }
+
+ // 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<PackageData> result = new ArrayList<PackageData>();
+ // 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 delCsarThread(String csarid, boolean isInstanceTemplate) {
+ this.csarid = csarid;
+ this.isInstanceTemplate = isInstanceTemplate;
+ }
+
+ @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");
+ }
+ }
+
+ 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");
+ }
+
+ // private void publishDelFinishCometdMessage(String csarid, String csarDelStatus) {
+ // if (isInstanceTemplate) {
+ // LOG.info("delete instance Template finish. csarid:{}", csarid);
+ // return;
+ // }
+ // try {
+ // Map<String, Object> cometdMessage = new HashMap<String, Object>();
+ // 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);
+ // }
+ // }
+ }
+
+ 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<PackageData> 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());
+ }
+ }
+
+ public Response downloadCsarPackagesById(String csarId) {
+ ArrayList<PackageData> 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();
+ }
+
+ 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());
+ }
+ }
+
+ public Response queryPackageListByCond(String name, String provider, String version,
+ String deletionPending, String type) {
+ ArrayList<PackageData> dbresult = new ArrayList<PackageData>();
+ ArrayList<PackageMeta> result = new ArrayList<PackageMeta>();
+ 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());
+ }
+ }
+
+ 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);
+ }
+
+ return Response.serverError().build();
+ }
+
+ public CsarFileUriResponse getCsarFileDownloadUri(String csarId, String relativePath)
+ throws CatalogResourceException {
+ CsarFileUriResponse result = new CsarFileUriResponse();
+ String downloadUrl = null;
+ String downloadUri = null;
+ String localPath = null;
+ ArrayList<PackageData> 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;
+ }
+
+ /**
+ * @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();
+
+ 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));
+ }
+ }
+ }
+
+ public Response getCsarPlansUri(String csarId) {
+ ArrayList<FileLink> fileLinks = new ArrayList<FileLink>();
+ LOG.info("start query plans of package.csarId:" + csarId);
+ ArrayList<PackageData> packageList = new ArrayList<PackageData>();
+ 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());
+ }
+ // 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 new file mode 100644 index 00000000..7395ed16 --- /dev/null +++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/wrapper/PackageWrapperUtil.java @@ -0,0 +1,406 @@ +/**
+ * 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.wrapper;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+
+import javax.ws.rs.NotFoundException;
+
+import org.openo.commontosca.catalog.cometd.CometdException;
+import org.openo.commontosca.catalog.common.CommonConstant;
+import org.openo.commontosca.catalog.common.FileUtil;
+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.entity.EnumProcessState;
+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.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.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;
+
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+
+/**
+ * @author 00164331
+ *
+ */
+public class PackageWrapperUtil {
+ private static final Logger LOG = LoggerFactory.getLogger(PackageWrapperUtil.class);
+
+
+ public static List<CSARPackage> formJson2Packages(String packageJson) {
+ List<CSARPackage> packageList =
+ new Gson().fromJson(packageJson, new TypeToken<List<CSARPackage>>() {}.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 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 ArrayList<PackageData> getPackageInfoById(String csarId) {
+ ArrayList<PackageData> result = new ArrayList<PackageData>();
+ try {
+ result = PackageManager.getInstance().queryPackageByCsarId(csarId);
+ } catch (CatalogResourceException e) {
+ LOG.error("query package by csarId from db error ! " + e.getMessage());
+ }
+ return result;
+ }
+
+ 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("false");
+ packageMeta.setProcessState(EnumProcessState.normal);
+ return packageMeta;
+ }
+
+ public static String getPackagePath(String csarId) {
+ ArrayList<PackageData> packageList = new ArrayList<PackageData>();
+ 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<String> instanceConvertToHashSet(ArrayList<InstanceEntity> instancelist) {
+ HashSet<String> result = new HashSet<String>();
+ 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<ServiceTemplate> templateList = queryAvailableTemplatesByCsar(csarId);
+ // 调生命周期的接口查询所有实例,查询实例中是否包含指定csarId对应的服务模析ID
+ HashSet<String> 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;
+ }
+
+ public static ArrayList<ServiceTemplate> queryAvailableTemplatesByCsar(String csarId) {
+ return null;
+ // ArrayList<ServiceTemplate> resultlist = new ArrayList<ServiceTemplate>();
+ // String filter = LDAPUtil.getObjectClassFilter(LDAPConstant.OBJECTCLASS_CSAR);
+ // String result =
+ // LDAPDataFactory.getInstance().queryData(EnumLDAPData.SERVICETEMPLATE, null, false,
+ // filter);
+ // Type type = new TypeToken<ArrayList<ServiceTemplate>>() {}.getType();
+ // ArrayList<ServiceTemplate> 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<String, Object> cometdMessage = new HashMap<String, Object>();
+ // 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 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 getFtpDir(String ftpUrl) {
+ // // TODO Auto-generated method stub
+ // return null;
+ // }
+
+ /**
+ * @param ftpUrl
+ * @return
+ */
+ public static String getPackageName(String ftpUrl) {
+ int index = ftpUrl.lastIndexOf("/");
+ String packageName = ftpUrl.substring(index);
+ return packageName;
+ }
+
+ 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 dbResult
+ * @return
+ */
+ public static ArrayList<PackageMeta> packageDataList2PackageMetaList(
+ ArrayList<PackageData> dbResult) {
+ ArrayList<PackageMeta> metas = new ArrayList<PackageMeta>();
+ 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;
+ }
+
+ 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;
+ }
+
+ 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<String> 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 !");
+ }
+ 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;
+ 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) {
+ }
+ }
+ }
+ return basicInfo;
+ }
+}
|