From c0604184b2aa8cff924ca783ec6b36f1f5988775 Mon Sep 17 00:00:00 2001 From: Zhaoxing Date: Tue, 8 Aug 2017 14:02:53 +0800 Subject: init code Change-Id: Icd0948118397b256da70dfbcbbec5520dc5eafd4 Signed-off-by: Zhaoxing --- .../org/openo/carbon/bpel/Wso2BpelApplication.java | 106 ++++ .../openo/carbon/bpel/Wso2BpelConfiguration.java | 200 +++++++ .../java/org/openo/carbon/bpel/common/Config.java | 30 + .../openo/carbon/bpel/common/ServiceRegistrer.java | 70 +++ .../bpel/externalservice/entity/ServiceNode.java | 33 ++ .../entity/ServiceRegisterEntity.java | 57 ++ .../msb/MicroserviceBusConsumer.java | 48 ++ .../externalservice/msb/MicroserviceBusRest.java | 39 ++ .../openo/carbon/bpel/resources/BpsPackage.java | 632 +++++++++++++++++++++ .../openo/carbon/bpel/resources/BpsProcess.java | 544 ++++++++++++++++++ .../carbon/bpel/resources/BpsServiceException.java | 30 + .../openo/carbon/bpel/resources/RestAppConfig.java | 37 ++ .../openo/carbon/bpel/util/ClientWsdlLoader.java | 82 +++ .../java/org/openo/carbon/bpel/util/JsonUtil.java | 61 ++ .../openo/carbon/bpel/util/LRULinkedHashMap.java | 106 ++++ .../java/org/openo/carbon/bpel/util/SoapUtil.java | 156 +++++ .../org/openo/carbon/bpel/util/Xml2JsonUtil.java | 141 +++++ 17 files changed, 2372 insertions(+) create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/Wso2BpelApplication.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/Wso2BpelConfiguration.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/common/Config.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/common/ServiceRegistrer.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/entity/ServiceNode.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/entity/ServiceRegisterEntity.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/msb/MicroserviceBusConsumer.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/msb/MicroserviceBusRest.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsPackage.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsProcess.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsServiceException.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/RestAppConfig.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/ClientWsdlLoader.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/JsonUtil.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/LRULinkedHashMap.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/SoapUtil.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/Xml2JsonUtil.java (limited to 'wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon') diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/Wso2BpelApplication.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/Wso2BpelApplication.java new file mode 100644 index 0000000..5cec239 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/Wso2BpelApplication.java @@ -0,0 +1,106 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * 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.carbon.bpel; + +import io.dropwizard.Application; +import io.dropwizard.assets.AssetsBundle; +import io.dropwizard.configuration.EnvironmentVariableSubstitutor; +import io.dropwizard.configuration.SubstitutingSourceProvider; +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 org.glassfish.jersey.media.multipart.MultiPartFeature; +import org.openo.carbon.bpel.common.Config; +import org.openo.carbon.bpel.common.ServiceRegistrer; +import org.openo.carbon.bpel.resources.BpsPackage; +import org.openo.carbon.bpel.resources.BpsProcess; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.annotation.JsonInclude; + + + +public class Wso2BpelApplication extends Application { + private static final Logger LOGGER = LoggerFactory.getLogger(Wso2BpelApplication.class); + private static final String API_RESOURCE = "org.openo.carbon.bpel.resources"; + + public static void main(String[] args) throws Exception { + new Wso2BpelApplication().run(args); + } + + + @Override + public String getName() { + return "hello-wso2bpel"; + } + + @Override + public void initialize(Bootstrap bootstrap) { + bootstrap.setConfigurationSourceProvider(new SubstitutingSourceProvider( + bootstrap.getConfigurationSourceProvider(), new EnvironmentVariableSubstitutor(false))); + // binding jar static resource + bootstrap.addBundle(new AssetsBundle("/api-doc", "/api-doc", "index.html", "api-doc")); + } + + private void initService() { + Thread registerWso2bpelService = new Thread(new ServiceRegistrer()); + registerWso2bpelService.setName("register wso2bpel service to Microservice Bus"); + registerWso2bpelService.start(); + } + + + + @Override + public void run(Wso2BpelConfiguration configuration, Environment environment) { + environment.jersey().register(MultiPartFeature.class); + environment.jersey().register(new BpsPackage()); + environment.jersey().register(new BpsProcess()); + // init Swagger conf + initSwaggerConfig(environment, configuration); + Config.setConfigration(configuration); + initService(); + } + + private void initSwaggerConfig(Environment environment, Wso2BpelConfiguration configuration) { + // register swagger scan class + environment.jersey().register(new ApiListingResource()); + environment.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL); + + BeanConfig config = new BeanConfig(); + config.setTitle(configuration.getApiDescription()); + config.setVersion("1.0"); + config.setResourcePackage(API_RESOURCE); + + // read rootPath config from yml + SimpleServerFactory simpleServerFactory = + (SimpleServerFactory) configuration.getServerFactory(); + String basePath = simpleServerFactory.getApplicationContextPath(); + String rootPath = simpleServerFactory.getJerseyRootPath(); + + // set basepath for rest api + rootPath = rootPath.substring(0, rootPath.indexOf("/*")); + basePath = basePath.equals("/") ? rootPath + : (new StringBuilder()).append(basePath).append(rootPath).toString(); + + LOGGER.info("getApplicationContextPath:" + basePath); + config.setBasePath(basePath); + config.setScan(true); + } +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/Wso2BpelConfiguration.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/Wso2BpelConfiguration.java new file mode 100644 index 0000000..953a919 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/Wso2BpelConfiguration.java @@ -0,0 +1,200 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * 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.carbon.bpel; + +import io.dropwizard.Configuration; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.dropwizard.db.DataSourceFactory; +import org.hibernate.validator.constraints.NotEmpty; + +import javax.validation.Valid; +import javax.validation.constraints.NotNull; + +public class Wso2BpelConfiguration extends Configuration { + @NotEmpty + private String template; + @NotEmpty + private String apiDescription = "Wso2bps REST API"; + @NotNull + private DataSourceFactory database = new DataSourceFactory(); + + @NotEmpty + private String msbServerAddr; + + @NotEmpty + private String wso2Host; + + @NotEmpty + private String wso2HostPort; + + @NotEmpty + private String wso2AuthUserName; + + @NotEmpty + private String wso2AuthPassword; + + @NotEmpty + private String wso2Path; + + @NotEmpty + private String wso2UploadFilePath; + + @NotEmpty + private String wso2SslJksFile; + + @NotEmpty + private String wso2SslJksPassword; + + @Valid + private String serviceIp; + + @JsonProperty + public String getTemplate() { + return template; + } + + @JsonProperty + public String getApiDescription() { + return apiDescription; + } + + @JsonProperty("database") + public DataSourceFactory getDataSourceFactory() { + return database; + } + + @JsonProperty + public DataSourceFactory getDatabase() { + return database; + } + + @JsonProperty + public void setDatabase(DataSourceFactory database) { + this.database = database; + } + + @JsonProperty + public String getMsbServerAddr() { + return msbServerAddr; + } + + @JsonProperty + public void setMsbServerAddr(String msbServerAddr) { + this.msbServerAddr = msbServerAddr; + } + + @JsonProperty + public String getWso2Host() { + return wso2Host; + } + + @JsonProperty + public void setWso2Host(String wso2Host) { + this.wso2Host = wso2Host; + } + + @JsonProperty + public String getWso2HostPort() { + return wso2HostPort; + } + + @JsonProperty + public void setWso2HostPort(String wso2HostPort) { + this.wso2HostPort = wso2HostPort; + } + + @JsonProperty + public String getWso2AuthUserName() { + return wso2AuthUserName; + } + + @JsonProperty + public void setWso2AuthUserName(String wso2AuthUserName) { + this.wso2AuthUserName = wso2AuthUserName; + } + + @JsonProperty + public String getWso2AuthPassword() { + return wso2AuthPassword; + } + + @JsonProperty + public void setWso2AuthPassword(String wso2AuthPassword) { + this.wso2AuthPassword = wso2AuthPassword; + } + + @JsonProperty + public String getWso2Path() { + return wso2Path; + } + + @JsonProperty + public void setWso2Path(String wso2Path) { + if (wso2Path.startsWith("/") == false) { + this.wso2Path = System.getProperty("WSO2_EXT_HOME") + "/" + wso2Path; + } else { + this.wso2Path = wso2Path; + } + } + + @JsonProperty + public String getWso2UploadFilePath() { + return wso2UploadFilePath; + } + + @JsonProperty + public void setWso2UploadFilePath(String wso2UploadFilePath) { + if (wso2UploadFilePath.startsWith("/") == false) { + this.wso2UploadFilePath = System.getProperty("WSO2_EXT_HOME") + "/" + wso2UploadFilePath; + } else { + this.wso2UploadFilePath = wso2UploadFilePath; + } + } + + @JsonProperty + public String getWso2SslJksFile() { + return wso2SslJksFile; + } + + @JsonProperty + public void setWso2SslJksFile(String wso2SslJksFile) { + if (wso2SslJksFile.startsWith("/") == false) { + this.wso2SslJksFile = System.getProperty("WSO2_EXT_HOME") + "/" + wso2SslJksFile; + } else { + this.wso2SslJksFile = wso2SslJksFile; + } + } + + @JsonProperty + public String getWso2SslJksPassword() { + return wso2SslJksPassword; + } + + @JsonProperty + public void setWso2SslJksPassword(String wso2SslJksPassword) { + this.wso2SslJksPassword = wso2SslJksPassword; + } + + @JsonProperty + public String getServiceIp() { + return serviceIp; + } + + @JsonProperty + public void setServiceIp(String serviceIp) { + this.serviceIp = serviceIp; + } +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/common/Config.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/common/Config.java new file mode 100644 index 0000000..f3e83cf --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/common/Config.java @@ -0,0 +1,30 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * 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.carbon.bpel.common; + +import org.openo.carbon.bpel.Wso2BpelConfiguration; + +public class Config { + private static Wso2BpelConfiguration configration; + + public static Wso2BpelConfiguration getConfigration() { + return configration; + } + + public static void setConfigration(Wso2BpelConfiguration config) { + configration = config; + } +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/common/ServiceRegistrer.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/common/ServiceRegistrer.java new file mode 100644 index 0000000..03d88aa --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/common/ServiceRegistrer.java @@ -0,0 +1,70 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * 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.carbon.bpel.common; + +import org.openo.carbon.bpel.externalservice.entity.ServiceRegisterEntity; +import org.openo.carbon.bpel.externalservice.msb.MicroserviceBusConsumer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ServiceRegistrer implements Runnable { + private static final Logger LOG = LoggerFactory.getLogger(ServiceRegistrer.class); + private final ServiceRegisterEntity wso2bpelEntity = new ServiceRegisterEntity(); + + public ServiceRegistrer() { + initServiceEntity(); + } + + @Override + public void run() { + LOG.info("start wso2bpelEntity microservice register"); + boolean flag = false; + int retry = 0; + while (!flag && retry < 1000) { + LOG.info("wso2bpel microservice register.retry:" + retry); + retry++; + flag = MicroserviceBusConsumer.registerService(wso2bpelEntity); + if (flag == false) { + LOG.warn("microservice register failed, sleep 30S and try again."); + threadSleep(30000); + } else { + LOG.info("microservice register success!"); + break; + } + } + LOG.info("wso2bpel microservice register end."); + } + + private void threadSleep(int second) { + LOG.info("start sleep ...."); + try { + Thread.sleep(second); + } catch (InterruptedException error) { + LOG.error("thread sleep error.errorMsg:" + error.getMessage()); + } + LOG.info("sleep end ."); + } + + private void initServiceEntity() { + wso2bpelEntity.setServiceName("wso2bpel"); + wso2bpelEntity.setProtocol("REST"); + wso2bpelEntity.setVersion("v1"); + wso2bpelEntity.setUrl("/openoapi/wso2bpel/v1"); + wso2bpelEntity.setSingleNode(Config.getConfigration().getServiceIp(), "8101", 0); + wso2bpelEntity.setVisualRange("1"); + } + +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/entity/ServiceNode.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/entity/ServiceNode.java new file mode 100644 index 0000000..5f0d3bb --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/entity/ServiceNode.java @@ -0,0 +1,33 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * 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.carbon.bpel.externalservice.entity; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@JsonIgnoreProperties(ignoreUnknown = true) +public class ServiceNode { + private String ip; + private String port; + private int ttl; +} + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/entity/ServiceRegisterEntity.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/entity/ServiceRegisterEntity.java new file mode 100644 index 0000000..3dd336d --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/entity/ServiceRegisterEntity.java @@ -0,0 +1,57 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * 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.carbon.bpel.externalservice.entity; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.ArrayList; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@JsonIgnoreProperties(ignoreUnknown = true) +public class ServiceRegisterEntity { + private String serviceName; + private String version; + private String url; + private String protocol; + private String visualRange; + private ArrayList nodes = new ArrayList(); + + /** + * set service entity. + * + * @param ip node ip. can be null + * @param port service port + * @param ttl service survival time + */ + public void setSingleNode(String ip, String port, int ttl) { + ServiceNode node = new ServiceNode(); + if (ip != null && ip.length() > 0) { + node.setIp(ip); + } else { + node.setIp(null); + } + node.setPort(port); + node.setTtl(ttl); + nodes.add(node); + } + +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/msb/MicroserviceBusConsumer.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/msb/MicroserviceBusConsumer.java new file mode 100644 index 0000000..b5086e8 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/msb/MicroserviceBusConsumer.java @@ -0,0 +1,48 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * 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.carbon.bpel.externalservice.msb; + +import com.eclipsesource.jaxrs.consumer.ConsumerFactory; + +import org.glassfish.jersey.client.ClientConfig; +import org.openo.carbon.bpel.common.Config; +import org.openo.carbon.bpel.externalservice.entity.ServiceRegisterEntity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + + + +public class MicroserviceBusConsumer { + private static final Logger LOG = LoggerFactory.getLogger(MicroserviceBusConsumer.class); + + /** + * @param entity service entity + * @return register service to msb success return true, else return false. + */ + public static boolean registerService(ServiceRegisterEntity entity) { + ClientConfig config = new ClientConfig(); + try { + MicroserviceBusRest resourceserviceproxy = ConsumerFactory.createConsumer( + Config.getConfigration().getMsbServerAddr(), config, MicroserviceBusRest.class); + resourceserviceproxy.registerServce("false", entity); + } catch (Exception error) { + LOG.error("microservice register failed!" + error.getMessage()); + return false; + } + return true; + } +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/msb/MicroserviceBusRest.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/msb/MicroserviceBusRest.java new file mode 100644 index 0000000..83a6941 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/msb/MicroserviceBusRest.java @@ -0,0 +1,39 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * 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.carbon.bpel.externalservice.msb; + +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; + +import org.openo.carbon.bpel.externalservice.entity.ServiceRegisterEntity; + + + + +@Path("/openoapi/microservices/v1/services") +// @Path("/api/microservices/v1/services") +public interface MicroserviceBusRest { + @Path("") + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public ServiceRegisterEntity registerServce(@QueryParam("createOrUpdate") String createOrUpdate, + ServiceRegisterEntity entity)throws Exception; +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsPackage.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsPackage.java new file mode 100644 index 0000000..e11c1eb --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsPackage.java @@ -0,0 +1,632 @@ +/** + * Copyright 2016-2017 ZTE Corporation. + * + * 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.carbon.bpel.resources; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicLong; + +import javax.activation.DataHandler; +import javax.activation.DataSource; +import javax.activation.FileDataSource; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.QueryParam; +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.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.Context; +import javax.ws.rs.core.MediaType; +import javax.xml.namespace.QName; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMFactory; +import org.apache.axiom.om.OMNamespace; +import org.apache.axis2.AxisFault; +import org.apache.axis2.addressing.EndpointReference; +import org.apache.axis2.client.Options; +import org.apache.axis2.rpc.client.RPCServiceClient; +import org.apache.axis2.transport.http.HTTPConstants; +import org.apache.axis2.transport.http.HttpTransportProperties; +import org.apache.axis2.transport.http.HttpTransportProperties.Authenticator; +import org.apache.commons.io.FileUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.FormDataParam; +import org.glassfish.jersey.media.multipart.MultiPartFeature; +import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; +import org.wso2.carbon.bpel.stub.upload.types.UploadedFileItem; +import org.openo.carbon.bpel.common.Config; +import org.openo.carbon.bpel.util.JsonUtil; +import org.openo.carbon.bpel.util.Xml2JsonUtil; + +import com.codahale.metrics.annotation.Timed; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("/") +@Api(tags = {"wso2 bpel api"}) +public class BpsPackage { + + private static final Log log = LogFactory.getLog(BpsPackage.class); + + public static final int STATUS_SUCCESS = 1; + public static final int STATUS_FAIL = 0; + /** + * 无错误 + */ + public static final int ERROR_CODE_NOERROR = 0; + /** + * 不支持的文件类型 + */ + public static final int ERROR_CODE_PACKAGE_UNSUPPORED_FILE = 10001; + /** + * 同名的包正在操作中 + */ + public static final int ERROR_CODE_PACKAGE_STATUS_BUSY = 10002; + /** + * 包名重复 + */ + public static final int ERROR_CODE_PACKAGE_DUPLICATED_NAME = 10003; + /** + * 未获取到包部署的信息 + */ + public static final int ERROR_CODE_PACKAGE_DEPLOY_INFORMATION_IS_LOST = 10004; + /** + * 卸载包失败 + */ + public static final int ERROR_CODE_PACKAGE_UNDEPLOY_FAILED = 10005; + /** + * 包不存在 + */ + public static final int ERROR_CODE_PACKAGE_NOTEXISTS = 10006; + /** + * 服务运行时异常 + */ + public static final int ERROR_CODE_RUNTIME_EXCEPTION = 20001; + /** + * Axis运行时异常 + */ + public static final int ERROR_CODE_RUNTIME_EXCEPTION_AXIS = 20002; + /** + * IO运行时异常 + */ + public static final int ERROR_CODE_RUNTIME_EXCEPTION_IO = 20003; + + public static Set packageNameSet = new HashSet(); + + private Map configMap = null; + + @SuppressWarnings("unused") + private final AtomicLong counter; + + public BpsPackage() { + this.counter = new AtomicLong(); + } + + private synchronized String getConfig(String key) { + if (configMap == null) { + configMap = new HashMap(); + String uploadFilePath = Config.getConfigration().getWso2UploadFilePath(); + String jksFile = Config.getConfigration().getWso2SslJksFile(); + String trustStorePassword = Config.getConfigration().getWso2SslJksPassword(); + String httpUsername = Config.getConfigration().getWso2AuthUserName(); + String httpPassword = Config.getConfigration().getWso2AuthPassword(); + String host = Config.getConfigration().getWso2Host(); + String port = Config.getConfigration().getWso2HostPort(); + configMap.put("uploadFilePath", uploadFilePath); + configMap.put("jksFile", jksFile); + configMap.put("trustStorePassword", trustStorePassword); + configMap.put("httpUsername", httpUsername); + configMap.put("httpPassword", httpPassword); + configMap.put("host", host); + configMap.put("port", port); + } + if (configMap.containsKey(key)) { + return configMap.get(key); + } else { + return ""; + } + } + + public static boolean lockPackageName(String packageName) { + boolean succeed = false; + synchronized (packageNameSet) { + if (!packageNameSet.contains(packageName)) { + packageNameSet.add(packageName); + succeed = true; + } + } + return succeed; + } + + public static boolean unlockPackageName(String packageName) { + boolean succeed = false; + synchronized (packageNameSet) { + if (packageNameSet.contains(packageName)) { + packageNameSet.remove(packageName); + succeed = true; + } + } + return succeed; + } + + @POST + @Path(value = "package") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(value = MediaType.APPLICATION_JSON) + @ApiOperation(value = "package process", response = Map.class) + @Timed + public Map uploadFile(@FormDataParam("filename") String filename, + @FormDataParam("file") InputStream fileInputStream, + @FormDataParam("file") FormDataContentDisposition fileDetail, + @Context HttpServletRequest request, @Context HttpServletResponse response) + throws IOException { + Map map = new LinkedHashMap(); + String errorMessage = "unkown"; + int errorCode = ERROR_CODE_NOERROR; + + String fileName = fileDetail.getFileName(); + String fullName = getConfig("uploadFilePath") + "/" + fileName; + File file = new File(fullName); + String packageName = null; + try { + if (fileName.endsWith(".zip")) { + packageName = fileName.substring(0, fileName.length() - 4); + } else { + errorCode = ERROR_CODE_PACKAGE_UNSUPPORED_FILE; + throw new Exception("Only support *.zip file."); + } + if (!lockPackageName(packageName)) { + errorCode = ERROR_CODE_PACKAGE_STATUS_BUSY; + throw new Exception("Package " + packageName + " is operating."); + } + FileUtils.copyInputStreamToFile(fileInputStream, file); + System.setProperty("javax.net.ssl.trustStore", "*.keystore"); + System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); + System.setProperty("javax.net.ssl.trustStore", getConfig("jksFile")); + System.setProperty("javax.net.ssl.trustStorePassword", getConfig("trustStorePassword")); + + HttpTransportProperties.Authenticator authenticator = + new HttpTransportProperties.Authenticator(); + List auth = new ArrayList(); + auth.add(Authenticator.BASIC); + authenticator.setAuthSchemes(auth); + authenticator.setUsername(getConfig("httpUsername")); + authenticator.setPassword(getConfig("httpPassword")); + authenticator.setPreemptiveAuthentication(true); + + map.putAll(bpsDeployPackage(fileName, fullName, packageName, authenticator)); + map.put("status", STATUS_SUCCESS); + map.put("message", "success"); + return map; + } catch (AxisFault e) { + errorMessage = e.getLocalizedMessage(); + errorCode = ERROR_CODE_RUNTIME_EXCEPTION_AXIS; + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (IOException e) { + errorMessage = e.getLocalizedMessage(); + errorCode = ERROR_CODE_RUNTIME_EXCEPTION_IO; + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (Throwable e) { + errorMessage = e.getLocalizedMessage(); + if (e instanceof BpsServiceException) { + errorCode = ((BpsServiceException) e).getErrorCode(); + } else { + errorCode = ERROR_CODE_RUNTIME_EXCEPTION; + } + log.error(e.getMessage(), e); + e.printStackTrace(); + } finally { + if (packageName != null) { + unlockPackageName(packageName); + } + } + map.put("errorCode", errorCode); + map.put("status", STATUS_FAIL); + map.put("message", errorMessage); + return map; + } + + @SuppressWarnings("rawtypes") + private Map bpsDeployPackage(String fileName, String fullName, String packageName, + HttpTransportProperties.Authenticator authenticator) + throws JsonParseException, JsonMappingException, IOException, AxisFault, Exception { + Map map = new HashMap(); + Map deployedPackageInfoMap = getDeployedPackageInfo(authenticator, packageName, ""); + if (deployedPackageInfoMap.get("packageName") != null) { + throw new BpsServiceException(ERROR_CODE_PACKAGE_DUPLICATED_NAME,"Package " + deployedPackageInfoMap.get("packageName") + + " exist, please undeploy it first."); + } + OMElement element = deployPackage(fileName, fullName, authenticator); + System.out.println(Xml2JsonUtil.xml2JSON(element.toString())); + + long timeout = 60 * 1000L; + long timeStart = System.currentTimeMillis(); + while (System.currentTimeMillis() - timeStart < timeout) { + deployedPackageInfoMap = getDeployedPackageInfo(authenticator, packageName, ""); + if (deployedPackageInfoMap.get("packageName") == null) { + Thread.sleep(2000); + } else { + break; + } + } + if (deployedPackageInfoMap.get("packageName") == null) { + throw new BpsServiceException(ERROR_CODE_PACKAGE_DEPLOY_INFORMATION_IS_LOST, + "Package " + packageName + " deploy failed or deploy information is lost."); + } + map.put("packageName", deployedPackageInfoMap.get("packageName")); + map.put("processId", deployedPackageInfoMap.get("pid")); + return map; + } + + private OMElement deployPackage(String fileName, String fullName, + HttpTransportProperties.Authenticator authenticator) throws AxisFault { + String url = + "https://" + getConfig("host") + ":" + getConfig("port") + "/services/BPELUploader?wsdl"; + RPCServiceClient serviceClient = new RPCServiceClient(); + EndpointReference targetEPR = new EndpointReference(url); + Options options = serviceClient.getOptions(); + options.setTo(targetEPR); + options.setAction("urn:uploadService"); + options.setProperty(HTTPConstants.SO_TIMEOUT, new Integer(300000)); + options.setProperty(HTTPConstants.AUTHENTICATE, authenticator); + serviceClient.setOptions(options); + + QName qname = new QName("http://services.deployer.bpel.carbon.wso2.org", "uploadService"); + UploadedFileItem fileItem = new UploadedFileItem(); + fileItem.setFileName(fileName); + fileItem.setFileType("zip"); + + DataSource dataSource = new FileDataSource(fullName); + fileItem.setDataHandler(new DataHandler(dataSource)); + UploadedFileItem[] parameters = new UploadedFileItem[] {fileItem}; + OMElement element = serviceClient.invokeBlocking(qname, parameters); + return element; + } + + @Path(value = "package/{packageName}") + @DELETE + @Produces(value = MediaType.APPLICATION_JSON) + @ApiOperation(value = "delete", response = Map.class) + @Timed + public Map delete(@PathParam("packageName") String packageName, + @Context HttpServletRequest request) { + Map map = new LinkedHashMap(); + String errorMessage = "unkown"; + int errorCode = ERROR_CODE_NOERROR; + try { + if (!lockPackageName(packageName)) { + throw new Exception("Package " + packageName + " is operating."); + } + System.setProperty("javax.net.ssl.trustStore", "*.keystore"); + System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); + System.setProperty("javax.net.ssl.trustStore", getConfig("jksFile")); + System.setProperty("javax.net.ssl.trustStorePassword", getConfig("trustStorePassword")); + + HttpTransportProperties.Authenticator authenticator = + new HttpTransportProperties.Authenticator(); + List auth = new ArrayList(); + auth.add(Authenticator.BASIC); + authenticator.setAuthSchemes(auth); + authenticator.setUsername(getConfig("httpUsername")); + authenticator.setPassword(getConfig("httpPassword")); + authenticator.setPreemptiveAuthentication(true); + + map.putAll(bpsUndeployPackage(packageName, authenticator)); + + return map; + } catch (AxisFault e) { + errorMessage = e.getLocalizedMessage(); + errorCode = ERROR_CODE_RUNTIME_EXCEPTION_AXIS; + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (Throwable e) { + errorMessage = e.getLocalizedMessage(); + if (e instanceof BpsServiceException) { + errorCode = ((BpsServiceException) e).getErrorCode(); + } else { + errorCode = ERROR_CODE_RUNTIME_EXCEPTION; + } + log.error(e.getMessage(), e); + e.printStackTrace(); + } finally { + if (packageName != null) { + unlockPackageName(packageName); + } + } + map.put("errorCode", errorCode); + map.put("status", STATUS_FAIL); + map.put("message", errorMessage); + return map; + } + + @SuppressWarnings({"rawtypes", "unused"}) + private Map bpsUndeployPackage(String packageName, + HttpTransportProperties.Authenticator authenticator) + throws JsonParseException, JsonMappingException, IOException, AxisFault, Exception { + Map map = new HashMap(); + Map deployedPackageInfoMap = getDeployedPackageInfo(authenticator, packageName, ""); + if (deployedPackageInfoMap.get("packageName") == null) { + throw new BpsServiceException(ERROR_CODE_PACKAGE_NOTEXISTS,"Package " + deployedPackageInfoMap.get("packageName") + + " does not exist, please deploy it first."); + } + OMElement element = undeployPackage(authenticator, packageName); + deployedPackageInfoMap = getDeployedPackageInfo(authenticator, packageName, ""); + if (deployedPackageInfoMap.get("packageName") != null) { + throw new BpsServiceException(ERROR_CODE_PACKAGE_UNDEPLOY_FAILED, + "Package " + deployedPackageInfoMap.get("packageName") + " undeploy failed."); + } + map.put("status", STATUS_SUCCESS); + map.put("message", "success"); + + return map; + } + + private OMElement undeployPackage(HttpTransportProperties.Authenticator authenticator, + String packageName) throws AxisFault { + String url = "https://" + getConfig("host") + ":" + getConfig("port") + + "/services/BPELPackageManagementService?wsdl"; + RPCServiceClient serviceClient = new RPCServiceClient(); + EndpointReference targetEPR = new EndpointReference(url); + Options options = serviceClient.getOptions(); + options.setTo(targetEPR); + options.setAction("sch:undeployBPELPackage"); + options.setProperty(HTTPConstants.SO_TIMEOUT, new Integer(300000)); + options.setProperty(HTTPConstants.AUTHENTICATE, authenticator); + serviceClient.setOptions(options); + OMFactory fac = OMAbstractFactory.getOMFactory(); + OMNamespace omNs = fac.createOMNamespace("http://wso2.org/bps/management/schema", "sch"); + OMElement method = fac.createOMElement("undeployBPELPackage", omNs); + OMElement content = fac.createOMElement("package", omNs); + content.addChild(fac.createOMText(content, packageName)); + method.addChild(content); + method.build(); + OMElement res = serviceClient.sendReceive(method); + return res; + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private Map getFullDeployedPackageInfo(HttpTransportProperties.Authenticator authenticator, + String packageName, String page) throws Exception { + String result; + String jsonTemplate = + "{'listDeployedPackagesPaginated':{'page':'${page}','packageSearchString':'${searchString}'}}"; + Map jsonParamMap = new HashMap(); + jsonParamMap.put("page", page); + jsonParamMap.put("searchString", packageName); + Object params = getParams(jsonTemplate, jsonParamMap); + result = BpsProcess.invokeWsdl("https://" + getConfig("host") + ":" + getConfig("port") + + "/services/BPELPackageManagementService?wsdl", params, authenticator); + Map processMap = JsonUtil.json2Bean(result, Map.class); + return processMap; + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private Map getDeployedPackageInfo(HttpTransportProperties.Authenticator authenticator, + String packageName, String page) throws Exception { + Map resultMap = new HashMap(); + Map processMap = getFullDeployedPackageInfo(authenticator, packageName, page); + Object packages = ((Map) processMap.get("deployedPackagesPaginated")).get("package"); + Map deployedPackage = null; + if (packages instanceof List) { + for (Iterator iter = ((List) packages).iterator(); iter.hasNext();) { + Map packageMap = (Map) iter.next(); + String deployedPackageName = (String) packageMap.get("name"); + if (deployedPackageName.equals(packageName)) { + deployedPackage = packageMap; + break; + } + } + } else if (packages instanceof Map) { + String deployedPackageName = (String) ((Map) packages).get("name"); + if (deployedPackageName.equals(packageName)) { + deployedPackage = (Map) packages; + } + } + if (deployedPackage != null) { + String fullPackageName = null; + String pid = null; + Object versions = ((Map) deployedPackage.get("versions")).get("version"); + Map lastestVersion = null; + if (versions instanceof List) { + for (Iterator iter = ((List) versions).iterator(); iter.hasNext();) { + Map version = (Map) iter.next(); + if (version.get("isLatest").equals("true")) { + lastestVersion = version; + } + } + } else if (versions instanceof Map) { + lastestVersion = (Map) versions; + } + fullPackageName = (String) ((Map) ((Map) lastestVersion.get("processes")).get("process")) + .get("packageName"); + pid = (String) ((Map) ((Map) lastestVersion.get("processes")).get("process")).get("pid"); + resultMap.put("packageName", fullPackageName); + resultMap.put("pid", pid); + } + return resultMap; +} + + + @SuppressWarnings({"rawtypes", "unchecked"}) + public static Map getParams(String jsonTemplate, Map paramMap) + throws JsonParseException, JsonMappingException, IOException { + String json = jsonTemplate.replaceAll("'", "\""); + for (Iterator iter = paramMap.keySet().iterator(); iter.hasNext();) { + String key = (String) iter.next(); + String value = ""; + if (paramMap.get(key) != null) { + value = paramMap.get(key).toString().replaceAll("\"", "\\\\\""); + } + json = json.replaceAll("\\$\\{" + key + "\\}", value); + } + return JsonUtil.json2Bean(json, Map.class); + } + + @GET + @Path(value = "listPackages") + @Produces(value = MediaType.APPLICATION_JSON) + @ApiOperation(value = "list packages", response = Map.class) + @Timed + public Map listPackages(@QueryParam("page") String page, + @QueryParam("searchString") String searchString, @Context HttpServletRequest request) + throws IOException { + Map map = new LinkedHashMap(); + String errorMessage = "unkown"; + int errorCode = ERROR_CODE_NOERROR; + String packageName = null; + try { + System.setProperty("javax.net.ssl.trustStore", "*.keystore"); + System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); + System.setProperty("javax.net.ssl.trustStore", getConfig("jksFile")); + System.setProperty("javax.net.ssl.trustStorePassword", getConfig("trustStorePassword")); + + HttpTransportProperties.Authenticator authenticator = + new HttpTransportProperties.Authenticator(); + List auth = new ArrayList(); + auth.add(Authenticator.BASIC); + authenticator.setAuthSchemes(auth); + authenticator.setUsername(getConfig("httpUsername")); + authenticator.setPassword(getConfig("httpPassword")); + authenticator.setPreemptiveAuthentication(true); + + map.putAll(getFullDeployedPackageInfo(authenticator,searchString,page)); + + map.put("status", STATUS_SUCCESS); + map.put("message", "success"); + return map; + } catch (AxisFault e) { + errorMessage = e.getLocalizedMessage(); + errorCode = ERROR_CODE_RUNTIME_EXCEPTION_AXIS; + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (IOException e) { + errorMessage = e.getLocalizedMessage(); + errorCode = ERROR_CODE_RUNTIME_EXCEPTION_IO; + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (Throwable e) { + if (e instanceof BpsServiceException) { + errorCode = ((BpsServiceException) e).getErrorCode(); + } else { + errorCode = ERROR_CODE_RUNTIME_EXCEPTION; + } + errorMessage = e.getLocalizedMessage(); + log.error(e.getMessage(), e); + e.printStackTrace(); + } finally { + if (packageName != null) { + unlockPackageName(packageName); + } + } + map.put("errorCode", errorCode); + map.put("status", STATUS_FAIL); + map.put("message", errorMessage); + return map; + } + + @SuppressWarnings("rawtypes") + public static void main(String[] args) { + try { + + boolean remoteDebug = true; + boolean localDebug = false; + if (remoteDebug) { + Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build(); + WebTarget target = client.target("http://localhost:8101/openoapi/wso2bpel/v1/package"); + FileDataBodyPart bodyPart = new FileDataBodyPart("file", + new File("F:\\wso2bps-3.5.1\\wso2bps-3.5.1\\repository\\samples\\bpel\\Alarm.zip")); + FormDataMultiPart formDataMultiPart = new FormDataMultiPart(); + formDataMultiPart.field("fileName", "Alarm.zip").bodyPart(bodyPart); + String result = target.request(MediaType.APPLICATION_JSON) + .post(Entity.entity(formDataMultiPart, formDataMultiPart.getMediaType()), String.class); + System.out.println(result); + } + // + // System.out.println("************************************************************************"); + // + // bodyPart = new FileDataBodyPart("file", new + // File("D:\\temp\\bpel-sample\\AssignDate\\AssignDate.zip")); + // formDataMultiPart = new FormDataMultiPart(); + // formDataMultiPart.field("fileName", + // "AssignDate.zip").bodyPart(bodyPart); + // result = target.request(MediaType.APPLICATION_JSON) + // .post(Entity.entity(formDataMultiPart, + // formDataMultiPart.getMediaType()), String.class); + // System.out.println(result); + // + if (localDebug) { + System.setProperty("javax.net.ssl.trustStore", "*.keystore"); + System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); + System.setProperty("javax.net.ssl.trustStore", + "D:\\software\\WSO2\\wso2bps-3.5.1\\repository\\resources\\security\\wso2carbon.jks"); + System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon"); + HttpTransportProperties.Authenticator authenticator = + new HttpTransportProperties.Authenticator(); + List auth = new ArrayList(); + auth.add(Authenticator.BASIC); + authenticator.setAuthSchemes(auth); + authenticator.setUsername("admin"); + authenticator.setPassword("admin"); + authenticator.setPreemptiveAuthentication(true); + // + // String packageName = "RESTProcess"; + // Map deployedPackageInfoMap = + // getDeployedPackageInfo(authenticator, packageName); + + BpsPackage packageTest = new BpsPackage(); + Map map; + // map = packageTest.bpsUndeployPackage("AssignDate", + // authenticator); + // System.out.println(JsonUtil.bean2Json(map)); + map = packageTest.bpsDeployPackage("AssignDate.zip", + "D:\\temp\\bpel-sample\\AssignDate\\AssignDate.zip", "AssignDate", authenticator); + System.out.println(JsonUtil.bean2Json(map)); + map = packageTest.bpsUndeployPackage("AssignDate", authenticator); + System.out.println(JsonUtil.bean2Json(map)); + } + + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsProcess.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsProcess.java new file mode 100644 index 0000000..148e309 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsProcess.java @@ -0,0 +1,544 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * 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.carbon.bpel.resources; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicLong; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +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.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.xml.namespace.QName; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMAttribute; +import org.apache.axiom.om.OMDocument; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMFactory; +import org.apache.axiom.om.OMNamespace; +import org.apache.axiom.om.OMText; +import org.apache.axiom.om.OMXMLBuilderFactory; +import org.apache.axiom.om.OMXMLParserWrapper; +import org.apache.axiom.om.util.StAXParserConfiguration; +import org.apache.axis2.AxisFault; +import org.apache.axis2.addressing.EndpointReference; +import org.apache.axis2.client.Options; +import org.apache.axis2.client.ServiceClient; +import org.apache.axis2.rpc.client.RPCServiceClient; +import org.apache.axis2.transport.http.HTTPConstants; +import org.apache.axis2.transport.http.HttpTransportProperties; +import org.apache.axis2.transport.http.HttpTransportProperties.Authenticator; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.glassfish.jersey.media.multipart.MultiPartFeature; +import org.openo.carbon.bpel.common.Config; +import org.openo.carbon.bpel.util.JsonUtil; +import org.openo.carbon.bpel.util.SoapUtil; +import org.openo.carbon.bpel.util.Xml2JsonUtil; + +import com.codahale.metrics.annotation.Timed; +import com.eviware.soapui.model.iface.MessagePart; +import com.eviware.soapui.model.iface.Request; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("/") +@Api(tags = {"wso2 bpel api"}) +public class BpsProcess { + + private static final Log log = LogFactory.getLog(BpsProcess.class); + + public static final int STATUS_SUCCESS = 1; + public static final int STATUS_FAIL = 0; + + private Map configMap = null; + + @SuppressWarnings("unused") + private final AtomicLong counter; + + public BpsProcess() { + this.counter = new AtomicLong(); + } + + private synchronized String getConfig(String key) { + if (configMap == null) { + configMap = new HashMap(); + //Config.getConfigration().getMsbServerAddr(); + /* String uploadFilePath = ConfigManager.getInstance().getProperty("wso2.uploadfile.path"); + String jksFile = ConfigManager.getInstance().getProperty("wso2.ssl.jks.file"); + String trustStorePassword = + ConfigManager.getInstance().getProperty("wso2.ssl.trustStorePassword"); + String httpUsername = + ConfigManager.getInstance().getProperty("wso2.http.authenticator.username"); + String httpPassword = + ConfigManager.getInstance().getProperty("wso2.http.authenticator.password"); + String host = ConfigManager.getInstance().getProperty("wso2.host"); + String port = ConfigManager.getInstance().getProperty("wso2.http.port");*/ + String uploadFilePath = Config.getConfigration().getWso2UploadFilePath(); + String jksFile = Config.getConfigration().getWso2SslJksFile(); + String trustStorePassword = Config.getConfigration().getWso2SslJksPassword(); + String httpUsername = Config.getConfigration().getWso2AuthUserName(); + String httpPassword = Config.getConfigration().getWso2AuthPassword(); + String host = Config.getConfigration().getWso2Host(); + String port = Config.getConfigration().getWso2HostPort(); + configMap.put("uploadFilePath", uploadFilePath); + configMap.put("jksFile", jksFile); + configMap.put("trustStorePassword", trustStorePassword); + configMap.put("httpUsername", httpUsername); + configMap.put("httpPassword", httpPassword); + configMap.put("host", host); + configMap.put("port", port); + } + if (configMap.containsKey(key)) { + return configMap.get(key); + } else { + return ""; + } + } + + @SuppressWarnings("unchecked") + @POST + @Path("process/instance") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(value = MediaType.APPLICATION_JSON) + @ApiOperation(value = "startProcess", response = Map.class) + @Timed + public Map startProcess(JsonNode jsonObj, @Context HttpServletRequest request) { + Map map = new LinkedHashMap(); + String errorMessage = "unkown"; + + Map paramMap = new HashMap(); + try { + paramMap = JsonUtil.json2Bean(jsonObj.toString(), Map.class); + String processId = (String) paramMap.get("processId"); + + Object params = paramMap.get("params"); + + String wsdlUrl = getWsdlUrl(processId); + String response = invokeWsdl(wsdlUrl, params); + + map.put("status", STATUS_SUCCESS); + map.put("message", "success"); + // map.put("wsdl", wsdlUrl); + map.put("response", response); + return map; + } catch (JsonParseException e) { + errorMessage = e.getLocalizedMessage(); + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (JsonMappingException e) { + errorMessage = e.getLocalizedMessage(); + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (IOException e) { + errorMessage = e.getLocalizedMessage(); + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (Exception e) { + errorMessage = e.getLocalizedMessage(); + log.error(e.getMessage(), e); + e.printStackTrace(); + } + + map.put("status", STATUS_FAIL); + map.put("message", errorMessage); + return map; + } + + public static String invokeWsdl(String wsdlUrl, Object params) throws Exception { + return invokeWsdl(wsdlUrl, params, null); + } + + @SuppressWarnings({"unused", "rawtypes"}) + public static String invokeWsdl(String wsdlUrl, Object params, + HttpTransportProperties.Authenticator authenticator) throws Exception { + SoapUtil soapUtil = new SoapUtil(); + Request[] requestTemplates = soapUtil.getRequestTemplate(wsdlUrl); + String requestTemplate = null; + Request invokeRequest = null; + for (Request requestXML : requestTemplates) { + + InputStream is = new ByteArrayInputStream(requestXML.getRequestContent().getBytes()); + OMXMLParserWrapper builder = OMXMLBuilderFactory.createOMBuilder( + OMAbstractFactory.getOMFactory(), StAXParserConfiguration.STANDALONE, is); + OMElement root = builder.getDocumentElement(); + OMDocument omDocument = builder.getDocument(); + Iterator iter = omDocument.getChildren(); + OMElement bodyElement = null; + while (iter.hasNext()) { + OMElement node = (OMElement) iter.next(); + String nodeName = node.getLocalName(); + if (nodeName.equals("Envelope")) { + Iterator envChildren = node.getChildElements(); + while (envChildren.hasNext()) { + Object childNode = envChildren.next(); + if (childNode instanceof OMElement) { + if (((OMElement) childNode).getLocalName().equals("Body")) { + bodyElement = (OMElement) childNode; + } + } + } + } + } + Set paramSet = new HashSet(); + Iterator bodyIter = bodyElement.getChildElements(); + while (bodyIter.hasNext()) { + Object obj = bodyIter.next(); + OMElement requestBody = (OMElement) obj; + paramSet.add(requestBody.getLocalName()); + } + if (params instanceof Map) { + Set paramKeySet = ((Map) params).keySet(); + boolean matched = true; + for (Object key : paramKeySet) { + if (!paramSet.contains(key)) { + matched = false; + continue; + } + } + if (matched) { + invokeRequest = requestXML; + requestTemplate = requestXML.getRequestContent(); + break; + } + } + } + if (requestTemplate == null) { + throw new Exception("Invalid param."); + } + + InputStream is = new ByteArrayInputStream(requestTemplate.getBytes()); + OMXMLParserWrapper builder = OMXMLBuilderFactory + .createOMBuilder(OMAbstractFactory.getOMFactory(), StAXParserConfiguration.STANDALONE, is); + OMElement root = builder.getDocumentElement(); + OMDocument omDocument = builder.getDocument(); + Iterator iter = omDocument.getChildren(); + OMElement bodyElement = null; + while (iter.hasNext()) { + OMElement node = (OMElement) iter.next(); + String nodeName = node.getLocalName(); + if (nodeName.equals("Envelope")) { + Iterator envChildren = node.getChildElements(); + while (envChildren.hasNext()) { + Object childNode = envChildren.next(); + if (childNode instanceof OMElement) { + if (((OMElement) childNode).getLocalName().equals("Body")) { + bodyElement = (OMElement) childNode; + } + } + } + } + } + + Options options = new Options(); + EndpointReference targetEPR = new EndpointReference(wsdlUrl); + options.setTo(targetEPR); + if (authenticator != null) { + options.setProperty(HTTPConstants.AUTHENTICATE, authenticator); + } + ServiceClient sender = new ServiceClient(); + sender.setOptions(options); + OMFactory factory = OMAbstractFactory.getOMFactory(); + OMElement requestBody = null; + Iterator bodyIter = bodyElement.getChildElements(); + while (bodyIter.hasNext()) { + Object obj = bodyIter.next(); + requestBody = (OMElement) obj; + } + + // Iterator requestBodyIter = requestBody.getChildElements(); + setParams(requestBody, params); + + requestBody.build(); + OMElement result = null; + boolean needResponse = false; + try { + MessagePart[] parts = invokeRequest.getResponseParts(); + if (parts != null && parts.length > 0) { + needResponse = true; + } + } catch (RuntimeException e) { + e.printStackTrace(); + } catch (Throwable e) { + e.printStackTrace(); + } + if (needResponse) { + result = sender.sendReceive(requestBody); + return Xml2JsonUtil.xml2JSON(result.toString()); + } else { + sender.sendRobust(requestBody); + return ""; + } + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private static void setParams(OMElement requestBody, Object params) { + Object currentParams = null; + if (params instanceof Map) { + currentParams = ((Map) params).get((requestBody).getLocalName()); + Object obj = requestBody.getFirstElement(); + if (obj == null) { + if (currentParams instanceof String) { + requestBody.setText((String) currentParams); + } + } else { + Iterator iter = requestBody.getChildElements(); + while (iter.hasNext()) { + OMElement child = iter.next(); + setParams((OMElement) child, currentParams); + } + } + } + } + + @SuppressWarnings("unchecked") + public String getWsdlUrl(String pid) { + log.warn("rest begin..."); + String wsdlUrl = null; + try { + System.setProperty("javax.net.ssl.trustStore", "*.keystore"); + + System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); + + System.setProperty("javax.net.ssl.trustStore", getConfig("jksFile")); + System.setProperty("javax.net.ssl.trustStorePassword", getConfig("trustStorePassword")); + + String url = "https://" + getConfig("host") + ":" + getConfig("port") + + "/services/ProcessManagementService?wsdl"; + RPCServiceClient serviceClient = new RPCServiceClient(); + EndpointReference targetEPR = new EndpointReference(url); + Options options = serviceClient.getOptions(); + options.setTo(targetEPR); + // options.setAction("sch:undeployBPELPackage"); + + options.setProperty(HTTPConstants.SO_TIMEOUT, new Integer(300000)); + HttpTransportProperties.Authenticator authenticator = + new HttpTransportProperties.Authenticator(); + List auth = new ArrayList(); + auth.add(Authenticator.BASIC); + authenticator.setAuthSchemes(auth); + authenticator.setUsername(getConfig("httpUsername")); + authenticator.setPassword(getConfig("httpPassword")); + authenticator.setPreemptiveAuthentication(true); + options.setProperty(HTTPConstants.AUTHENTICATE, authenticator); + + serviceClient.setOptions(options); + + OMFactory fac = OMAbstractFactory.getOMFactory(); + OMNamespace omNs = fac.createOMNamespace("http://wso2.org/bps/management/schema", "sch"); + + OMElement method = fac.createOMElement("getProcessInfoIn", omNs); + QName pidQName = QName.valueOf(pid); + OMElement pidElement = fac.createOMElement("pid", omNs); + + pidElement.addChild(fac.createOMText(pidElement, pidQName)); + method.addChild(pidElement); + + method.build(); + + OMElement res = serviceClient.sendReceive(method); + res.getFirstElement().getText(); + + // System.out.println(JsonUtil.bean2Json(parse(res))); + + Iterator iter = res.getChildrenWithLocalName("endpoints"); + if (iter.hasNext()) { + OMElement endPoints = (OMElement) iter.next(); + Iterator endPointIter = endPoints.getChildrenWithLocalName("endpointRef"); + if (endPointIter.hasNext()) { + OMElement endpointRef = (OMElement) endPointIter.next(); + Iterator endpointRefIter = + endpointRef.getChildrenWithLocalName("serviceLocations"); + if (endpointRefIter.hasNext()) { + OMElement serviceLocations = (OMElement) endpointRefIter.next(); + Iterator serviceLocationsIter = + serviceLocations.getChildrenWithLocalName("serviceLocation"); + while (serviceLocationsIter.hasNext()) { + OMElement serviceLocation = (OMElement) serviceLocationsIter.next(); + String sUrl = serviceLocation.getText(); + if (sUrl.endsWith("wsdl")) { + wsdlUrl = sUrl; + break; + } + } + } + } + } + + } catch (AxisFault e) { + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (Throwable e) { + log.error(e.getMessage(), e); + e.printStackTrace(); + } finally { + log.warn("invoke finally..."); + } + return wsdlUrl; + } + + @SuppressWarnings({"unused", "rawtypes", "unchecked"}) + private Map parse(OMElement node) { + Map resultMap = new HashMap(); + Iterator attrIter = node.getAllAttributes(); + while (attrIter.hasNext()) { + OMAttribute attr = (OMAttribute) attrIter.next(); + resultMap.put(attr.getLocalName(), attr.getAttributeValue()); + } + boolean hasChild = false; + List childList = new ArrayList(); + Iterator childIter = node.getChildren();// getChildElements(); + while (childIter.hasNext()) { + hasChild = true; + Object child = childIter.next(); + if (child instanceof OMText) { + resultMap.put(node.getLocalName(), ((OMText) child).getText()); + } else if (child instanceof OMElement) { + childList.add(parse((OMElement) child)); + resultMap.put(node.getLocalName(), childList); + } + } + return resultMap; + } + + public static void main1(String[] args) { + Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build(); + WebTarget target = client.target("http://127.0.0.1:8080/wso2bpel/v1/process/instance"); + String jsonObj = + "{\"processId\":\"{http://ode/bpel/unit-test}HelloWorld2-18\",\"params\": {\"hello\":{\"TestPart\":\"AAA\"}}}"; + Response response = target.request(MediaType.APPLICATION_JSON) + .post(Entity.entity(jsonObj, MediaType.APPLICATION_JSON)); + int responseCode = response.getStatus(); + if (responseCode == 200) { + String excuteRespJson = response.readEntity(String.class); + // context.setExcuteRespJson(excuteRespJson); + // System.out.println("excute responseJson=====" + + // context.getExcuteRespJson()); + System.out.println(excuteRespJson); + } + + System.out.println("************************************************************************"); + jsonObj = + "{\"processId\":\"{http://ode/bpel/unit-test}HelloWorld2-18\",\"params\": {\"hello\":{\"TestPart\":\"AAA\"}}}"; + BpsProcess process = new BpsProcess(); + try { + Map resultMap = process.startProcess(JsonUtil.getJsonNode(jsonObj), null); + System.out.println(JsonUtil.bean2Json(resultMap)); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("************************************************************************"); + jsonObj = + "{\"processId\":\"{http://ode/bpel/unit-test}HelloXslWorld-3\",\"params\": {\"helloXsl\":{\"TestPart\":{\"content\":\"AAA\"}}}}"; + process = new BpsProcess(); + try { + Map resultMap = process.startProcess(JsonUtil.getJsonNode(jsonObj), null); + System.out.println(JsonUtil.bean2Json(resultMap)); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("************************************************************************"); + jsonObj = + "{\"processId\":\"{http://wso2.org/bps/samples/While}While-5\",\"params\": {\"WhileRequest\":{\"input\":\"365\"}}}"; + process = new BpsProcess(); + try { + Map resultMap = process.startProcess(JsonUtil.getJsonNode(jsonObj), null); + System.out.println(JsonUtil.bean2Json(resultMap)); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } catch (IOException e) { + } + + } + + @SuppressWarnings("unchecked") + public static void main(String[] args) { + + Map map = new LinkedHashMap(); + String errorMessage = "unkown"; + + Map paramMap = new HashMap(); + try { + String param = + "{\"planInput\":{\"sfc_count\":\"2\",\"nsInstanceId\":\"223\",\"vnfmId\":\"112\",\"instanceId\":\"334\",\"object_context\":\"{\\\"e\\\":{\\\"f\\\":\\\"4\\\"}}\",\"vnf_count\":\"2\",\"serviceTemplateId\":\"?\",\"vl_count\":\"2\",\"containerapiUrl\":\"?\",\"object_additionalParamForVnf\":\"[{\\\"b\\\":1},{\\\"c\\\":{\\\"d\\\":\\\"2\\\"}}}]\",\"object_additionalParamForNs\":\"[{\\\"a\\\":3},{\\\"e\\\":{\\\"f\\\":\\\"4\\\"}}}]\"}}"; + String jsonObj = + "{\"processId\":\"{http://wso2.org/bps/samples/While}While-5\",\"params\":" + param + "}"; + paramMap = JsonUtil.json2Bean(jsonObj.toString(), Map.class); + Object params = paramMap.get("params"); + String wsdlUrl = "http://10.74.151.36:9763/services/initService?wsdl"; + String response = invokeWsdl(wsdlUrl, params); + map.put("status", STATUS_SUCCESS); + map.put("message", "success"); + map.put("response", response); + System.out.println(JsonUtil.bean2Json(map)); + } catch (JsonParseException e) { + errorMessage = e.getLocalizedMessage(); + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (JsonMappingException e) { + errorMessage = e.getLocalizedMessage(); + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (IOException e) { + errorMessage = e.getLocalizedMessage(); + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (Exception e) { + errorMessage = e.getLocalizedMessage(); + log.error(e.getMessage(), e); + e.printStackTrace(); + } + + map.put("status", STATUS_FAIL); + map.put("message", errorMessage); + try { + System.out.println(JsonUtil.bean2Json(map)); + } catch (IOException e) { + errorMessage = e.getLocalizedMessage(); + log.error(e.getMessage(), e); + e.printStackTrace(); + } + + } +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsServiceException.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsServiceException.java new file mode 100644 index 0000000..bd05a95 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsServiceException.java @@ -0,0 +1,30 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * 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.carbon.bpel.resources; + +public class BpsServiceException extends Exception { + + int errorCode = 0; + + public int getErrorCode() { + return errorCode; + } + + public BpsServiceException(int errorCode, String message) { + super(message); + this.errorCode = errorCode; + } +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/RestAppConfig.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/RestAppConfig.java new file mode 100644 index 0000000..b81fbe9 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/RestAppConfig.java @@ -0,0 +1,37 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * 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.carbon.bpel.resources; + +import javax.ws.rs.ApplicationPath; + +import org.glassfish.jersey.filter.LoggingFilter; +import org.glassfish.jersey.media.multipart.MultiPartFeature; +import org.glassfish.jersey.server.ResourceConfig; + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + +@ApplicationPath("/v1") +public class RestAppConfig extends ResourceConfig { + + public RestAppConfig() { + packages("org.wso2.carbon.bpel.rest.ext.v1"); + register(JacksonJsonProvider.class); + register(MultiPartFeature.class); + // register(MultiPartResource.class); + register(LoggingFilter.class); + } + +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/ClientWsdlLoader.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/ClientWsdlLoader.java new file mode 100644 index 0000000..70a9588 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/ClientWsdlLoader.java @@ -0,0 +1,82 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * 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.carbon.bpel.util; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.net.URL; +import org.apache.log4j.Logger; + +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpException; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.httpclient.methods.GetMethod; + +import com.eviware.soapui.impl.wsdl.support.wsdl.WsdlLoader; + +public class ClientWsdlLoader extends WsdlLoader { + private static Logger logger = Logger.getLogger(ClientWsdlLoader.class); + + private boolean isAborted = false; + private HttpClient httpClient; + + public ClientWsdlLoader(String url, HttpClient httpClient) { + super(url); + this.httpClient = httpClient; + } + + public InputStream load(String url) throws Exception { + GetMethod httpGetMethod; + + if (url.startsWith("file")) { + return new URL(url).openStream(); + } + + // Authentication is not being overridden on the method. It needs + // to be present on the supplied HttpClient instance! + httpGetMethod = new GetMethod(url); + httpGetMethod.setDoAuthentication(true); + + try { + int result = httpClient.executeMethod(httpGetMethod); + + if (result != HttpStatus.SC_OK) { + if (result < 200 || result > 299) { + throw new HttpException( + "Received status code '" + result + "' on WSDL HTTP (GET) request: '" + url + "'."); + } else { + logger.warn( + "Received status code '" + result + "' on WSDL HTTP (GET) request: '" + url + "'."); + } + } + + return new ByteArrayInputStream(httpGetMethod.getResponseBody()); + } finally { + httpGetMethod.releaseConnection(); + } + } + + public boolean abort() { + isAborted = true; + return true; + } + + public boolean isAborted() { + return isAborted; + } + + public void close() {} +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/JsonUtil.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/JsonUtil.java new file mode 100644 index 0000000..f2a4d97 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/JsonUtil.java @@ -0,0 +1,61 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * 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.carbon.bpel.util; + +import java.io.IOException; +import java.io.StringWriter; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JsonUtil { + + @SuppressWarnings("deprecation") + public static String bean2Json(Object obj) throws IOException { + ObjectMapper mapper = new ObjectMapper(); + StringWriter sw = new StringWriter(); + JsonGenerator gen = new JsonFactory().createJsonGenerator(sw); + mapper.writeValue(gen, obj); + gen.close(); + return sw.toString(); + } + + public static T json2Bean(String jsonStr, Class objClass) + throws JsonParseException, JsonMappingException, IOException { + ObjectMapper mapper = new ObjectMapper(); + return mapper.readValue(jsonStr, objClass); + } + + @SuppressWarnings("deprecation") + public static T readJson(String jsonStr, Class collectionClass, Class... elementClasses) + throws Exception { + ObjectMapper mapper = new ObjectMapper(); + JavaType javaType = + mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); + return mapper.readValue(jsonStr, javaType); + } + + public static JsonNode getJsonNode(String json) throws JsonProcessingException, IOException { + return new ObjectMapper().readTree(json); + } + +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/LRULinkedHashMap.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/LRULinkedHashMap.java new file mode 100644 index 0000000..deb07c6 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/LRULinkedHashMap.java @@ -0,0 +1,106 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * 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.carbon.bpel.util; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +/** + * + * @author bsli + * + * @param + * @param + */ +@SuppressWarnings("serial") +public class LRULinkedHashMap extends LinkedHashMap { + private final int maxCapacity; + + private static final float DEFAULT_LOAD_FACTOR = 0.75f; + + private final Lock lock = new ReentrantLock(); + + public LRULinkedHashMap(int maxCapacity) { + super(maxCapacity, DEFAULT_LOAD_FACTOR, true); + this.maxCapacity = maxCapacity; + } + + @Override + protected boolean removeEldestEntry(java.util.Map.Entry eldest) { + return size() > maxCapacity; + } + + @Override + public boolean containsKey(Object key) { + try { + lock.lock(); + return super.containsKey(key); + } finally { + lock.unlock(); + } + } + + @Override + public V get(Object key) { + try { + lock.lock(); + return super.get(key); + } finally { + lock.unlock(); + } + } + + @Override + public V put(K key, V value) { + try { + lock.lock(); + return super.put(key, value); + } finally { + lock.unlock(); + } + } + + public int size() { + try { + lock.lock(); + return super.size(); + } finally { + lock.unlock(); + } + } + + public void clear() { + try { + lock.lock(); + super.clear(); + } finally { + lock.unlock(); + } + } + + public Collection> getAll() { + try { + lock.lock(); + return new ArrayList>(super.entrySet()); + } finally { + lock.unlock(); + } + } +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/SoapUtil.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/SoapUtil.java new file mode 100644 index 0000000..6f7bf0d --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/SoapUtil.java @@ -0,0 +1,156 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * 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.carbon.bpel.util; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import javax.naming.ConfigurationException; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.apache.commons.httpclient.HttpClient; +import org.apache.log4j.Logger; + +import com.eviware.soapui.impl.wsdl.WsdlInterface; +import com.eviware.soapui.impl.wsdl.WsdlProject; +import com.eviware.soapui.impl.wsdl.support.wsdl.WsdlLoader; +import com.eviware.soapui.model.iface.Operation; +import com.eviware.soapui.model.iface.Request; + +public class SoapUtil { + private static final Logger log = Logger.getLogger(SoapUtil.class); + + private DocumentBuilderFactory docBuilderFactory; + private Map wsdls = new LRULinkedHashMap(256); + + public SoapUtil() { + docBuilderFactory = DocumentBuilderFactory.newInstance(); + docBuilderFactory.setNamespaceAware(true); + } + + public Request[] getRequestTemplate(String wsdlUrl) + throws UnsupportedOperationException, IOException { + Request[] requests = new Request[0]; + List requestList = new ArrayList(); + Operation operationInst = null; + WsdlInterface[] wsdlInterfaces = getWsdlInterfaces(wsdlUrl, null); + for (WsdlInterface wsdlInterface : wsdlInterfaces) { + Operation opr = wsdlInterface.getOperationAt(0); + if (opr != null) { + operationInst = opr; + String requestTemplate = operationInst.getRequestAt(0).getRequestContent(); + requestList.add(operationInst.getRequestAt(0)); + } + } + requests = requestList.toArray(new Request[0]); + return requests; + } + + /** + * + * @param wsdl + * @param operation + * @param httpClientProps + * @return + * @throws IOException + * @throws UnsupportedOperationException + */ + private Operation getOperation(String wsdl, String operation, Properties httpClientProps) + throws IOException, UnsupportedOperationException { + WsdlInterface[] wsdlInterfaces = getWsdlInterfaces(wsdl, httpClientProps); + for (WsdlInterface wsdlInterface : wsdlInterfaces) { + Operation operationInst = wsdlInterface.getOperationByName(operation); + + if (operationInst != null) { + return operationInst; + } + } + wsdls.remove(wsdl); + wsdlInterfaces = getWsdlInterfaces(wsdl, httpClientProps); + for (WsdlInterface wsdlInterface : wsdlInterfaces) { + Operation operationInst = wsdlInterface.getOperationByName(operation); + if (operationInst != null) { + return operationInst; + } + } + + throw new UnsupportedOperationException( + "Operation '" + operation + "' not supported by WSDL '" + wsdl + "'."); + } + + /** + * + * @param wsdl + * @param httpClientProps + * @return + * @throws IOException + */ + private WsdlInterface[] getWsdlInterfaces(String wsdl, Properties httpClientProps) + throws IOException { + try { + WsdlInterface[] wsdlInterfaces = wsdls.get(wsdl); + if (wsdlInterfaces == null) { + WsdlProject wsdlProject = new WsdlProject(); + WsdlLoader wsdlLoader = createWsdlLoader(wsdl, httpClientProps); + + wsdlInterfaces = wsdlProject.importWsdl(wsdl, true, wsdlLoader); + + wsdls.put(wsdl, wsdlInterfaces); + } + return wsdlInterfaces; + } catch (Exception e) { + e.printStackTrace(); + log.error(e.getMessage()); + throw new RuntimeException("Failed to import WSDL '" + wsdl + "'."); + } + } + + /** + * + * @param wsdl + * @param httpClientProps + * @return + * @throws ConfigurationException + */ + private WsdlLoader createWsdlLoader(String wsdl, Properties httpClientProps) + throws ConfigurationException { + HttpClient httpClient = new HttpClient(); + return new ClientWsdlLoader(wsdl, httpClient); + } + + public static void main(String[] args) { + SoapUtil soapUtil = new SoapUtil(); + + try { + String url = "http://10.74.151.36:9763/services/initService?wsdl"; + Request[] requestXMLs = soapUtil.getRequestTemplate(url); + + for (Request requestXML : requestXMLs) { + String requestJson = Xml2JsonUtil.xml2JSON(requestXML.getRequestContent()); + System.out.println("===================================="); + System.out.println(requestJson); + } + + } catch (UnsupportedOperationException e1) { + e1.printStackTrace(); + } catch (IOException e1) { + e1.printStackTrace(); + } + } +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/Xml2JsonUtil.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/Xml2JsonUtil.java new file mode 100644 index 0000000..7f05a84 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/Xml2JsonUtil.java @@ -0,0 +1,141 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * 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.carbon.bpel.util; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.InputStream; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import net.sf.json.JSONObject; + +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.input.SAXBuilder; + +public class Xml2JsonUtil { + /** + * transform xml to json + * + * @param xml xml format string + * @return return json string when success; otherwise return null + */ + public static String xml2JSON(String xml) { + JSONObject obj = new JSONObject(); + try { + InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8")); + SAXBuilder sb = new SAXBuilder(); + Document doc = sb.build(is); + Element root = doc.getRootElement(); + obj.put(root.getName(), iterateElement(root)); + return obj.toString(); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * transform xml file to json string + * + * @param file java.io.File is an effective xml file + * @return return json string when success; otherwise return null + */ + public static String xml2JSON(File file) { + JSONObject obj = new JSONObject(); + try { + SAXBuilder sb = new SAXBuilder(); + Document doc = sb.build(file); + Element root = doc.getRootElement(); + obj.put(root.getName(), iterateElement(root)); + return obj.toString(); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * an iteration function + * + * @param parentElement : org.jdom.Element + * @return java.util.Map + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + private static Map iterateElement(Element parentElement) { + List node = parentElement.getChildren(); + Element element = null; + Map map = new HashMap(); + List list = null; + for (int i = 0; i < node.size(); i++) { + element = (Element) node.get(i); + if (element.getTextTrim().equals("")) { + if (element.getChildren().size() == 0) + continue; + if (map.containsKey(element.getName())) { + Object obj = map.get(element.getName()); + if (obj instanceof Map) { + list = new LinkedList(); + list.add(obj); + list.add(iterateElement(element)); + map.remove(element.getName()); + map.put(element.getName(), list); + } else if (obj instanceof List) { + list = (List) obj; + list.add(iterateElement(element)); + } + } else { + map.put(element.getName(), iterateElement(element)); + } + } else { + map.put(element.getName(), element.getTextTrim()); + } + } + return map; + } + + public static void main(String[] args) { + System.out.println(Xml2JsonUtil.xml2JSON("" + "" + "" + + "MapGuideddddddd" + "true" + "" + + "ddd" + "" + "" + "" + "ccc" + + "ggg" + "" + "aaa" + + "" + "" + "" + "" + "" + "33333333" + + "" + "" + "444" + "" + "")); + + String xml = + " fdsafasdfasdf "; + + System.out.println(Xml2JsonUtil.xml2JSON(xml)); + + xml = + " ? "; + + System.out.println(Xml2JsonUtil.xml2JSON(xml)); + + xml = + ""; + + System.out.println(Xml2JsonUtil.xml2JSON(xml)); + + xml = + " 2 112 {\"e\":{\"f\":\"4\"}} ? 2 ? 223 334 2 [{\"b\":1},{\"c\":{\"d\":\"2\"}}}] [{\"a\":3},{\"e\":{\"f\":\"4\"}}}] "; + + System.out.println(Xml2JsonUtil.xml2JSON(xml)); + } +} -- cgit 1.2.3-korg