use of com.twinsoft.convertigo.engine.enums.HttpMethodType in project convertigo by convertigo.
the class NewObjectWizard method doFinish.
private void doFinish(IProgressMonitor monitor) throws CoreException {
String dboName, name;
boolean bContinue = true;
int index = 0;
try {
int total = 0;
Class<?> c = getCreatedBeanClass();
if (c != null) {
total = 4;
if (c.equals(WebServiceReference.class)) {
total += ImportWsReference.getTotalTaskNumber();
}
}
monitor.beginTask("Creating new object", total);
newBean = getCreatedBean();
if (newBean != null) {
monitor.setTaskName("Object created");
monitor.worked(1);
dboName = newBean.getName();
if (!StringUtils.isNormalized(dboName))
throw new EngineException("Bean name is not normalized : \"" + dboName + "\".");
// Verify if a child object with same name exist and change name
while (bContinue) {
if (index == 0)
name = dboName;
else
name = dboName + index;
newBean.setName(name);
newBean.hasChanged = true;
newBean.bNew = true;
try {
new WalkHelper() {
boolean root = true;
boolean find = false;
@Override
protected boolean before(DatabaseObject dbo, Class<? extends DatabaseObject> dboClass) {
boolean isInstance = dboClass.isInstance(newBean);
find |= isInstance;
return isInstance;
}
@Override
protected void walk(DatabaseObject dbo) throws Exception {
if (root) {
root = false;
super.walk(dbo);
if (!find) {
throw new EngineException("You cannot add to a " + newBean.getClass().getSimpleName() + " a database object of type " + parentObject.getClass().getSimpleName());
}
} else {
if (newBean.getName().equalsIgnoreCase(dbo.getName())) {
throw new ObjectWithSameNameException("Unable to add the object because an object with the same name already exists in target.");
}
}
}
}.init(parentObject);
bContinue = false;
} catch (ObjectWithSameNameException owsne) {
if ((parentObject instanceof HtmlTransaction) && (newBean instanceof Statement)) {
throw new EngineException("HtmlTransaction already contains a statement named \"" + name + "\".", owsne);
}
// Silently ignore
index++;
} catch (EngineException ee) {
throw ee;
} catch (Exception e) {
throw new EngineException("Exception in create", e);
}
}
// Now add bean to target
try {
boolean hasChanged = parentObject.hasChanged;
if ((newBean instanceof Statement) && (parentObject instanceof Transaction)) {
newBean.priority = 0;
}
if (newBean instanceof ScreenClass)
newBean.priority = parentObject.priority + 1;
if (newBean instanceof Criteria) {
Connector connector = parentObject.getConnector();
if (parentObject.equals(((IScreenClassContainer<?>) connector).getDefaultScreenClass()))
throw new EngineException("You cannot add a new criterion on default screenclass.");
}
parentObject.add(newBean);
monitor.setTaskName("Object added");
monitor.worked(1);
if (newBean instanceof HTTPStatement) {
HTTPStatement httpStatement = (HTTPStatement) newBean;
HtmlConnector connector = (HtmlConnector) httpStatement.getParentTransaction().getParent();
httpStatement.setMethod("GET");
httpStatement.setHost(connector.getServer());
httpStatement.setPort(connector.getPort());
httpStatement.setHttps(connector.isHttps());
}
if (newBean instanceof ContinueWithSiteClipperStatement) {
Project project = newBean.getProject();
if (project != null) {
String[] connectorWithSiteClipperConnector = ContinueWithSiteClipperStatement.getSiteClippersConnectorNames(project);
if (connectorWithSiteClipperConnector.length > 0) {
((ContinueWithSiteClipperStatement) newBean).setSiteClipperConnectorName(connectorWithSiteClipperConnector[0]);
}
}
}
if (newBean instanceof Connector) {
Project project = (Project) parentObject;
if (project.getDefaultConnector() == null)
project.setDefaultConnector((Connector) newBean);
Connector.setupConnector(newBean);
}
if (newBean instanceof PageComponent) {
ApplicationComponent application = (ApplicationComponent) parentObject;
if (application.getRootPage() == null)
application.setRootPage((PageComponent) newBean);
}
if (newBean instanceof SequenceStep) {
Project project = newBean.getProject();
((SequenceStep) newBean).setSourceSequence(project.getName() + TransactionStep.SOURCE_SEPARATOR + project.getSequencesList().get(0));
}
if (newBean instanceof TransactionStep) {
Project project = newBean.getProject();
Connector connector = project.getDefaultConnector();
Transaction transaction = connector.getDefaultTransaction();
((TransactionStep) newBean).setSourceTransaction(project.getName() + TransactionStep.SOURCE_SEPARATOR + connector.getName() + TransactionStep.SOURCE_SEPARATOR + transaction.getName());
}
if (newBean instanceof IThenElseContainer) {
ThenStep thenStep = new ThenStep();
((IThenElseContainer) newBean).addStep(thenStep);
ElseStep elseStep = new ElseStep();
((IThenElseContainer) newBean).addStep(elseStep);
}
if (newBean instanceof IThenElseStatementContainer) {
ThenStatement thenStatement = new ThenStatement();
((IThenElseStatementContainer) newBean).addStatement(thenStatement);
ElseStatement elseStatement = new ElseStatement();
((IThenElseStatementContainer) newBean).addStatement(elseStatement);
}
if (newBean instanceof Sheet) {
InputStream is = null;
try {
String sheetName = newBean.getName() + ".xsl";
is = new FileInputStream(new File(Engine.XSL_PATH + "/customsheet.xsl"));
String projectName = ((DatabaseObject) parentObject).getProject().getName();
IProject project = ConvertigoPlugin.getDefault().getProjectPluginResource(projectName);
final IFile file = project.getFile(sheetName);
if (!file.exists())
file.create(is, true, null);
((Sheet) newBean).setUrl(sheetName);
} catch (Exception e) {
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
}
if (newBean instanceof TestCase) {
TestCase testCase = (TestCase) newBean;
testCase.importRequestableVariables((RequestableObject) testCase.getParent());
}
if (newBean instanceof RequestableHttpVariable) {
RequestableHttpVariable variable = (RequestableHttpVariable) newBean;
AbstractHttpTransaction httpTransaction = (AbstractHttpTransaction) variable.getParent();
HttpMethodType httpMethodType = httpTransaction.getHttpVerb();
boolean isVarPost = httpMethodType.equals(HttpMethodType.PUT) || httpMethodType.equals(HttpMethodType.POST);
variable.setHttpMethod(isVarPost ? HttpMethodType.POST.name() : HttpMethodType.GET.name());
if (!(httpTransaction instanceof HtmlTransaction)) {
variable.setHttpName(variable.getName());
}
}
if (newBean instanceof WebServiceReference) {
try {
Project project = (Project) parentObject;
WebServiceReference webServiceReference = (WebServiceReference) newBean;
ImportWsReference wsr = new ImportWsReference(webServiceReference);
wsr.importInto(project);
} catch (Exception e) {
if (newBean != null) {
parentObject.remove(newBean);
parentObject.hasChanged = hasChanged;
}
throw new Exception(e);
}
}
if (newBean instanceof RestServiceReference) {
try {
Project project = (Project) parentObject;
RestServiceReference restServiceReference = (RestServiceReference) newBean;
ImportWsReference wsr = new ImportWsReference(restServiceReference);
wsr.importInto(project);
} catch (Exception e) {
if (newBean != null) {
parentObject.remove(newBean);
parentObject.hasChanged = hasChanged;
}
throw new Exception(e);
}
}
if (newBean instanceof SqlTransaction) {
SqlTransaction sqlTransaction = (SqlTransaction) newBean;
sqlTransaction.setSqlQuery(sqlQueriesWizardPage.getSQLQueries());
sqlTransaction.initializeQueries(true);
}
if (newBean instanceof SapJcoLogonTransaction) {
SapJcoLogonTransaction sapLogonTransaction = (SapJcoLogonTransaction) newBean;
sapLogonTransaction.addCredentialsVariables();
}
if (newBean instanceof AbstractCouchDbTransaction) {
AbstractCouchDbTransaction abstractCouchDbTransaction = (AbstractCouchDbTransaction) newBean;
List<CouchVariable> selectedVariables = objectInfoPage.getSelectedParameters();
abstractCouchDbTransaction.createVariables(selectedVariables);
}
ConvertigoPlugin.logInfo("New object class '" + this.className + "' named '" + newBean.getName() + "' has been added");
monitor.setTaskName("Object setted up");
monitor.worked(1);
bContinue = false;
} catch (com.twinsoft.convertigo.engine.ObjectWithSameNameException owsne) {
if (newBean instanceof HandlerStatement) {
throw owsne;
}
}
} else {
throw new Exception("Could not instantiate bean!");
}
} catch (Exception e) {
String message = "Unable to create a new object from class '" + this.className + "'.";
ConvertigoPlugin.logException(e, message);
if (objectExplorerPage != null) {
objectExplorerPage.doCancel();
}
}
}
use of com.twinsoft.convertigo.engine.enums.HttpMethodType in project convertigo by convertigo.
the class HTTPStatement method execute.
@Override
public boolean execute(Context javascriptContext, Scriptable scope) throws EngineException {
if (isEnabled()) {
if (super.execute(javascriptContext, scope)) {
this.javascriptContext = javascriptContext;
this.scope = scope;
HtmlTransaction htmlTransaction = getParentTransaction();
HttpMethodType exVerb = htmlTransaction.getHttpVerb();
String exCustomVerb = htmlTransaction.getCustomHttpVerb();
long exTimeout = htmlTransaction.getResponseTimeout();
try {
htmlTransaction.setHttpVerb(getHttpVerb());
htmlTransaction.setCustomHttpVerb(getCustomHttpVerb());
try {
htmlTransaction.setResponseTimeout(getTrigger().getTrigger().getTimeout() / 1000);
} finally {
}
htmlTransaction.applyUserRequest(this);
return true;
} finally {
htmlTransaction.setHttpVerb(exVerb);
htmlTransaction.setCustomHttpVerb(exCustomVerb);
htmlTransaction.setResponseTimeout(exTimeout);
}
}
}
return false;
}
use of com.twinsoft.convertigo.engine.enums.HttpMethodType in project convertigo by convertigo.
the class FullSyncServlet method service.
@Override
protected void service(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
StringBuffer debug = new StringBuffer();
HttpMethodType method;
try {
HttpUtils.checkCV(request);
String corsOrigin = HttpUtils.applyCorsHeaders(request, response);
if (corsOrigin != null) {
debug.append("Added CORS header for: " + corsOrigin + "\n");
}
method = HttpMethodType.valueOf(request.getMethod());
if (method == HttpMethodType.OPTIONS) {
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
return;
}
if (method != HttpMethodType.HEAD) {
HttpSessionListener.checkSession(request);
}
} catch (Throwable e) {
throw new ServletException(e);
}
HttpSession httpSession = request.getSession();
try {
FullSyncClient fsClient = Engine.theApp.couchDbManager.getFullSyncClient();
RequestParser requestParser = new RequestParser(request, fsClient.getPrefix());
boolean isUtilsSession = "true".equals(httpSession.getAttribute("__isUtilsSession"));
boolean isUtilsRequest = false;
if (isUtilsSession || "_utils".equals(requestParser.special)) {
Engine.authenticatedSessionManager.checkRoles(httpSession, Role.WEB_ADMIN, Role.FULLSYNC_CONFIG, Role.FULLSYNC_VIEW);
httpSession.setAttribute("__isUtilsSession", "true");
String referer = request.getHeader("Referer");
isUtilsRequest = (referer != null && referer.contains("/_utils/") && !"_all_dbs".equals(requestParser.getSpecial()));
} else {
Engine.theApp.couchDbManager.checkRequest(requestParser.getPath(), requestParser.getSpecial(), requestParser.getDocId());
}
synchronized (httpSession) {
Set<HttpServletRequest> set = SessionAttribute.fullSyncRequests.get(httpSession);
if (set == null) {
SessionAttribute.fullSyncRequests.set(httpSession, set = new HashSet<HttpServletRequest>());
}
set.add(request);
}
LogParameters logParameters = GenericUtils.cast(httpSession.getAttribute(FullSyncServlet.class.getCanonicalName()));
if (logParameters == null) {
httpSession.setAttribute(FullSyncServlet.class.getCanonicalName(), logParameters = new LogParameters());
logParameters.put(mdcKeys.ContextID.toString().toLowerCase(), httpSession.getId());
}
Log4jHelper.mdcSet(logParameters);
logParameters.put(mdcKeys.ClientIP.toString().toLowerCase(), request.getRemoteAddr());
if (EnginePropertiesManager.getProperty(PropertyName.NET_REVERSE_DNS).equalsIgnoreCase("true")) {
Log4jHelper.mdcPut(mdcKeys.ClientHostName, request.getRemoteHost());
}
String dbName = requestParser.getDbName();
FullSyncAuthentication fsAuth = Engine.theApp.couchDbManager.getFullSyncAuthentication(request.getSession());
if (fsAuth == null) {
Log4jHelper.mdcPut(mdcKeys.User, "(anonymous)");
debug.append("Anonymous user\n");
Boolean allowAnonymous = null;
for (String projectName : Engine.theApp.databaseObjectsManager.getAllProjectNamesList()) {
try {
Project project = Engine.theApp.databaseObjectsManager.getOriginalProjectByName(projectName);
for (Connector connector : project.getConnectorsList()) {
if (connector instanceof FullSyncConnector) {
FullSyncConnector fullSyncConnector = (FullSyncConnector) connector;
if (fullSyncConnector.getDatabaseName().equals(dbName)) {
allowAnonymous = fullSyncConnector.getAnonymousReplication() == FullSyncAnonymousReplication.allow;
break;
}
}
}
if (allowAnonymous != null) {
break;
}
} catch (Exception e) {
// TODO: handle exception
}
}
if (allowAnonymous == Boolean.FALSE) {
throw new SecurityException("The '" + dbName + "' database deny pull synchronization for an anonymous session");
}
} else {
Log4jHelper.mdcPut(mdcKeys.User, "'" + fsAuth.getAuthenticatedUser() + "'");
debug.append("Authenticated user: ").append(fsAuth.getAuthenticatedUser()).append('\n').append("Authenticated groups: ").append(fsAuth.getGroups()).append('\n');
}
String url = Engine.theApp.couchDbManager.getFullSyncUrl() + requestParser.getPath();
URIBuilder builder = new URIBuilder(url);
String query = request.getQueryString();
if (query != null) {
try {
// needed for PouchDB replication
URI uri = URI.create(url + "?" + request.getQueryString());
query = uri.getQuery();
} catch (Exception e) {
debug.append("parse query failed (" + e.getMessage() + "), use as it; query=" + query + "\n");
}
builder.setCustomQuery(query);
}
String special = requestParser.getSpecial();
boolean isChanges = "_changes".equals(special);
String version = fsClient.getServerVersion();
if (isChanges && version.compareTo("2.") >= 0) {
method = HttpMethodType.POST;
}
debug.append("dbName=" + dbName + " special=" + special + " couchdb=" + version + (requestParser.hasAttachment() ? " attachment=true" : "") + "\n");
HttpRequestBase newRequest;
switch(method) {
case DELETE:
if (isUtilsRequest) {
Engine.authenticatedSessionManager.checkRoles(httpSession, Role.WEB_ADMIN, Role.FULLSYNC_CONFIG);
if (requestParser.getDocId() == null && StringUtils.isNotBlank(requestParser.getDbName()) && DelegateServlet.canDelegate()) {
JSONObject instruction = new JSONObject();
JSONObject variables = new JSONObject();
try {
instruction.put("action", "deleteDatabase");
variables.put("db", fsClient.getPrefix() + requestParser.getDbName());
instruction.put("variables", variables);
JSONObject deleteResponse = DelegateServlet.delegate(instruction);
if (deleteResponse != null) {
JSONObject meta = CouchKey._c8oMeta.JSONObject(deleteResponse);
CouchKey._c8oMeta.remove(deleteResponse);
response.setStatus(meta.getInt("statusCode"));
JSONObject headers = meta.getJSONObject("headers");
for (java.util.Iterator<?> i = headers.keys(); i.hasNext(); ) {
String key = (String) i.next();
response.addHeader(key, headers.getString(key));
}
response.setCharacterEncoding("UTF-8");
try (Writer w = response.getWriter()) {
w.write(deleteResponse.toString());
}
return;
}
} catch (Exception e) {
}
}
newRequest = new HttpDelete();
} else {
// disabled to prevent db delete
throw new ServletException("Invalid HTTP method");
}
break;
case GET:
newRequest = new HttpGet();
break;
case HEAD:
newRequest = new HttpHead();
break;
case OPTIONS:
newRequest = new HttpOptions();
break;
case POST:
if (isUtilsRequest) {
Engine.authenticatedSessionManager.checkRoles(httpSession, Role.WEB_ADMIN, Role.FULLSYNC_CONFIG);
}
newRequest = new HttpPost();
break;
case PUT:
if (isUtilsRequest) {
Engine.authenticatedSessionManager.checkRoles(httpSession, Role.WEB_ADMIN, Role.FULLSYNC_CONFIG);
}
newRequest = new HttpPut();
break;
case TRACE:
newRequest = new HttpTrace();
break;
default:
throw new ServletException("Invalid HTTP method");
}
if (method.equals(HttpMethodType.POST) && "_bulk_docs".equals(special)) {
int n = fsClient.getN();
if (n > 1) {
for (NameValuePair kv : builder.getQueryParams()) {
if ("w".equals(kv.getName())) {
n = 0;
break;
}
}
if (n > 1) {
builder.addParameter("w", Integer.toString(n));
}
}
}
URI uri = builder.build();
newRequest.setURI(uri);
debug.append(method.name() + " URI: " + uri.toString() + "\n");
String requestStringEntity = null;
HttpEntity httpEntity = null;
JSONObject bulkDocsRequest = null;
boolean isCBL = false;
boolean isCBLiOS = false;
{
String agent = HeaderName.UserAgent.getHeader(request);
isCBL = agent != null && agent.startsWith("CouchbaseLite/1.");
if (isCBL) {
isCBLiOS = agent.contains("iOS");
isCBL = version != null && version.compareTo("1.7") >= 0;
}
}
for (String headerName : Collections.list(request.getHeaderNames())) {
if (!(HeaderName.TransferEncoding.is(headerName) || HeaderName.ContentLength.is(headerName) || HeaderName.UserAgent.is(headerName) || HeaderName.Expect.is(headerName) || HeaderName.Connection.is(headerName) || HeaderName.Host.is(headerName) || HeaderName.Cookie.is(headerName) || HeaderName.ContentEncoding.is(headerName) || HeaderName.Origin.is(headerName) || (isChanges && (HeaderName.IfNoneMatch.is(headerName) || HeaderName.IfModifiedSince.is(headerName) || HeaderName.CacheControl.is(headerName) || HeaderName.AcceptEncoding.is(headerName))))) {
for (String headerValue : Collections.list(request.getHeaders(headerName))) {
debug.append("request Header: " + headerName + "=" + headerValue + "\n");
newRequest.addHeader(headerName, headerValue);
}
} else {
debug.append("skip request Header: " + headerName + "=" + request.getHeader(headerName) + "\n");
}
}
{
Header authBasicHeader = fsClient.getAuthBasicHeader();
if (authBasicHeader != null) {
debug.append("request add BasicHeader");
newRequest.addHeader(authBasicHeader);
}
}
if (request.getInputStream() != null) {
String reqContentType = request.getContentType();
if (reqContentType != null && reqContentType.startsWith("multipart/related;")) {
final MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(request.getInputStream(), reqContentType));
final long[] size = { request.getIntHeader(HeaderName.ContentLength.value()) };
final boolean chunked = size[0] == -1;
int count = mp.getCount();
debug.append("handle multipart/related: " + reqContentType + "; " + count + " parts; original size of " + size[0]);
final File mpTmp;
if (chunked) {
mpTmp = File.createTempFile("c8o", "mpTmp");
mpTmp.deleteOnExit();
} else {
mpTmp = null;
}
try {
bulkDocsRequest = new JSONObject();
JSONArray bulkDocsArray = new JSONArray();
CouchKey.docs.put(bulkDocsRequest, bulkDocsArray);
for (int i = 0; i < count; i++) {
BodyPart part = mp.getBodyPart(i);
ContentTypeDecoder contentType = new ContentTypeDecoder(part.getContentType());
if (contentType.mimeType() == MimeType.Json) {
String charset = contentType.getCharset("UTF-8");
List<javax.mail.Header> headers = Collections.list(GenericUtils.<Enumeration<javax.mail.Header>>cast(part.getAllHeaders()));
byte[] buf = IOUtils.toByteArray(part.getInputStream());
if (!chunked) {
size[0] -= buf.length;
}
String json = new String(buf, charset);
try {
JSONObject docRequest = new JSONObject(json);
Engine.theApp.couchDbManager.handleDocRequest(dbName, docRequest, fsAuth);
bulkDocsArray.put(docRequest);
json = docRequest.toString();
} catch (JSONException e) {
debug.append("failed to parse [ " + e.getMessage() + "]: " + json);
}
part.setContent(buf = json.getBytes(charset), part.getContentType());
if (!chunked) {
size[0] += buf.length;
}
for (javax.mail.Header header : headers) {
String name = header.getName();
if (HeaderName.ContentLength.is(name)) {
part.setHeader(name, Integer.toString(buf.length));
} else {
part.setHeader(name, header.getValue());
}
}
}
}
if (chunked) {
try (FileOutputStream fos = new FileOutputStream(mpTmp)) {
mp.writeTo(fos);
}
size[0] = mpTmp.length();
}
debug.append("; new size of " + size[0] + "\n");
httpEntity = new AbstractHttpEntity() {
@Override
public void writeTo(OutputStream output) throws IOException {
if (chunked) {
try (FileInputStream fis = new FileInputStream(mpTmp)) {
IOUtils.copyLarge(fis, output);
}
} else {
try {
mp.writeTo(output);
} catch (MessagingException e) {
new IOException(e);
}
}
}
@Override
public boolean isStreaming() {
return false;
}
@Override
public boolean isRepeatable() {
return true;
}
@Override
public long getContentLength() {
return size[0];
}
@Override
public InputStream getContent() throws IOException, IllegalStateException {
return null;
}
};
} finally {
if (mpTmp != null) {
mpTmp.delete();
}
}
} else {
InputStream is = null;
try {
if ("gzip".equals(HeaderName.ContentEncoding.getHeader(request))) {
is = new GZIPInputStream(request.getInputStream());
} else {
is = request.getInputStream();
}
requestStringEntity = IOUtils.toString(is, "UTF-8");
debug.append("request Entity:\n" + requestStringEntity + "\n");
} finally {
if (is != null) {
is.close();
}
}
}
}
boolean isNewStringEntity = false;
if (method == HttpMethodType.POST && "_bulk_docs".equals(special)) {
try {
bulkDocsRequest = new JSONObject(requestStringEntity);
Engine.theApp.couchDbManager.handleBulkDocsRequest(dbName, bulkDocsRequest, fsAuth);
String newEntity = bulkDocsRequest.toString();
if (!newEntity.equals(requestStringEntity)) {
requestStringEntity = newEntity;
isNewStringEntity = true;
}
} catch (JSONException e) {
debug.append("failed to parse [ " + e.getMessage() + "]: " + requestStringEntity);
}
} else if (isChanges) {
requestStringEntity = Engine.theApp.couchDbManager.handleChangesUri(dbName, newRequest, requestStringEntity, fsAuth);
if (requestStringEntity != null) {
debug.append("request new Entity:\n" + requestStringEntity + "\n");
}
uri = newRequest.getURI();
debug.append("Changed to " + newRequest.getMethod() + " URI: " + uri + "\n");
}
if (!isChanges && newRequest instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRequest entityRequest = ((HttpEntityEnclosingRequest) newRequest);
if (entityRequest.getEntity() == null) {
if (httpEntity != null) {
// already exists
} else if (requestStringEntity != null) {
if (isNewStringEntity) {
debug.append("request new Entity:\n" + requestStringEntity + "\n");
}
httpEntity = new StringEntity(requestStringEntity, "UTF-8");
} else {
httpEntity = new InputStreamEntity(request.getInputStream());
}
entityRequest.setEntity(httpEntity);
}
}
Map<AbstractFullSyncListener, JSONArray> listeners = Engine.theApp.couchDbManager.handleBulkDocsRequest(dbName, bulkDocsRequest);
long requestTime = System.currentTimeMillis();
CloseableHttpResponse newResponse = null;
try {
newResponse = httpClient.get().execute(newRequest);
} catch (IOException e) {
debug.append("retry request because: " + e.getMessage());
newResponse = httpClient.get().execute(newRequest);
}
requestTime = System.currentTimeMillis() - requestTime;
int code = newResponse.getStatusLine().getStatusCode();
debug.append("response Code: " + code + " in " + requestTime + " ms\n");
if (isCBLiOS && code == 400) {
code = 500;
debug.append("response changed Code to: " + code + " (for iOS CBL)\n");
}
response.setStatus(code);
boolean isCblBulkGet = isCBL && version.compareTo("2.3.") < 0 && "_bulk_get".equals(special);
if (!isCblBulkGet) {
for (Header header : newResponse.getAllHeaders()) {
if (isCBL && HeaderName.Server.is(header)) {
response.addHeader("Server", "Couchbase Sync Gateway/0.81");
debug.append("response Header: Server=Couchbase Sync Gateway/0.81\n");
} else if (!(HeaderName.TransferEncoding.is(header) || HeaderName.ContentLength.is(header) || HeaderName.AccessControlAllowOrigin.is(header) || (isChanges && (HeaderName.ETag.is(header) || HeaderName.LastModified.is(header) || HeaderName.CacheControl.is(header))))) {
response.addHeader(header.getName(), header.getValue());
debug.append("response Header: " + header.getName() + "=" + header.getValue() + "\n");
} else {
debug.append("skip response Header: " + header.getName() + "=" + header.getValue() + "\n");
}
}
ServletUtils.applyCustomHeaders(request, response);
}
HttpEntity responseEntity = newResponse.getEntity();
ContentTypeDecoder contentType = new ContentTypeDecoder(responseEntity == null || responseEntity.getContentType() == null ? "" : responseEntity.getContentType().getValue());
debug.append("response ContentType charset=" + contentType.getCharset("n/a") + " mime=" + contentType.getMimeType() + "\n");
OutputStream os = response.getOutputStream();
String responseStringEntity = null;
if (responseEntity != null) {
// InputStream is = null;
try (InputStream is = responseEntity.getContent()) {
if (code >= 200 && code < 300 && !isUtilsRequest && contentType.mimeType().in(MimeType.Plain, MimeType.Json) && !"_design".equals(special) && !requestParser.hasAttachment() && ((isChanges && version.compareTo("2.") < 0) || "_bulk_get".equals(special) || "_all_docs".equals(special) || "_all_dbs".equals(special) || StringUtils.isNotEmpty(requestParser.getDocId()) || (bulkDocsRequest != null && listeners != null))) {
String charset = contentType.getCharset("UTF-8");
try (OutputStreamWriter writer = new OutputStreamWriter(os, charset);
BufferedInputStream bis = new BufferedInputStream(is)) {
if (isChanges) {
Engine.logCouchDbManager.info("(FullSyncServlet) Entering in continuous loop:\n" + debug);
try (BufferedReader br = new BufferedReader(new InputStreamReader(bis, charset))) {
Engine.theApp.couchDbManager.filterChanges(httpSession.getId(), dbName, uri, fsAuth, br, writer);
}
} else if (bulkDocsRequest != null) {
Engine.logCouchDbManager.info("(FullSyncServlet) Handle bulkDocsRequest:\n" + debug);
responseStringEntity = IOUtils.toString(bis, charset);
writer.write(responseStringEntity);
writer.flush();
if (listeners != null) {
Engine.theApp.couchDbManager.handleBulkDocsResponse(request, listeners, bulkDocsRequest, responseStringEntity);
}
} else if (isCblBulkGet) {
Engine.logCouchDbManager.info("(FullSyncServlet) Checking text response documents for CBL BulkGet:\n" + debug);
Engine.theApp.couchDbManager.checkCblBulkGetResponse(special, fsAuth, bis, charset, response);
} else {
Engine.logCouchDbManager.info("(FullSyncServlet) Checking response documents:\n" + debug);
Engine.theApp.couchDbManager.checkResponse(special, fsAuth, bis, charset, writer);
}
}
} else if (code >= 200 && code < 300 && contentType.mimeType() == MimeType.MultiPartRelated && "_bulk_get".equals(special)) {
Engine.logCouchDbManager.info("(FullSyncServlet) Checking multipart response documents for CBL BulkGet:\n" + debug);
Engine.theApp.couchDbManager.checkCblBulkGetResponse(fsAuth, is, response);
} else if (Pattern.matches(".*/bundle\\..*?\\.js", uri.getPath())) {
StringBuilder sb = new StringBuilder();
sb.append(IOUtils.toString(is, "UTF-8").replace("json=function(e){var t", "json=function(e){e=e.replace('../../','../');var t"));
sb.append("\n$(\"#primary-navbar\").remove();");
byte[] b = sb.toString().getBytes("UTF-8");
HeaderName.ContentLength.addHeader(response, Integer.toString(b.length));
os.write(b);
} else if (Pattern.matches(".*/styles\\..*?\\.css", uri.getPath())) {
StringBuilder sb = new StringBuilder();
sb.append(IOUtils.toString(is, "UTF-8"));
sb.append("\n.closeMenu #dashboard { left: 0px; }");
sb.append("\n.closeMenu .pusher { padding-right: 0px; }");
sb.append("\nbutton.add-new-database-btn { display: none; }");
sb.append("\n#notification-center-btn { display: none; }");
sb.append("\na.fonticon-replicate { display: none; }");
sb.append("\n.faux-header__doc-header-dropdown-itemwrapper a.faux-header__doc-header-dropdown-item[href*=\"replication\"] { display: none; }\n");
byte[] b = sb.toString().getBytes("UTF-8");
HeaderName.ContentLength.addHeader(response, Integer.toString(b.length));
os.write(b);
} else if (requestParser.docId == null && requestParser.special == null && !fsClient.getPrefix().isEmpty()) {
String content = IOUtils.toString(is, "UTF-8");
content = content.replace("\"db_name\":\"" + fsClient.getPrefix(), "\"db_name\":\"");
byte[] bytes = content.getBytes("UTF-8");
HeaderName.ContentLength.addHeader(response, Integer.toString(bytes.length));
debug.append("response Header: " + HeaderName.ContentLength.value() + "=" + bytes.length + "\n");
Engine.logCouchDbManager.info("(FullSyncServlet) Remove prefix from response:\n" + debug);
os.write(bytes);
} else {
String contentLength = HeaderName.ContentLength.getHeader(newResponse);
if (contentLength != null) {
HeaderName.ContentLength.addHeader(response, contentLength);
debug.append("response Header: " + HeaderName.ContentLength.value() + "=" + contentLength + "\n");
}
Engine.logCouchDbManager.info("(FullSyncServlet) Copying response stream:\n" + debug);
StreamUtils.copyAutoFlush(is, os);
}
} finally {
newResponse.close();
}
}
} catch (SecurityException e) {
Engine.logCouchDbManager.warn("(FullSyncServlet) Failed to process request due to a security exception:\n" + e.getMessage() + "\n" + debug);
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
HttpUtils.terminateNewSession(httpSession);
} catch (EngineException e) {
String message = e.getMessage();
if (message != null && message.contains("anonymous user")) {
Engine.logCouchDbManager.warn("(FullSyncServlet) Failed to process request: " + message + "\n" + debug);
} else {
Engine.logCouchDbManager.error("(FullSyncServlet) Failed to process request:\n" + debug, e);
}
HttpUtils.terminateNewSession(httpSession);
} catch (Exception e) {
if ("ClientAbortException".equals(e.getClass().getSimpleName())) {
Engine.logCouchDbManager.info("(FullSyncServlet) Client disconnected:\n" + debug);
} else {
Engine.logCouchDbManager.error("(FullSyncServlet) Failed to process request:\n" + debug, e);
}
HttpUtils.terminateNewSession(httpSession);
} finally {
Log4jHelper.mdcClear();
synchronized (httpSession) {
Set<HttpServletRequest> set = SessionAttribute.fullSyncRequests.get(httpSession);
if (set != null) {
set.remove(request);
}
}
}
}
use of com.twinsoft.convertigo.engine.enums.HttpMethodType 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.engine.enums.HttpMethodType 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);
Engine.logBeans.debug("(HttpConnector) Total read bytes: " + ((result != null) ? result.length : 0));
// 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: " + (result != null ? result.length : 0) + "}\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();
}
}
Aggregations