use of com.twinsoft.convertigo.beans.transactions.AbstractHttpTransaction in project convertigo by convertigo.
the class OpenApiUtils method createRestConnector.
public static HttpConnector createRestConnector(OpenAPI openApi) throws Exception {
try {
HttpConnector httpConnector = new HttpConnector();
httpConnector.bNew = true;
Info info = openApi.getInfo();
String title = info != null ? info.getTitle() : "";
title = title == null || title.isEmpty() ? "RestConnector" : title;
String description = info != null ? info.getDescription() : "";
description = description == null || description.isEmpty() ? "" : description;
httpConnector.setName(StringUtils.normalize(title));
httpConnector.setComment(description);
String httpUrl = "";
List<Server> servers = openApi.getServers();
if (servers.size() > 0) {
httpUrl = servers.get(0).getUrl();
}
httpUrl = httpUrl.isEmpty() ? getConvertigoServeurUrl() : httpUrl;
UrlFields urlFields = UrlParser.parse(httpUrl);
if (urlFields != null) {
String scheme = urlFields.getScheme();
String host = urlFields.getHost();
String port = urlFields.getPort();
String basePath = urlFields.getPath();
boolean isHttps = "https".equals(scheme);
httpConnector.setHttps(isHttps);
httpConnector.setServer(host);
httpConnector.setPort(port == null ? (isHttps ? 443 : 80) : Integer.valueOf(port));
httpConnector.setBaseDir(basePath);
}
httpConnector.setBaseUrl(httpUrl);
List<SecurityRequirement> securityRequirements = openApi.getSecurity();
if (securityRequirements != null && securityRequirements.size() > 0) {
Map<String, SecurityScheme> securitySchemes = openApi.getComponents().getSecuritySchemes();
for (SecurityRequirement sr : securityRequirements) {
for (String s_name : sr.keySet()) {
SecurityScheme securityScheme = securitySchemes.get(s_name);
if (securityScheme != null) {
String scheme = securityScheme.getScheme() == null ? "" : securityScheme.getScheme();
boolean isBasicScheme = scheme.toLowerCase().equals("basic");
boolean isHttpType = securityScheme.getType().equals(SecurityScheme.Type.HTTP);
if (isHttpType && isBasicScheme) {
httpConnector.setAuthenticationType(AuthenticationMode.Basic);
break;
}
}
}
}
}
Paths paths = openApi.getPaths();
if (paths != null) {
AbstractHttpTransaction defTransaction = null;
for (Entry<String, PathItem> entry : paths.entrySet()) {
HttpMethodType httpMethodType = null;
Operation operation = null;
String customHttpVerb = "";
String subDir = entry.getKey();
PathItem pathItem = entry.getValue();
Map<HttpMethod, Operation> operationMap = pathItem.readOperationsMap();
for (HttpMethod httpMethod : operationMap.keySet()) {
operation = operationMap.get(httpMethod);
if (httpMethod.equals(HttpMethod.GET)) {
httpMethodType = HttpMethodType.GET;
} else if (httpMethod.equals(HttpMethod.POST)) {
httpMethodType = HttpMethodType.POST;
} else if (httpMethod.equals(HttpMethod.PUT)) {
httpMethodType = HttpMethodType.PUT;
} else if (httpMethod.equals(HttpMethod.PATCH)) {
httpMethodType = HttpMethodType.PUT;
customHttpVerb = "PATCH";
} else if (httpMethod.equals(HttpMethod.DELETE)) {
httpMethodType = HttpMethodType.DELETE;
} else if (httpMethod.equals(HttpMethod.HEAD)) {
httpMethodType = HttpMethodType.HEAD;
} else if (httpMethod.equals(HttpMethod.TRACE)) {
httpMethodType = HttpMethodType.TRACE;
} else if (httpMethod.equals(HttpMethod.OPTIONS)) {
httpMethodType = HttpMethodType.OPTIONS;
} else {
httpMethodType = null;
}
if (operation != null && httpMethodType != null) {
String operationId = operation.getOperationId();
String operationDesc = operation.getDescription();
String summary = operation.getSummary();
String name = StringUtils.normalize(subDir + ":" + (customHttpVerb.isEmpty() ? httpMethodType.toString() : customHttpVerb));
if (name.isEmpty()) {
name = StringUtils.normalize(operationId);
if (name.isEmpty()) {
name = StringUtils.normalize(summary);
if (name.isEmpty()) {
name = "operation";
}
}
}
String comment = org.apache.commons.lang3.StringUtils.isNotBlank(summary) && !"null".equals(summary) ? summary : (org.apache.commons.lang3.StringUtils.isNotBlank(operationDesc) && !"null".equals(operationDesc) ? operationDesc : "");
XMLVector<XMLVector<String>> httpParameters = new XMLVector<XMLVector<String>>();
AbstractHttpTransaction transaction = new HttpTransaction();
String h_ContentType = MimeType.WwwForm.value();
/*if (consumeList != null) {
if (consumeList.contains(MimeType.Json.value())) {
h_ContentType = MimeType.Json.value();
}
else if (consumeList.contains(MimeType.Xml.value())) {
h_ContentType = MimeType.Xml.value();
}
else {
h_ContentType = consumeList.size() > 0 ?
consumeList.get(0) : MimeType.WwwForm.value();
}
}*/
String h_Accept = MimeType.Json.value();
if (h_Accept != null) {
XMLVector<String> xmlv = new XMLVector<String>();
xmlv.add("Accept");
xmlv.add(h_Accept);
httpParameters.add(xmlv);
if (h_Accept.equals(MimeType.Xml.value())) {
transaction = new XmlHttpTransaction();
((XmlHttpTransaction) transaction).setXmlEncoding("UTF-8");
} else if (h_Accept.equals(MimeType.Json.value())) {
transaction = new JsonHttpTransaction();
((JsonHttpTransaction) transaction).setIncludeDataType(false);
}
}
// Add variables
boolean hasBodyVariable = false;
RequestBody body = operation.getRequestBody();
if (body != null) {
Map<String, MediaType> medias = body.getContent();
for (String contentType : medias.keySet()) {
MediaType mediaType = medias.get(contentType);
Schema<?> mediaSchema = mediaType.getSchema();
List<String> requiredList = mediaSchema.getRequired();
if (contentType.equals("application/x-www-form-urlencoded")) {
@SuppressWarnings("rawtypes") Map<String, Schema> properties = mediaSchema.getProperties();
if (properties != null) {
for (String p_name : properties.keySet()) {
Schema<?> schema = properties.get(p_name);
String p_description = schema.getDescription();
boolean p_required = requiredList == null ? false : requiredList.contains(p_name);
boolean isMultiValued = false;
if (schema instanceof ArraySchema) {
isMultiValued = true;
}
RequestableHttpVariable httpVariable = isMultiValued ? new RequestableHttpMultiValuedVariable() : new RequestableHttpVariable();
httpVariable.bNew = true;
httpVariable.setHttpMethod(HttpMethodType.POST.name());
httpVariable.setName(p_name);
httpVariable.setDescription(p_name);
httpVariable.setHttpName(p_name);
httpVariable.setRequired(p_required);
httpVariable.setComment(p_description == null ? "" : p_description);
if (schema instanceof FileSchema) {
httpVariable.setDoFileUploadMode(DoFileUploadMode.multipartFormData);
}
Object defaultValue = schema.getDefault();
if (defaultValue == null && p_required) {
defaultValue = "";
}
httpVariable.setValueOrNull(defaultValue);
transaction.addVariable(httpVariable);
}
}
} else if (!hasBodyVariable) {
RequestableHttpVariable httpVariable = new RequestableHttpVariable();
httpVariable.bNew = true;
httpVariable.setHttpMethod(HttpMethodType.POST.name());
httpVariable.setRequired(true);
// overrides variable's name for internal use
httpVariable.setName(com.twinsoft.convertigo.engine.enums.Parameter.HttpBody.getName());
Object defaultValue = null;
httpVariable.setValueOrNull(defaultValue);
transaction.addVariable(httpVariable);
h_ContentType = contentType;
hasBodyVariable = true;
}
}
}
List<Parameter> parameters = operation.getParameters();
if (parameters != null) {
for (Parameter parameter : parameters) {
String p_name = parameter.getName();
String p_description = parameter.getDescription();
boolean p_required = parameter.getRequired();
boolean isMultiValued = false;
Schema<?> schema = parameter.getSchema();
if (schema instanceof ArraySchema) {
isMultiValued = true;
}
RequestableHttpVariable httpVariable = isMultiValued ? new RequestableHttpMultiValuedVariable() : new RequestableHttpVariable();
httpVariable.bNew = true;
httpVariable.setName(p_name);
httpVariable.setDescription(p_name);
httpVariable.setHttpName(p_name);
httpVariable.setRequired(p_required);
httpVariable.setComment(p_description == null ? "" : p_description);
if (parameter instanceof QueryParameter || parameter instanceof PathParameter || parameter instanceof HeaderParameter) {
httpVariable.setHttpMethod(HttpMethodType.GET.name());
if (parameter instanceof HeaderParameter) {
// overrides variable's name : will be treated as dynamic header
httpVariable.setName(com.twinsoft.convertigo.engine.enums.Parameter.HttpHeader.getName() + p_name);
// do not post on target server
httpVariable.setHttpName("");
}
if (parameter instanceof PathParameter) {
// do not post on target server
httpVariable.setHttpName("");
}
} else {
httpVariable.setHttpMethod("");
}
Object defaultValue = schema.getDefault();
if (defaultValue == null && p_required) {
defaultValue = "";
}
httpVariable.setValueOrNull(defaultValue);
transaction.addVariable(httpVariable);
}
}
// Set Content-Type
if (h_ContentType != null) {
XMLVector<String> xmlv = new XMLVector<String>();
xmlv.add(HeaderName.ContentType.value());
xmlv.add(hasBodyVariable ? h_ContentType : MimeType.WwwForm.value());
httpParameters.add(xmlv);
}
transaction.bNew = true;
transaction.setName(name);
transaction.setComment(comment);
transaction.setSubDir(subDir);
transaction.setHttpVerb(httpMethodType);
transaction.setCustomHttpVerb(customHttpVerb);
transaction.setHttpParameters(httpParameters);
transaction.setHttpInfo(true);
httpConnector.add(transaction);
if (defTransaction == null) {
defTransaction = transaction;
httpConnector.setDefaultTransaction(defTransaction);
}
}
}
}
}
return httpConnector;
} catch (Throwable t) {
Engine.logEngine.error("Unable to create connector", t);
throw new Exception("Unable to create connector", t);
}
}
use of com.twinsoft.convertigo.beans.transactions.AbstractHttpTransaction in project convertigo by convertigo.
the class SwaggerUtils method createRestConnector.
public static HttpConnector createRestConnector(Swagger swagger) throws Exception {
try {
HttpConnector httpConnector = new HttpConnector();
httpConnector.bNew = true;
Info info = swagger.getInfo();
String title = info != null ? info.getTitle() : "";
title = title == null || title.isEmpty() ? "RestConnector" : title;
httpConnector.setName(StringUtils.normalize(title));
boolean isHttps = false;
for (Scheme scheme : swagger.getSchemes()) {
if (scheme.equals(Scheme.HTTPS)) {
isHttps = true;
}
}
String host = swagger.getHost();
int index = host.indexOf(":");
String server = index == -1 ? host : host.substring(0, index);
int port = index == -1 ? 0 : Integer.parseInt(host.substring(index + 1), 10);
httpConnector.setHttps(isHttps);
httpConnector.setServer(server);
httpConnector.setPort(port <= 0 ? (isHttps ? 443 : 80) : port);
String basePath = swagger.getBasePath();
httpConnector.setBaseDir(basePath);
Map<String, SecuritySchemeDefinition> securityMap = swagger.getSecurityDefinitions();
if (securityMap != null && securityMap.size() > 0) {
for (String securityName : securityMap.keySet()) {
SecuritySchemeDefinition securityScheme = securityMap.get(securityName);
if (securityScheme != null) {
boolean isBasicScheme = securityScheme.getType().toLowerCase().equals("basic");
if (isBasicScheme) {
httpConnector.setAuthenticationType(AuthenticationMode.Basic);
break;
}
}
}
}
List<String> _consumeList = swagger.getConsumes();
List<String> _produceList = swagger.getProduces();
// Map<String, Model> models = swagger.getDefinitions();
Map<String, Path> paths = swagger.getPaths();
for (String subDir : paths.keySet()) {
Path path = paths.get(subDir);
// Add transactions
List<Operation> operations = path.getOperations();
for (Operation operation : operations) {
HttpMethodType httpMethodType = null;
if (operation.equals(path.getGet())) {
httpMethodType = HttpMethodType.GET;
} else if (operation.equals(path.getPost())) {
httpMethodType = HttpMethodType.POST;
} else if (operation.equals(path.getPut())) {
httpMethodType = HttpMethodType.PUT;
} else if (operation.equals(path.getDelete())) {
httpMethodType = HttpMethodType.DELETE;
} else if (operation.equals(path.getHead())) {
httpMethodType = HttpMethodType.HEAD;
} else if (operation.equals(path.getOptions())) {
httpMethodType = HttpMethodType.OPTIONS;
} else {
httpMethodType = null;
}
if (httpMethodType != null) {
List<String> consumeList = operation.getConsumes();
consumeList = consumeList == null || consumeList.isEmpty() ? _consumeList : consumeList;
List<String> produceList = operation.getProduces();
produceList = produceList == null || produceList.isEmpty() ? _produceList : produceList;
String operationId = operation.getOperationId();
String description = operation.getDescription();
String summary = operation.getSummary();
String name = StringUtils.normalize(subDir + ":" + httpMethodType.toString());
if (name.isEmpty()) {
name = StringUtils.normalize(operationId);
if (name.isEmpty()) {
name = StringUtils.normalize(summary);
if (name.isEmpty()) {
name = "operation";
}
}
}
String comment = summary;
if (comment == null)
comment = "";
if (comment.isEmpty()) {
comment = description;
}
XMLVector<XMLVector<String>> httpParameters = new XMLVector<XMLVector<String>>();
AbstractHttpTransaction transaction = new HttpTransaction();
String h_ContentType = MimeType.WwwForm.value();
if (consumeList != null) {
if (consumeList.contains(MimeType.Json.value())) {
h_ContentType = MimeType.Json.value();
} else if (consumeList.contains(MimeType.Xml.value())) {
h_ContentType = MimeType.Xml.value();
} else {
h_ContentType = consumeList.size() > 0 ? consumeList.get(0) : MimeType.WwwForm.value();
}
}
String h_Accept = MimeType.Json.value();
if (produceList != null) {
if (produceList.contains(h_ContentType)) {
h_Accept = h_ContentType;
} else {
if (produceList.contains(MimeType.Json.value())) {
h_Accept = MimeType.Json.value();
} else if (produceList.contains(MimeType.Xml.value())) {
h_Accept = MimeType.Xml.value();
}
}
if (consumeList == null && h_Accept != null) {
h_ContentType = h_Accept;
}
}
if (h_Accept != null) {
XMLVector<String> xmlv = new XMLVector<String>();
xmlv.add("Accept");
xmlv.add(h_Accept);
httpParameters.add(xmlv);
if (h_Accept.equals(MimeType.Xml.value())) {
transaction = new XmlHttpTransaction();
((XmlHttpTransaction) transaction).setXmlEncoding("UTF-8");
} else if (h_Accept.equals(MimeType.Json.value())) {
transaction = new JsonHttpTransaction();
((JsonHttpTransaction) transaction).setIncludeDataType(false);
}
}
// Add variables
boolean hasBodyVariable = false;
List<io.swagger.models.parameters.Parameter> parameters = operation.getParameters();
for (io.swagger.models.parameters.Parameter parameter : parameters) {
// String p_access = parameter.getAccess();
String p_description = parameter.getDescription();
// String p_in = parameter.getIn();
String p_name = parameter.getName();
// String p_pattern = parameter.getPattern();
boolean p_required = parameter.getRequired();
// Map<String,Object> p_extensions = parameter.getVendorExtensions();
boolean isMultiValued = false;
if (parameter instanceof SerializableParameter) {
SerializableParameter serializable = (SerializableParameter) parameter;
if (serializable.getType().equalsIgnoreCase("array")) {
if (serializable.getCollectionFormat().equalsIgnoreCase("multi")) {
isMultiValued = true;
}
}
}
RequestableHttpVariable httpVariable = isMultiValued ? new RequestableHttpMultiValuedVariable() : new RequestableHttpVariable();
httpVariable.bNew = true;
httpVariable.setName(p_name);
httpVariable.setHttpName(p_name);
httpVariable.setRequired(p_required);
if (parameter instanceof QueryParameter || parameter instanceof PathParameter || parameter instanceof HeaderParameter) {
httpVariable.setHttpMethod(HttpMethodType.GET.name());
if (parameter instanceof HeaderParameter) {
// overrides variable's name : will be treated as dynamic header
httpVariable.setName(com.twinsoft.convertigo.engine.enums.Parameter.HttpHeader.getName() + p_name);
// do not post on target server
httpVariable.setHttpName("");
}
if (parameter instanceof PathParameter) {
// do not post on target server
httpVariable.setHttpName("");
}
} else if (parameter instanceof FormParameter || parameter instanceof BodyParameter) {
httpVariable.setHttpMethod(HttpMethodType.POST.name());
if (parameter instanceof FormParameter) {
FormParameter formParameter = (FormParameter) parameter;
if (formParameter.getType().equalsIgnoreCase("file")) {
httpVariable.setDoFileUploadMode(DoFileUploadMode.multipartFormData);
}
} else if (parameter instanceof BodyParameter) {
hasBodyVariable = true;
// overrides variable's name for internal use
httpVariable.setName(com.twinsoft.convertigo.engine.enums.Parameter.HttpBody.getName());
// add internal __contentType variable
/*RequestableHttpVariable ct = new RequestableHttpVariable();
ct.setName(Parameter.HttpContentType.getName());
ct.setHttpMethod(HttpMethodType.POST.name());
ct.setValueOrNull(null);
ct.bNew = true;
transaction.addVariable(ct);*/
BodyParameter bodyParameter = (BodyParameter) parameter;
Model model = bodyParameter.getSchema();
if (model != null) {
}
}
} else {
httpVariable.setHttpMethod("");
}
Object defaultValue = null;
if (parameter instanceof AbstractSerializableParameter<?>) {
defaultValue = ((AbstractSerializableParameter<?>) parameter).getDefaultValue();
}
if (defaultValue == null && parameter instanceof SerializableParameter) {
SerializableParameter serializable = (SerializableParameter) parameter;
if (serializable.getType().equalsIgnoreCase("array")) {
Property items = serializable.getItems();
try {
Class<?> c = items.getClass();
defaultValue = c.getMethod("getDefault").invoke(items);
} catch (Exception e) {
}
}
}
if (defaultValue == null && p_required) {
defaultValue = "";
}
httpVariable.setValueOrNull(defaultValue);
if (p_description != null) {
httpVariable.setDescription(p_description);
httpVariable.setComment(p_description);
}
transaction.addVariable(httpVariable);
}
// Set Content-Type
if (h_ContentType != null) {
XMLVector<String> xmlv = new XMLVector<String>();
xmlv.add(HeaderName.ContentType.value());
xmlv.add(hasBodyVariable ? h_ContentType : MimeType.WwwForm.value());
httpParameters.add(xmlv);
}
transaction.bNew = true;
transaction.setName(name);
transaction.setComment(comment);
transaction.setSubDir(subDir);
transaction.setHttpVerb(httpMethodType);
transaction.setHttpParameters(httpParameters);
transaction.setHttpInfo(true);
httpConnector.add(transaction);
}
}
}
return httpConnector;
} catch (Throwable t) {
Engine.logEngine.error("Unable to create connector", t);
throw new Exception("Unable to create connector", t);
}
}
use of com.twinsoft.convertigo.beans.transactions.AbstractHttpTransaction in project convertigo by convertigo.
the class HttpConnector method getData.
public byte[] getData(Context context, String sUrl) throws IOException, EngineException {
HttpMethod method = null;
try {
// Fire event for plugins
long t0 = System.currentTimeMillis();
Engine.theApp.pluginsManager.fireHttpConnectorGetDataStart(context);
Engine.logBeans.trace("(HttpConnector) Retrieving data as a bytes array...");
Engine.logBeans.debug("(HttpConnector) Connecting to: " + sUrl);
// Setting the referer
referer = sUrl;
Engine.logBeans.debug("(HttpConnector) Https: " + https);
URL url = new URL(sUrl);
String host = url.getHost();
int port = url.getPort();
if (sUrl.toLowerCase().startsWith("https:")) {
if (!https) {
Engine.logBeans.debug("(HttpConnector) Setting up SSL properties");
certificateManager.collectStoreInformation(context);
}
if (port == -1)
port = 443;
Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port);
Engine.logBeans.debug("(HttpConnector) CertificateManager has changed: " + certificateManager.hasChanged);
if (certificateManager.hasChanged || (!host.equalsIgnoreCase(hostConfiguration.getHost())) || (hostConfiguration.getPort() != port)) {
Engine.logBeans.debug("(HttpConnector) Using MySSLSocketFactory for creating the SSL socket");
Protocol myhttps = new Protocol("https", MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore, certificateManager.keyStorePassword, certificateManager.trustStore, certificateManager.trustStorePassword, this.trustAllServerCertificates), port);
hostConfiguration.setHost(host, port, myhttps);
}
sUrl = url.getFile();
Engine.logBeans.debug("(HttpConnector) Updated URL for SSL purposes: " + sUrl);
} else {
Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port);
hostConfiguration.setHost(host, port);
}
// Retrieving httpState
getHttpState(context);
// Proxy configuration
Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url);
AbstractHttpTransaction httpTransaction = (AbstractHttpTransaction) context.transaction;
// Retrieve HTTP method
HttpMethodType httpVerb = httpTransaction.getHttpVerb();
String sHttpVerb = httpVerb.name();
final String sCustomHttpVerb = httpTransaction.getCustomHttpVerb();
if (sCustomHttpVerb.length() > 0) {
Engine.logBeans.debug("(HttpConnector) HTTP verb: " + sHttpVerb + " overridden to '" + sCustomHttpVerb + "'");
switch(httpVerb) {
case GET:
method = new GetMethod(sUrl) {
@Override
public String getName() {
return sCustomHttpVerb;
}
};
break;
case POST:
method = new PostMethod(sUrl) {
@Override
public String getName() {
return sCustomHttpVerb;
}
};
break;
case PUT:
method = new PutMethod(sUrl) {
@Override
public String getName() {
return sCustomHttpVerb;
}
};
break;
case DELETE:
method = new DeleteMethod(sUrl) {
@Override
public String getName() {
return sCustomHttpVerb;
}
};
break;
case HEAD:
method = new HeadMethod(sUrl) {
@Override
public String getName() {
return sCustomHttpVerb;
}
};
break;
case OPTIONS:
method = new OptionsMethod(sUrl) {
@Override
public String getName() {
return sCustomHttpVerb;
}
};
break;
case TRACE:
method = new TraceMethod(sUrl) {
@Override
public String getName() {
return sCustomHttpVerb;
}
};
break;
}
} else {
Engine.logBeans.debug("(HttpConnector) HTTP verb: " + sHttpVerb);
switch(httpVerb) {
case GET:
method = new GetMethod(sUrl);
break;
case POST:
method = new PostMethod(sUrl);
break;
case PUT:
method = new PutMethod(sUrl);
break;
case DELETE:
method = new DeleteMethod(sUrl);
break;
case HEAD:
method = new HeadMethod(sUrl);
break;
case OPTIONS:
method = new OptionsMethod(sUrl);
break;
case TRACE:
method = new TraceMethod(sUrl);
break;
}
}
// Setting HTTP parameters
boolean hasUserAgent = false;
for (List<String> httpParameter : httpParameters) {
String key = httpParameter.get(0);
String value = httpParameter.get(1);
if (key.equalsIgnoreCase("host") && !value.equals(host)) {
value = host;
}
if (!key.startsWith(DYNAMIC_HEADER_PREFIX)) {
method.setRequestHeader(key, value);
}
if (HeaderName.UserAgent.is(key)) {
hasUserAgent = true;
}
}
// set user-agent header if not found
if (!hasUserAgent) {
HeaderName.UserAgent.setRequestHeader(method, getUserAgent(context));
}
// Setting POST or PUT parameters if any
Engine.logBeans.debug("(HttpConnector) Setting " + httpVerb + " data");
if (method instanceof EntityEnclosingMethod) {
EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) method;
AbstractHttpTransaction transaction = (AbstractHttpTransaction) context.requestedObject;
if (doMultipartFormData) {
RequestableHttpVariable body = (RequestableHttpVariable) httpTransaction.getVariable(Parameter.HttpBody.getName());
if (body != null && body.getDoFileUploadMode() == DoFileUploadMode.multipartFormData) {
String stringValue = httpTransaction.getParameterStringValue(Parameter.HttpBody.getName());
String filepath = Engine.theApp.filePropertyManager.getFilepathFromProperty(stringValue, getProject().getName());
File file = new File(filepath);
if (file.exists()) {
HeaderName.ContentType.setRequestHeader(method, contentType);
entityEnclosingMethod.setRequestEntity(new FileRequestEntity(file, contentType));
} else {
throw new FileNotFoundException(file.getAbsolutePath());
}
} else {
List<Part> parts = new LinkedList<Part>();
for (RequestableVariable variable : transaction.getVariablesList()) {
if (variable instanceof RequestableHttpVariable) {
RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable;
if ("POST".equals(httpVariable.getHttpMethod())) {
Object httpObjectVariableValue = transaction.getVariableValue(httpVariable.getName());
if (httpVariable.isMultiValued()) {
if (httpObjectVariableValue instanceof Collection<?>) {
for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) {
addFormDataPart(parts, httpVariable, httpVariableValue);
}
}
} else {
addFormDataPart(parts, httpVariable, httpObjectVariableValue);
}
}
}
}
MultipartRequestEntity mre = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), entityEnclosingMethod.getParams());
HeaderName.ContentType.setRequestHeader(method, mre.getContentType());
entityEnclosingMethod.setRequestEntity(mre);
}
} else if (MimeType.TextXml.is(contentType)) {
final MimeMultipart[] mp = { null };
for (RequestableVariable variable : transaction.getVariablesList()) {
if (variable instanceof RequestableHttpVariable) {
RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable;
if (httpVariable.getDoFileUploadMode() == DoFileUploadMode.MTOM) {
Engine.logBeans.trace("(HttpConnector) Variable " + httpVariable.getName() + " detected as MTOM");
MimeMultipart mimeMultipart = mp[0];
try {
if (mimeMultipart == null) {
Engine.logBeans.debug("(HttpConnector) Preparing the MTOM request");
mimeMultipart = new MimeMultipart("related; type=\"application/xop+xml\"");
MimeBodyPart bp = new MimeBodyPart();
bp.setText(postQuery, "UTF-8");
bp.setHeader(HeaderName.ContentType.value(), contentType);
mimeMultipart.addBodyPart(bp);
}
Object httpObjectVariableValue = transaction.getVariableValue(httpVariable.getName());
if (httpVariable.isMultiValued()) {
if (httpObjectVariableValue instanceof Collection<?>) {
for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) {
addMtomPart(mimeMultipart, httpVariable, httpVariableValue);
}
}
} else {
addMtomPart(mimeMultipart, httpVariable, httpObjectVariableValue);
}
mp[0] = mimeMultipart;
} catch (Exception e) {
Engine.logBeans.warn("(HttpConnector) Failed to add MTOM part for " + httpVariable.getName(), e);
}
}
}
}
if (mp[0] == null) {
entityEnclosingMethod.setRequestEntity(new StringRequestEntity(postQuery, MimeType.TextXml.value(), "UTF-8"));
} else {
Engine.logBeans.debug("(HttpConnector) Commit the MTOM request with the ContentType: " + mp[0].getContentType());
HeaderName.ContentType.setRequestHeader(method, mp[0].getContentType());
entityEnclosingMethod.setRequestEntity(new RequestEntity() {
@Override
public void writeRequest(OutputStream outputStream) throws IOException {
try {
mp[0].writeTo(outputStream);
} catch (MessagingException e) {
new IOException(e);
}
}
@Override
public boolean isRepeatable() {
return true;
}
@Override
public String getContentType() {
return mp[0].getContentType();
}
@Override
public long getContentLength() {
return -1;
}
});
}
} else {
String charset = httpTransaction.getComputedUrlEncodingCharset();
HeaderName.ContentType.setRequestHeader(method, contentType);
entityEnclosingMethod.setRequestEntity(new StringRequestEntity(postQuery, contentType, charset));
}
}
// Getting the result
Engine.logBeans.debug("(HttpConnector) HttpClient: getting response body");
byte[] result = executeMethod(method, context);
long length = result != null ? result.length : 0;
if (context.transaction instanceof DownloadHttpTransaction) {
try {
length = (long) context.get("__downloadedFileLength");
} catch (Exception e) {
}
}
Engine.logBeans.debug("(HttpConnector) Total read bytes: " + length);
// Fire event for plugins
long t1 = System.currentTimeMillis();
Engine.theApp.pluginsManager.fireHttpConnectorGetDataEnd(context, t0, t1);
StringBuilder sb = new StringBuilder();
sb.append("HTTP result {ContentType: " + context.contentType + ", Length: " + length + "}\n\n");
if (result != null && context.contentType != null && (context.contentType.startsWith("text/") || context.contentType.startsWith("application/xml") || context.contentType.startsWith("application/json"))) {
sb.append(new String(result, "UTF-8"));
}
fireDataChanged(new ConnectorEvent(this, sb.toString()));
return result;
} finally {
if (method != null)
method.releaseConnection();
}
}
use of com.twinsoft.convertigo.beans.transactions.AbstractHttpTransaction in project convertigo by convertigo.
the class HttpConnector method doExecuteMethod.
protected int doExecuteMethod(final HttpMethod method, Context context) throws ConnectionException, URIException, MalformedURLException {
int statuscode = -1;
// Tells the method to automatically handle authentication.
method.setDoAuthentication(true);
// Tells the method to automatically handle redirection.
method.setFollowRedirects(false);
HttpPool httpPool = ((AbstractHttpTransaction) context.transaction).getHttpPool();
HttpClient httpClient = context.getHttpClient3(httpPool);
try {
// Display the cookies
if (handleCookie) {
Cookie[] cookies = httpState.getCookies();
if (Engine.logBeans.isTraceEnabled())
Engine.logBeans.trace("(HttpConnector) HttpClient request cookies:" + Arrays.asList(cookies).toString());
}
forwardHeader(new HeaderForwarder() {
public void add(String name, String value, String forwardPolicy) {
if (HttpConnector.HTTP_HEADER_FORWARD_POLICY_IGNORE.equals(forwardPolicy)) {
Header exHeader = method.getRequestHeader(name);
if (exHeader != null) {
// Nothing to do
Engine.logEngine.debug("(WebViewer) Forwarding header '" + name + "' has been ignored due to forward policy");
} else {
method.setRequestHeader(name, value);
Engine.logEngine.debug("(WebViewer) Header forwarded and added: " + name + "=" + value);
}
} else if (HttpConnector.HTTP_HEADER_FORWARD_POLICY_REPLACE.equals(forwardPolicy)) {
method.setRequestHeader(name, value);
Engine.logEngine.debug("(WebViewer) Header forwarded and replaced: " + name + "=" + value);
} else if (HttpConnector.HTTP_HEADER_FORWARD_POLICY_MERGE.equals(forwardPolicy)) {
Header exHeader = method.getRequestHeader(name);
if (exHeader != null)
value = exHeader.getValue() + ", " + value;
method.setRequestHeader(name, value);
Engine.logEngine.debug("(WebViewer) Header forwarded and merged: " + name + "=" + value);
}
}
});
// handle oAuthSignatures if any
if (oAuthKey != null && oAuthSecret != null && oAuthToken != null && oAuthTokenSecret != null) {
oAuthConsumer = new HttpOAuthConsumer(oAuthKey, oAuthSecret, hostConfiguration);
oAuthConsumer.setTokenWithSecret(oAuthToken, oAuthTokenSecret);
oAuthConsumer.sign(method);
oAuthConsumer = null;
}
HttpUtils.logCurrentHttpConnection(httpClient, hostConfiguration, httpPool);
hostConfiguration.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, (int) context.requestedObject.getResponseTimeout() * 1000);
hostConfiguration.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, (int) context.requestedObject.getResponseTimeout() * 1000);
Engine.logBeans.debug("(HttpConnector) HttpClient: executing method...");
statuscode = httpClient.executeMethod(hostConfiguration, method, httpState);
Engine.logBeans.debug("(HttpConnector) HttpClient: end of method successfull");
// Display the cookies
if (handleCookie) {
Cookie[] cookies = httpState.getCookies();
if (Engine.logBeans.isTraceEnabled())
Engine.logBeans.trace("(HttpConnector) HttpClient response cookies:" + Arrays.asList(cookies).toString());
}
} catch (SocketTimeoutException e) {
throw new ConnectionException("Timeout reached (" + context.requestedObject.getResponseTimeout() + " sec)");
} catch (IOException e) {
if (!context.requestedObject.runningThread.bContinue) {
return statuscode;
}
HttpUtils.logCurrentHttpConnection(httpClient, hostConfiguration, httpPool);
Engine.logBeans.warn("(HttpConnector) HttpClient: connection error to " + sUrl + ": " + e.getMessage());
} catch (OAuthException eee) {
throw new ConnectionException("OAuth Connection error to " + sUrl, eee);
}
return statuscode;
}
use of com.twinsoft.convertigo.beans.transactions.AbstractHttpTransaction in project convertigo by convertigo.
the class WebServiceTranslator method addElement.
private void addElement(SOAPMessage responseMessage, SOAPEnvelope soapEnvelope, Context context, Element elementToAdd, SOAPElement soapElement) throws SOAPException {
SOAPElement soapMethodResponseElement = (SOAPElement) soapEnvelope.getBody().getFirstChild();
String targetNamespace = soapMethodResponseElement.getNamespaceURI();
String prefix = soapMethodResponseElement.getPrefix();
String nodeType = elementToAdd.getAttribute("type");
SOAPElement childSoapElement = soapElement;
boolean elementAdded = true;
boolean bTable = false;
if (nodeType.equals("table")) {
bTable = true;
/*childSoapElement = soapElement.addChildElement("ArrayOf" + context.transactionName + "_" + tableName + "_Row", "");
if (!context.httpServletRequest.getServletPath().endsWith(".wsl")) {
childSoapElement.addAttribute(soapEnvelope.createName("xsi:type"), "soapenc:Array");
}*/
childSoapElement = soapElement.addChildElement(elementToAdd.getNodeName());
} else if (nodeType.equals("row")) {
/*String elementType = context.transactionName + "_" + tableName + "_Row";
childSoapElement = soapElement.addChildElement(elementType, "");*/
childSoapElement = soapElement.addChildElement(elementToAdd.getNodeName());
} else if (nodeType.equals("attachment")) {
childSoapElement = soapElement.addChildElement(elementToAdd.getNodeName());
if (context.requestedObject instanceof AbstractHttpTransaction) {
AttachmentDetails attachment = AttachmentManager.getAttachment(elementToAdd);
if (attachment != null) {
byte[] raw = attachment.getData();
if (raw != null)
childSoapElement.addTextNode(Base64.encodeBase64String(raw));
}
/* DON'T WORK YET *\
AttachmentPart ap = responseMessage.createAttachmentPart(new ByteArrayInputStream(raw), elementToAdd.getAttribute("content-type"));
ap.setContentId(key);
ap.setContentLocation(elementToAdd.getAttribute("url"));
responseMessage.addAttachmentPart(ap);
\* DON'T WORK YET */
}
} else {
String elementNodeName = elementToAdd.getNodeName();
String elementNodeNsUri = elementToAdd.getNamespaceURI();
String elementNodePrefix = getPrefix(context.projectName, elementNodeNsUri);
XmlSchemaElement xmlSchemaElement = getXmlSchemaElementByName(context.projectName, elementNodeName);
boolean isGlobal = xmlSchemaElement != null;
if (isGlobal) {
elementNodeNsUri = xmlSchemaElement.getQName().getNamespaceURI();
elementNodePrefix = getPrefix(context.projectName, elementNodeNsUri);
}
// }
if ("http://schemas.xmlsoap.org/soap/envelope/".equals(elementToAdd.getNamespaceURI()) || "http://schemas.xmlsoap.org/soap/envelope/".equals(elementToAdd.getParentNode().getNamespaceURI()) || elementToAdd.getParentNode().getNodeName().toUpperCase().indexOf("NS0:") != -1 || elementNodeName.toUpperCase().indexOf("NS0:") != -1) {
elementAdded = false;
} else {
if (XsdForm.qualified == context.project.getSchemaElementForm() || isGlobal) {
if (elementNodePrefix == null) {
childSoapElement = soapElement.addChildElement(soapEnvelope.createName(elementNodeName, prefix, targetNamespace));
} else {
childSoapElement = soapElement.addChildElement(soapEnvelope.createName(elementNodeName, elementNodePrefix, elementNodeNsUri));
}
} else {
childSoapElement = soapElement.addChildElement(elementNodeName);
}
}
}
if (elementAdded && elementToAdd.hasAttributes()) {
addAttributes(responseMessage, soapEnvelope, context, elementToAdd.getAttributes(), childSoapElement);
}
if (elementToAdd.hasChildNodes()) {
NodeList childNodes = elementToAdd.getChildNodes();
int len = childNodes.getLength();
if (bTable) {
/*if (!context.httpServletRequest.getServletPath().endsWith(".wsl")) {
childSoapElement.addAttribute(soapEnvelope.createName("soapenc:arrayType"), context.projectName+"_ns:" + context.transactionName + "_" + tableName + "_Row[" + (len - 1) + "]");
}*/
}
org.w3c.dom.Node node;
Element childElement;
for (int i = 0; i < len; i++) {
node = childNodes.item(i);
switch(node.getNodeType()) {
case org.w3c.dom.Node.ELEMENT_NODE:
childElement = (Element) node;
addElement(responseMessage, soapEnvelope, context, childElement, childSoapElement);
break;
case org.w3c.dom.Node.CDATA_SECTION_NODE:
case org.w3c.dom.Node.TEXT_NODE:
String text = node.getNodeValue();
text = (text == null) ? "" : text;
childSoapElement.addTextNode(text);
break;
default:
break;
}
}
/*org.w3c.dom.Node node;
Element childElement;
for (int i = 0 ; i < len ; i++) {
node = childNodes.item(i);
if (node instanceof Element) {
childElement = (Element) node;
addElement(responseMessage, soapEnvelope, context, childElement, childSoapElement);
}
else if (node instanceof CDATASection) {
Node textNode = XMLUtils.findChildNode(elementToAdd, org.w3c.dom.Node.CDATA_SECTION_NODE);
String text = textNode.getNodeValue();
if (text == null) {
text = "";
}
childSoapElement.addTextNode(text);
}
else {
Node textNode = XMLUtils.findChildNode(elementToAdd, org.w3c.dom.Node.TEXT_NODE);
if (textNode != null) {
String text = textNode.getNodeValue();
if (text == null) {
text = "";
}
childSoapElement.addTextNode(text);
}
}
}*/
}
}
Aggregations