diff options
author | 2017-01-22 16:06:27 +0800 | |
---|---|---|
committer | 2017-01-22 16:13:11 +0800 | |
commit | 2fc88d416c3207c382b9b35f847a25c1114cbdd5 (patch) | |
tree | f50c8d0b419997bab319bb0d12746d90760495de /wso2bpel-ext/wso2bpel-core/BPEL4RESTLight | |
parent | b9d6eed278f02c75865fa97f4ba6020e348f2e93 (diff) |
Merger the code provide by lvbo chenbo.
Change-Id: I6b4b0402dea075e8d4d4629dfef3fe16d7930901
Issue-id: OCS-198
Signed-off-by: 10090474 <yuan.hu1@zte.com.cn>
Diffstat (limited to 'wso2bpel-ext/wso2bpel-core/BPEL4RESTLight')
17 files changed, 1399 insertions, 0 deletions
diff --git a/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/libs/ode-bpel-api-1.3.5-wso2v4.jar b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/libs/ode-bpel-api-1.3.5-wso2v4.jar Binary files differnew file mode 100644 index 0000000..b6da951 --- /dev/null +++ b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/libs/ode-bpel-api-1.3.5-wso2v4.jar diff --git a/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/libs/ode-bpel-obj-1.3.5-wso2v4.jar b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/libs/ode-bpel-obj-1.3.5-wso2v4.jar Binary files differnew file mode 100644 index 0000000..dccc75f --- /dev/null +++ b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/libs/ode-bpel-obj-1.3.5-wso2v4.jar diff --git a/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/libs/ode-bpel-runtime-1.3.5-wso2v4.jar b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/libs/ode-bpel-runtime-1.3.5-wso2v4.jar Binary files differnew file mode 100644 index 0000000..f8d5c45 --- /dev/null +++ b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/libs/ode-bpel-runtime-1.3.5-wso2v4.jar diff --git a/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/pom.xml b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/pom.xml new file mode 100644 index 0000000..1e00421 --- /dev/null +++ b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/pom.xml @@ -0,0 +1,147 @@ +<!-- + + Copyright (C) 2015 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. + +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.openo.common-services.common-utilities.wso2bpel-ext</groupId> + <artifactId>wso2bpel-core-parent</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> +<!-- + <groupId>org.openo.common-services.common-utilities.wso2bpel-ext</groupId> + <version>0.0.1-SNAPSHOT</version> + --> + <artifactId>BPEL4RESTLight</artifactId> + <name>openo/commonservice/commonutilities/wso2bpel-core-parent/BPEL4RESTLight</name> + + <packaging>jar</packaging> + + <properties> + <httpclient.version>4.4.1</httpclient.version> + </properties> + + <build> + + <finalName>bpel4rest</finalName> + + <plugins> + <plugin> + <groupId>com.mycila</groupId> + <artifactId>license-maven-plugin</artifactId> + <configuration> + <excludes> + <excludes>**</excludes> + </excludes> + </configuration> + </plugin> + + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-checkstyle-plugin</artifactId> + <inherited>false</inherited> + <configuration> + <excludes>**</excludes> + </configuration> + </plugin> + + </plugins> + </build> + + + <dependencies> + <dependency> + <groupId>commons-codec</groupId> + <artifactId>commons-codec</artifactId> + <version>1.3</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>commons-httpclient</groupId> + <artifactId>commons-httpclient</artifactId> + <version>3.0-rc4</version> + </dependency> + <dependency> + <groupId>commons-logging</groupId> + <artifactId>commons-logging</artifactId> + <version>1.0.3</version> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpcore</artifactId> + <version>${httpclient.version}</version> + </dependency> + <!-- + <dependency> + <groupId>org.apache.ode</groupId> + <artifactId>ode-bpel-api</artifactId> + <version>1.3.5</version> + <scope>system</scope> + <systemPath>${project.basedir}/libs/ode-bpel-api-1.3.5-wso2v4.jar</systemPath> + </dependency> + <dependency> + <groupId>org.apache.ode</groupId> + <artifactId>ode-bpel-obj</artifactId> + <version>1.3.5</version> + <scope>system</scope> + <systemPath>${project.basedir}/libs/ode-bpel-obj-1.3.5-wso2v4.jar</systemPath> + </dependency> + <dependency> + <groupId>org.apache.ode</groupId> + <artifactId>ode-bpel-runtime</artifactId> + <version>1.3.5</version> + <scope>system</scope> + <systemPath>${project.basedir}/libs/ode-bpel-runtime-1.3.5-wso2v4.jar</systemPath> + </dependency> + --> + + <dependency> + <groupId>org.apache.ode</groupId> + <artifactId>ode-bpel-api</artifactId> + <version>1.3.5</version> + + <scope>system</scope> + <systemPath>${project.basedir}/libs/ode-bpel-api-1.3.5-wso2v4.jar</systemPath> + + </dependency> + <dependency> + <groupId>org.apache.ode</groupId> + <artifactId>ode-bpel-obj</artifactId> + <version>1.3.5</version> + + <scope>system</scope> + <systemPath>${project.basedir}/libs/ode-bpel-obj-1.3.5-wso2v4.jar</systemPath> + + </dependency> + <dependency> + <groupId>org.apache.ode</groupId> + <artifactId>ode-bpel-runtime</artifactId> + <version>1.3.5</version> + + <scope>system</scope> + <systemPath>${project.basedir}/libs/ode-bpel-runtime-1.3.5-wso2v4.jar</systemPath> + + </dependency> + + <dependency> + <groupId>com.googlecode.json-simple</groupId> + <artifactId>json-simple</artifactId> + <version>1.1.1</version> + </dependency> + </dependencies> +</project> diff --git a/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/Bpel4RestLightExtensionBundle.java b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/Bpel4RestLightExtensionBundle.java new file mode 100644 index 0000000..1423315 --- /dev/null +++ b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/Bpel4RestLightExtensionBundle.java @@ -0,0 +1,48 @@ +/** + * Copyright 2011 IAAS University of Stuttgart <br> + * <br> + * + * @author uwe.breitenbuecher@iaas.uni-stuttgart.de + * + */ +/** + * 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 de.unistuttgart.iaas.bpel.extensions.bpel4restlight; + +import org.apache.ode.bpel.runtime.extension.AbstractExtensionBundle; + + +public class Bpel4RestLightExtensionBundle extends AbstractExtensionBundle { + + public static final String NAMESPACE = "http://iaas.uni-stuttgart.de/bpel/extensions/bpel4restlight"; + + + /** {@inheritDoc} */ + @Override + public String getNamespaceURI() { + return NAMESPACE; + } + + /** {@inheritDoc} */ + @Override + public void registerExtensionActivities() { + super.registerExtensionOperation("logNodes", EPRDemoOperation.class); + super.registerExtensionOperation("PUT", Bpel4RestLightOperation.class); + super.registerExtensionOperation("GET", Bpel4RestLightOperation.class); + super.registerExtensionOperation("POST", Bpel4RestLightOperation.class); + super.registerExtensionOperation("DELETE", Bpel4RestLightOperation.class); + } +} diff --git a/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/Bpel4RestLightOperation.java b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/Bpel4RestLightOperation.java new file mode 100644 index 0000000..2335f49 --- /dev/null +++ b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/Bpel4RestLightOperation.java @@ -0,0 +1,147 @@ +package de.unistuttgart.iaas.bpel.extensions.bpel4restlight; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.Properties; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.ode.bpel.common.FaultException; +import org.apache.ode.bpel.runtime.extension.AbstractSyncExtensionOperation; +import org.apache.ode.bpel.runtime.extension.ExtensionContext; +import org.opentosca.bpel4restlight.rest.HighLevelRestApi; +import org.opentosca.bpel4restlight.rest.HttpMethod; +import org.opentosca.bpel4restlight.rest.HttpResponseMessage; +/** + * + * Copyright 2011 IAAS University of Stuttgart <br> + * <br> + * + * This class provides 4 BPEL4RestLight ExtensionActivity-operations which + * correspond to the 4 typical REST-Operations GET, PUT, POST and Delete. + * + * @author uwe.breitenbuecher@iaas.uni-stuttgart.de + * + */ +import org.w3c.dom.Element; + +import de.unistuttgart.iaas.bpel.extensions.bpel4restlight.util.Bpel4RestLightUtil; +import de.unistuttgart.iaas.bpel.util.BPELVariableInjectionUtil; +import de.unistuttgart.iaas.bpel.util.BpelUtil; + + +public class Bpel4RestLightOperation extends AbstractSyncExtensionOperation { + protected static final Log log = LogFactory.getLog(Bpel4RestLightOperation.class); + private static final String EXT_PROPERTIES = "wso2bps-ext.properties"; // extra properties setting + private static final String MSB_URL = "MSB_URL"; // http://msb:port, ext property msb url, if exist replace the request url + + + public static String wrapper = "temporary-simple-type-wrapper"; + private static String msbUrl = null; + + static { + + try { + File file = new File(EXT_PROPERTIES); + if(file.exists()) { + Properties p=new Properties(); + InputStream inputStream = new FileInputStream(file); + p.load(inputStream); + inputStream.close(); + msbUrl = p.getProperty(MSB_URL); + } + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + private void processResponseMessage(HttpResponseMessage responseMessage, ExtensionContext context, Element element) throws FaultException { + // Write responsePayload to designated variable + String responsePayloadVariableName = Bpel4RestLightUtil.getMethodAttributeValue(element, MethodAttribute.RESPONSEPAYLOADVARIABLE); + String statusCodeVariableName = Bpel4RestLightUtil.getMethodAttributeValue(element, MethodAttribute.STATUSCODEVARIABLE); + + if (responsePayloadVariableName != null && !responsePayloadVariableName.equals("")) { + BpelUtil.writeResponsePayloadToVariable(context, responseMessage.getResponseBody(), responsePayloadVariableName, Bpel4RestLightOperation.wrapper); + } + + if (statusCodeVariableName != null && !statusCodeVariableName.equals("")) { + String StatusCode = "" + responseMessage.getStatusCode(); // int can not be casted to String + + BpelUtil.writeResponsePayloadToVariable(context, StatusCode, statusCodeVariableName, Bpel4RestLightOperation.wrapper); + + } + } + + /** {@inheritDoc} */ + @Override + protected void runSync(ExtensionContext context, Element element) throws FaultException { + element = BPELVariableInjectionUtil.replaceExtensionVariables(context, element); + log.debug("LocalName of edited element: " + element.getLocalName()); + String httpMethod = element.getLocalName(); + + // Extract requestUri + String requestUri = getRequestUrl(element); + + HttpResponseMessage responseMessage = null; + String acceptHeader = Bpel4RestLightUtil.extractAcceptHeader(context, element); + String contentTypeHeader = Bpel4RestLightUtil.extractContentTypeHeader(context, element); + String requestPayload = Bpel4RestLightUtil.extractRequestPayload(context, element); + + // Execute corresponding HttpMethod via the HighLevelRestApi + switch (HttpMethod.valueOf(httpMethod)) { + + case PUT: { + responseMessage = HighLevelRestApi.Put(requestUri, requestPayload, acceptHeader, contentTypeHeader); + break; + } + + case POST: { + responseMessage = HighLevelRestApi.Post(requestUri, requestPayload, acceptHeader, contentTypeHeader); + break; + } + + case GET: { + responseMessage = HighLevelRestApi.Get(requestUri, acceptHeader, contentTypeHeader); + break; + } + + case DELETE: { + responseMessage = HighLevelRestApi.Delete(requestUri, acceptHeader, contentTypeHeader); + break; + } + } + + processResponseMessage(responseMessage, context, element); + // Bpel4RestLightOperation.wrapper = null; + } + + + /** + * getRequestUrl + * get request url from element, if exists msbUrl property, then replace the ip and port + * @param element + * @return + */ + private String getRequestUrl(Element element) { + String requestUri = Bpel4RestLightUtil.getMethodAttributeValue(element, MethodAttribute.REQUESTURI); + log.debug("original url:" + requestUri); + if(msbUrl == null || "".equals(msbUrl) || "http://msb:port".equals(msbUrl)) { + return requestUri; + } else { + requestUri = requestUri.substring(requestUri.indexOf("//") + 2); + int index = requestUri.indexOf("/"); + if(index == -1) { + + } else { + requestUri = requestUri.substring(index); + } + requestUri = msbUrl + requestUri; + log.debug("changed url:" + requestUri); + return requestUri; + } + } +} diff --git a/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/EPRDemoOperation.java b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/EPRDemoOperation.java new file mode 100644 index 0000000..fd7b4b3 --- /dev/null +++ b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/EPRDemoOperation.java @@ -0,0 +1,74 @@ +/** + * + * Copyright 2011 IAAS University of Stuttgart <br> + * <br> + * + * THIS CLASS IS USED FOR TEST PURPOSES! + * + * @author uwe.breitenbuecher@iaas.uni-stuttgart.de + * + */ +package de.unistuttgart.iaas.bpel.extensions.bpel4restlight; + +import java.net.HttpURLConnection; +import java.net.URL; + +import org.apache.ode.bpel.common.FaultException; +import org.apache.ode.bpel.o.OPartnerLink; +import org.apache.ode.bpel.runtime.PartnerLinkInstance; +import org.apache.ode.bpel.runtime.extension.AbstractSyncExtensionOperation; +import org.apache.ode.bpel.runtime.extension.ExtensionContext; +import org.w3c.dom.Element; + +import de.unistuttgart.iaas.xml.DomXmlConverter; + + +public class EPRDemoOperation extends AbstractSyncExtensionOperation { + + /** {@inheritDoc} */ + @Override + protected void runSync(ExtensionContext context, Element element) throws FaultException { + System.out.println("bin hier"); + try { + for (OPartnerLink l : context.getInternalInstance().getProcessModel().allPartnerLinks) { + + PartnerLinkInstance pli = context.getPartnerLinkInstance(l); + + Element epr = context.getInternalInstance().fetchPartnerRoleEndpointReferenceData(pli); + System.out.println("EPR|||"); + System.out.println(DomXmlConverter.nodeToString(epr, null)); + + System.out.println(epr.getChildNodes().item(0).getChildNodes().item(1).getNodeName()); + System.out.println(epr.getChildNodes().item(0).getChildNodes().item(1).getTextContent()); + System.out.println(".."); + System.out.println(epr.getChildNodes().item(0).getChildNodes().item(1).getChildNodes().item(0).getTextContent()); + + epr.getChildNodes().item(0).getChildNodes().item(1).getChildNodes().item(0).setTextContent("http://localhost:8084/FRP/rrr"); + + System.out.println(epr.getChildNodes().item(0).getChildNodes().item(1).getChildNodes().item(0).getTextContent()); + + System.out.println(context.getDUDir().toString()); + + } + + } catch (Exception e) { + e.printStackTrace(); + } + + System.out.println("ich bin hiiiiiiiiiier!!"); + + try { + URL url = new URL("http://localhost:8084/FRP/rrr"); + + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("PUT"); + + int responseCode = connection.getResponseCode(); + System.out.println(responseCode); + + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/MethodAttribute.java b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/MethodAttribute.java new file mode 100644 index 0000000..ce80c16 --- /dev/null +++ b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/MethodAttribute.java @@ -0,0 +1,17 @@ +/** + * + * Copyright 2011 IAAS University of Stuttgart <br> + * <br> + * + * This enum is used to decouple DOM-Attribute names from their + * String-representation within a certain library (for portability issues) + * + * @author uwe.breitenbuecher@iaas.uni-stuttgart.de + * + */ +package de.unistuttgart.iaas.bpel.extensions.bpel4restlight; + + +public enum MethodAttribute { + REQUESTURI, REQUESTPAYLOADVARIABLE, RESPONSEPAYLOADVARIABLE, STATUSCODEVARIABLE, ACCEPTHEADER, CONTENTTYPE; +}
\ No newline at end of file diff --git a/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/util/Bpel4RestLightUtil.java b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/util/Bpel4RestLightUtil.java new file mode 100644 index 0000000..1c9d7d1 --- /dev/null +++ b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/util/Bpel4RestLightUtil.java @@ -0,0 +1,113 @@ +/** + * Copyright 2011 IAAS University of Stuttgart <br> + * <br> + * + * @author uwe.breitenbuecher@iaas.uni-stuttgart.de + * + */ +package de.unistuttgart.iaas.bpel.extensions.bpel4restlight.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.ode.bpel.common.FaultException; +import org.apache.ode.bpel.runtime.extension.ExtensionContext; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +import de.unistuttgart.iaas.bpel.extensions.bpel4restlight.Bpel4RestLightOperation; +import de.unistuttgart.iaas.bpel.extensions.bpel4restlight.MethodAttribute; +import de.unistuttgart.iaas.xml.DomXmlConverter; + + +public class Bpel4RestLightUtil { + protected static final Log log = LogFactory.getLog(Bpel4RestLightUtil.class); + /** + * This function extracts the requestPayload specified in the passed + * element. This requestPayload is either the content contained in a special + * BPEL-Variable which is referenced by name by a special attribute of the + * passed element or the content contained in the first child node of the + * passed element + * + * @param context ExtensionContext + * @param element Element from which the requestPayload has to be extracted + * @return RequestPayload as String + * @throws FaultException + */ + public static String extractRequestPayload(ExtensionContext context, Element element) throws FaultException { + + String requestPayload = ""; + + String requestPayloadVariableName = getMethodAttributeValue(element, MethodAttribute.REQUESTPAYLOADVARIABLE); + + if (requestPayloadVariableName != null && requestPayloadVariableName != "") { + Node requestVariableNode = context.readVariable(requestPayloadVariableName); + if (requestVariableNode.getLocalName().equals("temporary-simple-type-wrapper")) { + Bpel4RestLightOperation.wrapper = "temporary-simple-type-wrapper"; + requestPayload = DomXmlConverter.nodeToString(requestVariableNode, "temporary-simple-type-wrapper"); + } else { + requestPayload = DomXmlConverter.nodeToString(requestVariableNode, null); + } + log.debug("The pure request variable as String: \n" + DomXmlConverter.nodeToString(requestVariableNode, null) + "\n"); + } + + return requestPayload; + } + + public static String extractAcceptHeader(ExtensionContext context, Element element) throws FaultException { + return getMethodAttributeValue(element, MethodAttribute.ACCEPTHEADER); + } + + public static String extractContentTypeHeader(ExtensionContext context, Element element) throws FaultException { + return getMethodAttributeValue(element, MethodAttribute.CONTENTTYPE); + } + + /** + * This function extracts special predefined attributes (see + * {@link MethodAttribute}) from a passed DOM-Element + * + * @param element Element containing the requested Attribute-Value + * @param methodAttribute Attribute whose content has to be returned + * @return Value / Content of the attribute + */ + public static String getMethodAttributeValue(Element element, MethodAttribute methodAttribute) { + + String result = ""; + + switch (methodAttribute) { + + case REQUESTURI: + result = element.getAttribute("uri"); + + if (result == null || "".equals(result)) { + result = element.getAttribute("requestUri"); + } + break; + case REQUESTPAYLOADVARIABLE: + result = element.getAttribute("request"); + + if (result == null || "".equals(result)) { + result = element.getAttribute("requestPayload"); + } + break; + case RESPONSEPAYLOADVARIABLE: + result = element.getAttribute("response"); + + if (result == null || "".equals(result)) { + result = element.getAttribute("responsePayload"); + } + break; + case STATUSCODEVARIABLE: + result = element.getAttribute("statusCode"); + break; + case ACCEPTHEADER: + result = element.getAttribute("accept"); + break; + case CONTENTTYPE: + result = element.getAttribute("contentType"); + break; + } + + return result; + } + +} diff --git a/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/util/BPELVariableInjectionUtil.java b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/util/BPELVariableInjectionUtil.java new file mode 100644 index 0000000..2298bf1 --- /dev/null +++ b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/util/BPELVariableInjectionUtil.java @@ -0,0 +1,149 @@ +/** + * Copyright 2011 + * + * @author Uwe Breitenbuecher + * + * This class provides some methods for BPEL-Variable-Injection + */ + package de.unistuttgart.iaas.bpel.util; + +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.apache.ode.bpel.common.FaultException; +import org.apache.ode.bpel.runtime.extension.ExtensionContext; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + + +public class BPELVariableInjectionUtil { + + /** + * This method serializes a Node into a String + * + * @param node + * @return String representation of the node + */ + public static String nodeToString(Node node) { + try { + + if (node != null && node.getLocalName().equals("temporary-simple-type-wrapper")) { + // this is a temporary hack for string variables and the likes, + // as you may see ODE wrappes simpletypes in wrapper-elements, + // but this isn't great here + return node.getTextContent(); + } + + // Create transformer + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + + // Transform Node into a String representation by regarding some + // formatting rules + StringWriter stringWriter = new StringWriter(); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3"); + transformer.transform(new DOMSource(node), new StreamResult(stringWriter)); + + // Return build string + return stringWriter.toString(); + } catch (Exception e) { + e.printStackTrace(); + } + + // If any error occurs, return empty string + return ""; + } + + /** + * This method executes the BPEL-Variable-Injection. It replaces referenced + * BPEL-Variables with corresponding content + * + * @param context ExtensionContext of process + * @param element DOM-Representation of the BPEL-Code in which the + * Variable-Injection has to be done + * @return modified BPEL-Code as DOM-Representation + */ + public static Element replaceExtensionVariables(ExtensionContext context, Element element) { + + try { + String BPELCodeAsString; + + // Transform BPEL-Code (DOM-Representation) into a String + BPELCodeAsString = nodeToString(element); + + // Find and replace referenced BPEL-Variables + int startIndex = BPELCodeAsString.indexOf("$bpelvar["); + if (startIndex != -1) { + while (startIndex != -1) { + int endIndex = startIndex; + while (BPELCodeAsString.charAt(endIndex) != ']') { + endIndex++; + } + + // Extract name of referenced variable + String variableName = BPELCodeAsString.substring(startIndex + 9, endIndex); + + // Extract content of referenced variable + Node variableContent = context.readVariable(variableName); + + System.out.println("Replacing variable " + variableName + "(" + variableContent.getNamespaceURI() + " " + variableContent.getLocalName() + ") with content: \n"); + System.out.println("NodeValue(): " + variableContent.getNodeValue() + "\n"); + System.out.println("TextContent(): " + variableContent.getTextContent()); + System.out.println("The full bpel script (before change) as string: \n" + BPELCodeAsString + "\n"); + + // Replace variable-reference with corresponding content + BPELCodeAsString = BPELCodeAsString.replace("$bpelvar[" + variableName + "]", nodeToString(variableContent)); + + System.out.println("The full bpel script as string: \n" + BPELCodeAsString + "\n"); + startIndex = BPELCodeAsString.indexOf("$bpelvar["); + } + + // Transform modified code (String) into DOM-Representation + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + DocumentBuilder builder = factory.newDocumentBuilder(); + + InputSource inputSource = new InputSource(); + inputSource.setCharacterStream(new StringReader(BPELCodeAsString)); + Document newDocument = builder.parse(inputSource); + + // Return first child (because Document root is not needed) + return (Element) newDocument.getFirstChild(); + + } else { + + // If no referenced variables are found, return original code + return element; + } + } catch (ParserConfigurationException e) { + e.printStackTrace(); + } catch (SAXException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (FaultException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return null; + } + +} diff --git a/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/util/BpelUtil.java b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/util/BpelUtil.java new file mode 100644 index 0000000..33c0d54 --- /dev/null +++ b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/util/BpelUtil.java @@ -0,0 +1,102 @@ +/** + * Copyright 2011 IAAS University of Stuttgart <br> + * <br> + * + * @author uwe.breitenbuecher@iaas.uni-stuttgart.de + * + */ +package de.unistuttgart.iaas.bpel.util; + +import java.io.IOException; +import java.io.StringReader; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.ode.bpel.common.FaultException; +import org.apache.ode.bpel.evar.ExternalVariableModuleException; +import org.apache.ode.bpel.o.OScope.Variable; +import org.apache.ode.bpel.runtime.extension.ExtensionContext; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + + +public class BpelUtil { + + /** + * This function writes a passed content to a specified processVariable + * (referenced by name). The content will be converted into its + * DOM-Representation for overwriting the processVariableContent (therefore + * it has to be XML-serializable, e.g. for complex data types there have to + * be JAX-B Annotations within the corresponding Class) + * + * @param context ExtensionContext needed to access the processVariable + * @param content New content for the specified processVariable + * @param processVariableName Variable whose content has to be overwritten + * @throws FaultException + */ + public static void writeContentToBPELVariable(ExtensionContext context, Object content, String processVariableName, String wrapper) throws FaultException { + // check the node + System.out.println("The content object: " + content + "\n"); + // small hack for test + Node hackNode = null; + System.out.println("Trying to parse string to dom: " + ((String) content) + "\n"); + + if (wrapper != null) { + // a hack for simple type wrapper + content = "<" + wrapper + ">" + (String) content + "</" + wrapper + ">"; + } + try { + hackNode = stringToDom((String) content); + } catch (ParserConfigurationException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (SAXException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + Variable bpelVariable = context.getVisibleVariables().get(processVariableName); + if (hackNode == null) { + System.out.println("hackNode is null! \n"); + } + if (bpelVariable == null) { + System.out.println("bpelVariable is null! \n"); + } + try { + // replaced responseAsNode to hackNode + context.writeVariable(bpelVariable, hackNode); + } catch (ExternalVariableModuleException e) { + e.printStackTrace(); + } + + } + + /** + * This function writes a String to a BPEL Variable of type XSD-String + * + * @param context ExtensionContext + * @param responsePayload ResponsePayload as String + * @param processVariableName Name of the target BPEL variable + * @throws FaultException + */ + public static void writeResponsePayloadToVariable(ExtensionContext context, Object responsePayload, String processVariableName, String wrapper) throws FaultException { + BpelUtil.writeContentToBPELVariable(context, responsePayload, processVariableName, wrapper); + } + + private static Node stringToDom(String xmlString) throws ParserConfigurationException, SAXException, IOException { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource is = new InputSource(new StringReader(xmlString)); + Document d = builder.parse(is); + return d.getFirstChild(); + } + +} diff --git a/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/xml/DomXmlConverter.java b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/xml/DomXmlConverter.java new file mode 100644 index 0000000..cbce6e8 --- /dev/null +++ b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/xml/DomXmlConverter.java @@ -0,0 +1,179 @@ +/** + * + * Copyright 2011 IAAS University of Stuttgart <br> + * <br> + * + * @author uwe.breitenbuecher@iaas.uni-stuttgart.de + * + */ +package de.unistuttgart.iaas.xml; + +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Marshaller; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + + +public class DomXmlConverter { + + // Single instance of transformer + private static Transformer xmlTransformer; + + + /** + * Converts a Node to its String-representation + * + * @param node Node which has to be converted + * @return String representation of the passed node + */ + public static String nodeToString(Node node, String wrapperElement) { + try { + System.out.println("\n\n\n"); + System.out.println("check if node got a namespace: " + node.getNamespaceURI()); + if (wrapperElement != null) { + // this hack is need as ODE wrapps simpletypes in such elements + return node.getTextContent(); + } + + Source source = new DOMSource(node); + + StringWriter writer = new StringWriter(); + Result result = new StreamResult(writer); + + Transformer transformer = DomXmlConverter.getTransformer(); + transformer.transform(source, result); + + return writer.toString(); + } catch (Exception e) { + e.printStackTrace(); + } + return "Parsing error"; + } + + /** + * Singleton implementation of transformer access + * + * @return Transformer + * @throws Exception + */ + private static synchronized Transformer getTransformer() throws Exception { + if (DomXmlConverter.xmlTransformer == null) { + DomXmlConverter.xmlTransformer = TransformerFactory.newInstance().newTransformer(); + DomXmlConverter.xmlTransformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + DomXmlConverter.xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); + DomXmlConverter.xmlTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); + } + return DomXmlConverter.xmlTransformer; + } + + /** + * This method converts a NodeList into a List of Strings. Each string + * represents the TextContent of each Node contained in the NodeList + * + * @param nodeList which contains the Nodes + * @return List of TextContents of each node + */ + public static List<String> convertNodeListToStringList(NodeList nodeList) { + List<String> resultList = new ArrayList<String>(); + + for (int i = 0; i < nodeList.getLength(); i++) { + resultList.add(nodeList.item(i).getTextContent()); + } + + return resultList; + } + + /** + * This method converts a NodeList into a List of Nodes + * + * @param nodeList + * @return List of Nodes + */ + public static List<Node> convertNodeListToList(NodeList nodeList) { + List<Node> resultList = new ArrayList<Node>(nodeList.getLength()); + for (int i = 0; i < nodeList.getLength(); i++) { + resultList.add(nodeList.item(i)); + } + return resultList; + } + + + /** + * Helper-Class for converting an Object into its DOM-Representation. The + * SerializingContainer is a Wrapper to enable the serialization of any + * object via JAXB. + */ + @XmlRootElement + private static class SerializingContainer { + + Object object; + + + public Object getObject() { + return this.object; + } + + public void setObject(Object object) { + this.object = object; + } + + } + + + /** + * This methods converts an Object into its DOM-Representation + * + * @param object which have to be converted + * @return DOM-Representation of the object + */ + public static Node convertObjectToDom(Object object) { + try { + + // Create new SerializingContainer and pack the object, which has to + // be serialized, into it. This has to be done, because JAXB + // only marshalls objects of classes annotated with the + // @XmlRootElement-Annotation. + SerializingContainer container = new SerializingContainer(); + container.setObject(object); + + // Create empty Document + Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); + + // Create JAXBContext and bind classes + Class<?>[] classesToBeBound = new Class[] {SerializingContainer.class, container.getObject().getClass()}; + JAXBContext jaxbContext = JAXBContext.newInstance(classesToBeBound, null); + + Marshaller marshaller = jaxbContext.createMarshaller(); + + // Set some properties + marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); + marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); + + // Marshall container into document. + marshaller.marshal(container, document); + + // Extract only the contained information in the serialized + // DOM-Representation of the SerializingContainer + return document.getFirstChild().getFirstChild(); + + } catch (Exception e) { + return null; + } + } + +} diff --git a/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/xml/XPathEvaluator.java b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/xml/XPathEvaluator.java new file mode 100644 index 0000000..0ae6b2c --- /dev/null +++ b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/xml/XPathEvaluator.java @@ -0,0 +1,34 @@ +/** + * + * Copyright 2011 IAAS University of Stuttgart <br> + * <br> + * + * @author uwe.breitenbuecher@iaas.uni-stuttgart.de + * + */ +package de.unistuttgart.iaas.xml; + +import javax.xml.namespace.QName; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathFactory; + + +public class XPathEvaluator { + + public static XPath xpath = XPathFactory.newInstance().newXPath(); + + + @SuppressWarnings("unchecked") + public static <t> t evaluate(String expression, Object source, QName returnType) { + + Object resultAsObject = null; + try { + resultAsObject = xpath.evaluate(expression, source, returnType); + + } catch (Exception e) { + e.printStackTrace(); + } + return (t) resultAsObject; + } + +} diff --git a/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/HighLevelRestApi.java b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/HighLevelRestApi.java new file mode 100644 index 0000000..74edbbc --- /dev/null +++ b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/HighLevelRestApi.java @@ -0,0 +1,167 @@ +/** + * This class wraps HTTP-Method functionality and thereby abstracts from low + * level code to simplify the usage. + */ +package org.opentosca.bpel4restlight.rest; + +import org.apache.commons.httpclient.HttpMethodBase; +import org.apache.commons.httpclient.NameValuePair; +import org.apache.commons.httpclient.methods.DeleteMethod; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.commons.httpclient.methods.PutMethod; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpHeaders; + + +public class HighLevelRestApi { + protected static final Log log = LogFactory.getLog(HighLevelRestApi.class); + /** + * This method implements the HTTP Put Method + * + * @param uri + * Resource URI + * @param requestPayload + * Content which has to be put into the Resource + * @return ResponseCode of HTTP Interaction + */ + @SuppressWarnings("deprecation") + public static HttpResponseMessage Put(String uri, String requestPayload, String acceptHeaderValue, String contentTypeHeader) { + + PutMethod method = new PutMethod(uri); + // requestPayload = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + + // requestPayload; + + HighLevelRestApi.setHeader(method, acceptHeaderValue, contentTypeHeader); + method.setRequestBody(requestPayload); + + HttpResponseMessage responseMessage = LowLevelRestApi.executeHttpMethod(method); + + // kill <?xml... in front of response + HighLevelRestApi.cleanResponseBody(responseMessage); + + return responseMessage; + } + + /** + * This method implements the HTTP Post Method + * + * @param uri + * Resource URI + * @param requestPayload + * Content which has to be posted into the Resource + * @return ResponseCode of HTTP Interaction + */ + @SuppressWarnings("deprecation") + public static HttpResponseMessage Post(String uri, String requestPayload, String acceptHeaderValue, String contentTypeHeader) { + + PostMethod method = null; + if (uri.contains("?")) { + log.debug("Found query trying to split"); + String[] split = uri.split("\\?"); + log.debug("Raw URI part: " + split[0]); + log.debug("Raw Query part: " + split[1]); + method = new PostMethod(split[0]); + method.setQueryString(HighLevelRestApi.createNameValuePairArrayFromQuery(split[1])); + } else { + method = new PostMethod(uri); + ; + } + method.setRequestBody(requestPayload); + HighLevelRestApi.setHeader(method, acceptHeaderValue, contentTypeHeader); + HttpResponseMessage responseMessage = LowLevelRestApi.executeHttpMethod(method); + HighLevelRestApi.cleanResponseBody(responseMessage); + return responseMessage; + } + + /** + * This method implements the HTTP Get Method + * + * @param uri + * Resource URI + * @return Content represented by the Resource URI + */ + public static HttpResponseMessage Get(String uri, String acceptHeaderValue, String contentTypeHeader) { + log.debug("Setting URI to: \n"); + log.debug(uri); + GetMethod method = null; + if (uri.contains("?")) { + log.debug("Found query trying to split"); + String[] split = uri.split("\\?"); + log.debug("Raw URI part: " + split[0]); + log.debug("Raw Query part: " + split[1]); + + method = new GetMethod(split[0]); + method.setQueryString(HighLevelRestApi.createNameValuePairArrayFromQuery(split[1])); + } else { + method = new GetMethod(uri); + } + HighLevelRestApi.setHeader(method, acceptHeaderValue, contentTypeHeader); + HttpResponseMessage responseMessage = LowLevelRestApi.executeHttpMethod(method); + HighLevelRestApi.cleanResponseBody(responseMessage); + return responseMessage; + } + + private static NameValuePair[] createNameValuePairArrayFromQuery(String query) { + // example: + // csarID=Moodle.csar&serviceTemplateID={http://www.example.com/tosca/ServiceTemplates/Moodle}Moodle&nodeTemplateID={http://www.example.com/tosca/ServiceTemplates/Moodle}VmApache + log.debug("Splitting query: " + query); + String[] pairs = query.trim().split("&"); + NameValuePair[] nameValuePairArray = new NameValuePair[pairs.length]; + int count = 0; + for (String pair : pairs) { + log.debug("Splitting query pair: " + pair); + String[] keyValue = pair.split("="); + NameValuePair nameValuePair = new NameValuePair(); + log.debug("Key: " + keyValue[0] + " Value: " + keyValue[1]); + nameValuePair.setName(keyValue[0]); + nameValuePair.setValue(keyValue[1]); + nameValuePairArray[count] = nameValuePair; + count++; + } + return nameValuePairArray; + } + + /** + * This method implements the HTTP Delete Method + * + * @param uri + * Resource URI + * @return ResponseCode of HTTP Interaction + */ + public static HttpResponseMessage Delete(String uri, String acceptHeaderValue, String contentTypeHeader) { + + DeleteMethod method = new DeleteMethod(uri); + HighLevelRestApi.setHeader(method, acceptHeaderValue, contentTypeHeader); + HttpResponseMessage responseMessage = LowLevelRestApi.executeHttpMethod(method); + HighLevelRestApi.cleanResponseBody(responseMessage); + return responseMessage; + } + + private static void setHeader(HttpMethodBase method, String accept, String contentType) { + if (!"".equals(accept)) { + method.setRequestHeader(HttpHeaders.ACCEPT, accept); + } else { + method.setRequestHeader(HttpHeaders.ACCEPT, "application/xml"); + } + + if (contentType != null && !"".equals(contentType)) { + method.setRequestHeader(HttpHeaders.CONTENT_TYPE, contentType); + } else { +// method.setRequestHeader("Accept", accept); + } + + } + + private static void cleanResponseBody(HttpResponseMessage responseMessage) { + log.debug("ResponseBody: \n"); + if (responseMessage != null && responseMessage.getResponseBody() != null) { + log.debug(responseMessage.getResponseBody()); + String temp = responseMessage.getResponseBody() + .replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>", ""); + responseMessage.setResponseBody(temp); + } + } + +} diff --git a/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/HttpMethod.java b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/HttpMethod.java new file mode 100644 index 0000000..ace91c9 --- /dev/null +++ b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/HttpMethod.java @@ -0,0 +1,9 @@ +/** + * This enum is intended to simplify identifying different HTTP-methods + */ +package org.opentosca.bpel4restlight.rest; + + +public enum HttpMethod { + PUT, POST, GET, DELETE +}
\ No newline at end of file diff --git a/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/HttpResponseMessage.java b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/HttpResponseMessage.java new file mode 100644 index 0000000..0836918 --- /dev/null +++ b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/HttpResponseMessage.java @@ -0,0 +1,42 @@ +/** + * This enum is intended to simplify identifying different HTTP-methods + */ +package org.opentosca.bpel4restlight.rest; + +/** + */ +public class HttpResponseMessage { + + private int statusCode; + private String responseBody; + + + /** + * @return the statusCode + */ + public int getStatusCode() { + return this.statusCode; + } + + /** + * @param statusCode the statusCode to set + */ + protected void setStatusCode(int statusCode) { + this.statusCode = statusCode; + } + + /** + * @return the responseBody + */ + public String getResponseBody() { + return this.responseBody; + } + + /** + * @param responseBody the responseBody to set + */ + protected void setResponseBody(String responseBody) { + this.responseBody = responseBody; + } + +} diff --git a/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/LowLevelRestApi.java b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/LowLevelRestApi.java new file mode 100644 index 0000000..2c6bc94 --- /dev/null +++ b/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/LowLevelRestApi.java @@ -0,0 +1,171 @@ +/** + * This static-class eases HTTP-method execution by self-managed fault-handling + * and automated Response-information processing + */ +package org.opentosca.bpel4restlight.rest; + +import java.io.IOException; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + + +public class LowLevelRestApi { + + protected static final Log log = LogFactory.getLog(LowLevelRestApi.class); + // Local HttpClient used for every communication (Singleton implementation) +// private static HttpClient httpClient = new HttpClient(); + + /** + * Executes a passed HttpMethod (Method type is either PUT, POST, GET or + * DELETE) and returns a HttpResponseMessage + * + * @param method Method to execute + * @return HttpResponseMessage which contains all information about the + * execution + */ + public static HttpResponseMessage executeHttpMethod(HttpMethod method) { + + HttpResponseMessage responseMessage = null; + + try { + log.debug("Method invocation on URI: \n"); + log.debug(method.getURI().toString()); + + // Execute Request + HttpClient httpClient = new HttpClient(); + httpClient.executeMethod(method); + responseMessage = LowLevelRestApi.extractResponseInformation(method); + + } catch (Exception e) { + log.error("call rest error:", e); + } finally { + // Release Connection anyway + method.releaseConnection(); + } + + // Extract response information and return + return responseMessage; + } + + /** + * Extracts the response information from an executed HttpMethod + * + * @param method Executed Method + * @return Packaged response information + */ + private static HttpResponseMessage extractResponseInformation(HttpMethod method) { + // Create and return HttpResponseMethod + HttpResponseMessage responseMessage = new HttpResponseMessage(); + responseMessage.setStatusCode(method.getStatusCode()); + try { + responseMessage.setResponseBody(getResponseBody(method)); + } catch (Exception e) { + log.error(e); + } + return responseMessage; + + } + + /** + * getResponseBody + * + * get response body info, if response body is a json object, then translate json object to xml + * if the rest request failed, i.e. the response body is a 404 error page, then response the body with header <root> + * @param method + * @return + * @throws ParseException + */ + private static String getResponseBody(HttpMethod method) throws ParseException + { + String result = null; + try { + result = method.getResponseBodyAsString(); + log.debug("result:"); + log.debug(result); + } catch (IOException e) { + log.error(e); + } + + Header header = method.getRequestHeader("Accept"); + if ("application/json".equals(header.getValue())) { + StringBuilder sb = new StringBuilder(); + sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"); + sb.append("<root>"); + if(result != null && !"".equals(result)) { + /** + if(result.startsWith("<html>")) { + sb.append("<![CDATA["); + sb.append(result); + sb.append("]]>"); + } else { + Object json = new JSONParser().parse(result); + json2Xml(sb, "obj", json); + } + */ + + try { + Object json = new JSONParser().parse(result); + json2Xml(sb, "obj", json); + } catch (Exception e) { + log.error(e); + sb.append("<![CDATA["); + sb.append(result); + sb.append("]]>"); + } + } + sb.append("</root>"); + + log.debug("responseBody:"); + log.debug(sb.toString()); + return sb.toString(); + } + return result; + } + + + @SuppressWarnings("unchecked") + public static void json2Xml(StringBuilder sb, String key, Object jsonObject) { + if(jsonObject == null) { + sb.append("<error>empty</error>"); + return; + } + + if(jsonObject instanceof JSONArray) { + JSONArray array = (JSONArray) jsonObject; + sb.append("<").append(key).append("s").append(">"); + for(int i=0, len=array.size(); i<len; i++) { + json2Xml(sb, key, array.get(i)); + } + sb.append("</").append(key).append("s").append(">"); + + return; + } else if(jsonObject instanceof JSONObject) { + sb.append("<").append(key).append(">"); + JSONObject json = (JSONObject) jsonObject; + for(Map.Entry<String, Object> entry : (Set<Map.Entry<String, Object>>)json.entrySet()) { + json2Xml(sb, entry.getKey(), entry.getValue()); + } + sb.append("</").append(key).append(">"); + return; + } else { + sb.append("<").append(key).append(">"); + sb.append("<![CDATA["); + sb.append(jsonObject.toString()); + sb.append("]]>"); + sb.append("</").append(key).append(">"); + + return; + } + } + +} |