Search in sources :

Example 51 with MultipartRequestEntity

use of org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity in project convertigo by convertigo.

the class HTTPUploadStatement method handleUpload.

public void handleUpload(HttpMethod method, Context context) throws EngineException {
    if (method instanceof PostMethod) {
        try {
            PostMethod uploadMethod = (PostMethod) method;
            MultipartRequestEntity mp = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), uploadMethod.getParams());
            HeaderName.ContentType.setRequestHeader(method, mp.getContentType());
            uploadMethod.setRequestEntity(mp);
        } catch (Exception e) {
            throw new EngineException("(HTTPUploadStatement) failed to handleUpload", e);
        }
    }
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) EngineException(com.twinsoft.convertigo.engine.EngineException) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FileNotFoundException(java.io.FileNotFoundException) EngineException(com.twinsoft.convertigo.engine.EngineException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 52 with MultipartRequestEntity

use of org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity in project convertigo by convertigo.

the class RemoteAdmin method deployArchive.

public void deployArchive(File archiveFile, boolean bAssembleXsl) throws RemoteAdminException {
    String deployServiceURL = (bHttps ? "https" : "http") + "://" + serverBaseUrl + "/admin/services/projects.Deploy?bAssembleXsl=" + bAssembleXsl;
    PostMethod deployMethod = null;
    Protocol myhttps = null;
    try {
        if (bHttps && bTrustAllCertificates) {
            ProtocolSocketFactory socketFactory = MySSLSocketFactory.getSSLSocketFactory(null, null, null, null, true);
            myhttps = new Protocol("https", socketFactory, serverPort);
            Protocol.registerProtocol("https", myhttps);
            hostConfiguration = httpClient.getHostConfiguration();
            hostConfiguration.setHost(host, serverPort, myhttps);
            httpClient.setHostConfiguration(hostConfiguration);
        }
        deployMethod = new PostMethod(deployServiceURL);
        Part[] parts = { new FilePart(archiveFile.getName(), archiveFile) };
        deployMethod.setRequestEntity(new MultipartRequestEntity(parts, deployMethod.getParams()));
        int returnCode = httpClient.executeMethod(deployMethod);
        String httpResponse = deployMethod.getResponseBodyAsString();
        if (returnCode == HttpStatus.SC_OK) {
            Document domResponse;
            try {
                DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                domResponse = parser.parse(new InputSource(new StringReader(httpResponse)));
                domResponse.normalize();
                NodeList nodeList = domResponse.getElementsByTagName("error");
                if (nodeList.getLength() != 0) {
                    Element errorNode = (Element) nodeList.item(0);
                    Element errorMessage = (Element) errorNode.getElementsByTagName("message").item(0);
                    Element exceptionName = (Element) errorNode.getElementsByTagName("exception").item(0);
                    Element stackTrace = (Element) errorNode.getElementsByTagName("stacktrace").item(0);
                    if (errorMessage != null) {
                        throw new RemoteAdminException(errorMessage.getTextContent(), exceptionName.getTextContent(), stackTrace.getTextContent());
                    } else {
                        throw new RemoteAdminException("An unexpected error has occured during the Convertigo project deployment: \n" + "Body content: \n\n" + XMLUtils.prettyPrintDOMWithEncoding(domResponse, "UTF-8"));
                    }
                }
            } catch (ParserConfigurationException e) {
                throw new RemoteAdminException("Unable to parse the Convertigo server response: \n" + e.getMessage() + ".\n" + "Received response: " + httpResponse);
            } catch (IOException e) {
                throw new RemoteAdminException("An unexpected error has occured during the Convertigo project deployment.\n" + "(IOException) " + e.getMessage() + "\n" + "Received response: " + httpResponse, e);
            } catch (SAXException e) {
                throw new RemoteAdminException("Unable to parse the Convertigo server response: " + e.getMessage() + ".\n" + "Received response: " + httpResponse);
            }
        } else {
            decodeResponseError(httpResponse);
        }
    } catch (HttpException e) {
        throw new RemoteAdminException("An unexpected error has occured during the Convertigo project deployment.\n" + "Cause: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new RemoteAdminException("Unable to reach the Convertigo server: \n" + "(IOException) " + e.getMessage(), e);
    } catch (Exception e) {
        throw new RemoteAdminException("Unable to reach the Convertigo server: \n" + "(Exception) " + e.getMessage(), e);
    } finally {
        Protocol.unregisterProtocol("https");
        if (deployMethod != null)
            deployMethod.releaseConnection();
    }
}
Also used : InputSource(org.xml.sax.InputSource) PostMethod(org.apache.commons.httpclient.methods.PostMethod) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) IOException(java.io.IOException) Document(org.w3c.dom.Document) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) GeneralSecurityException(java.security.GeneralSecurityException) HttpException(org.apache.commons.httpclient.HttpException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) EngineException(com.twinsoft.convertigo.engine.EngineException) SAXException(org.xml.sax.SAXException) EasySSLProtocolSocketFactory(org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory) ProtocolSocketFactory(org.apache.commons.httpclient.protocol.ProtocolSocketFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) StringReader(java.io.StringReader) HttpException(org.apache.commons.httpclient.HttpException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Protocol(org.apache.commons.httpclient.protocol.Protocol)

Example 53 with MultipartRequestEntity

use of org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity 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();
    }
}
Also used : RequestableHttpVariable(com.twinsoft.convertigo.beans.variables.RequestableHttpVariable) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) HttpMethodType(com.twinsoft.convertigo.engine.enums.HttpMethodType) PostMethod(org.apache.commons.httpclient.methods.PostMethod) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) FileNotFoundException(java.io.FileNotFoundException) URL(java.net.URL) AbstractHttpTransaction(com.twinsoft.convertigo.beans.transactions.AbstractHttpTransaction) HeadMethod(org.apache.commons.httpclient.methods.HeadMethod) OptionsMethod(org.apache.commons.httpclient.methods.OptionsMethod) MimeMultipart(javax.mail.internet.MimeMultipart) BigMimeMultipart(com.twinsoft.convertigo.engine.util.BigMimeMultipart) Protocol(org.apache.commons.httpclient.protocol.Protocol) DeleteMethod(org.apache.commons.httpclient.methods.DeleteMethod) ConnectorEvent(com.twinsoft.convertigo.beans.core.ConnectorEvent) MessagingException(javax.mail.MessagingException) TraceMethod(org.apache.commons.httpclient.methods.TraceMethod) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) RequestableVariable(com.twinsoft.convertigo.beans.variables.RequestableVariable) IOException(java.io.IOException) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) LinkedList(java.util.LinkedList) URIException(org.apache.commons.httpclient.URIException) SocketTimeoutException(java.net.SocketTimeoutException) OAuthException(oauth.signpost.exception.OAuthException) IOException(java.io.IOException) JSONException(org.codehaus.jettison.json.JSONException) MessagingException(javax.mail.MessagingException) FileNotFoundException(java.io.FileNotFoundException) EngineException(com.twinsoft.convertigo.engine.EngineException) MalformedURLException(java.net.MalformedURLException) FileRequestEntity(org.apache.commons.httpclient.methods.FileRequestEntity) DownloadHttpTransaction(com.twinsoft.convertigo.beans.transactions.DownloadHttpTransaction) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) MimePart(javax.mail.internet.MimePart) Part(org.apache.commons.httpclient.methods.multipart.Part) MimeBodyPart(javax.mail.internet.MimeBodyPart) GetMethod(org.apache.commons.httpclient.methods.GetMethod) PutMethod(org.apache.commons.httpclient.methods.PutMethod) Collection(java.util.Collection) MimeBodyPart(javax.mail.internet.MimeBodyPart) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) FileRequestEntity(org.apache.commons.httpclient.methods.FileRequestEntity) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) File(java.io.File) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 54 with MultipartRequestEntity

use of org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity in project alfresco-repository by Alfresco.

the class HttpClientTransmitterImpl method sendContent.

/**
 */
public void sendContent(Transfer transfer, Set<ContentData> data) throws TransferException {
    if (log.isDebugEnabled()) {
        log.debug("send content to transfer:" + transfer);
    }
    TransferTarget target = transfer.getTransferTarget();
    PostMethod postContentRequest = getPostMethod();
    try {
        HostConfiguration hostConfig = getHostConfig(target);
        HttpState httpState = getHttpState(target);
        try {
            postContentRequest.setPath(target.getEndpointPath() + "/post-content");
            // Put the transferId on the query string
            postContentRequest.setQueryString(new NameValuePair[] { new NameValuePair("transferId", transfer.getTransferId()) });
            // Put the transferId on the query string
            postContentRequest.setQueryString(new NameValuePair[] { new NameValuePair("transferId", transfer.getTransferId()) });
            Part[] parts = new Part[data.size()];
            int index = 0;
            for (ContentData content : data) {
                String contentUrl = content.getContentUrl();
                String fileName = TransferCommons.URLToPartName(contentUrl);
                log.debug("content partName: " + fileName);
                parts[index++] = new ContentDataPart(getContentService(), fileName, content);
            }
            MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts, postContentRequest.getParams());
            postContentRequest.setRequestEntity(requestEntity);
            int responseStatus = httpClient.executeMethod(hostConfig, postContentRequest, httpState);
            checkResponseStatus("sendContent", responseStatus, postContentRequest);
            if (log.isDebugEnabled()) {
                log.debug("sent content");
            }
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            String error = "Failed to execute HTTP request to target";
            log.debug(error, e);
            throw new TransferException(MSG_HTTP_REQUEST_FAILED, new Object[] { "sendContent", target.toString(), e.toString() }, e);
        }
    } finally {
        postContentRequest.releaseConnection();
    }
}
Also used : NameValuePair(org.apache.commons.httpclient.NameValuePair) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HostConfiguration(org.apache.commons.httpclient.HostConfiguration) HttpState(org.apache.commons.httpclient.HttpState) TransferTarget(org.alfresco.service.cmr.transfer.TransferTarget) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) TransferException(org.alfresco.service.cmr.transfer.TransferException) IOException(java.io.IOException) TransferException(org.alfresco.service.cmr.transfer.TransferException) ContentData(org.alfresco.service.cmr.repository.ContentData) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) JSONObject(org.json.JSONObject)

Example 55 with MultipartRequestEntity

use of org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity in project alfresco-repository by Alfresco.

the class HttpClientTransmitterImpl method sendManifest.

public void sendManifest(Transfer transfer, File manifest, OutputStream result) throws TransferException {
    TransferTarget target = transfer.getTransferTarget();
    PostMethod postSnapshotRequest = getPostMethod();
    MultipartRequestEntity requestEntity;
    if (log.isDebugEnabled()) {
        log.debug("does manifest exist? " + manifest.exists());
        log.debug("sendManifest file : " + manifest.getAbsoluteFile());
    }
    try {
        HostConfiguration hostConfig = getHostConfig(target);
        HttpState httpState = getHttpState(target);
        try {
            postSnapshotRequest.setPath(target.getEndpointPath() + "/post-snapshot");
            // Put the transferId on the query string
            postSnapshotRequest.setQueryString(new NameValuePair[] { new NameValuePair("transferId", transfer.getTransferId()) });
            // TODO encapsulate the name of the manifest part
            // And add the manifest file as a "part"
            Part file = new FilePart(TransferCommons.PART_NAME_MANIFEST, manifest);
            requestEntity = new MultipartRequestEntity(new Part[] { file }, postSnapshotRequest.getParams());
            postSnapshotRequest.setRequestEntity(requestEntity);
            int responseStatus = httpClient.executeMethod(hostConfig, postSnapshotRequest, httpState);
            checkResponseStatus("sendManifest", responseStatus, postSnapshotRequest);
            InputStream is = postSnapshotRequest.getResponseBodyAsStream();
            final ReadableByteChannel inputChannel = Channels.newChannel(is);
            final WritableByteChannel outputChannel = Channels.newChannel(result);
            try {
                // copy the channels
                channelCopy(inputChannel, outputChannel);
            } finally {
                inputChannel.close();
                outputChannel.close();
            }
            return;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            String error = "Failed to execute HTTP request to target";
            log.debug(error, e);
            throw new TransferException(MSG_HTTP_REQUEST_FAILED, new Object[] { "sendManifest", target.toString(), e.toString() }, e);
        }
    } finally {
        postSnapshotRequest.releaseConnection();
    }
}
Also used : NameValuePair(org.apache.commons.httpclient.NameValuePair) ReadableByteChannel(java.nio.channels.ReadableByteChannel) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HostConfiguration(org.apache.commons.httpclient.HostConfiguration) InputStream(java.io.InputStream) HttpState(org.apache.commons.httpclient.HttpState) WritableByteChannel(java.nio.channels.WritableByteChannel) TransferTarget(org.alfresco.service.cmr.transfer.TransferTarget) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) TransferException(org.alfresco.service.cmr.transfer.TransferException) IOException(java.io.IOException) TransferException(org.alfresco.service.cmr.transfer.TransferException) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) JSONObject(org.json.JSONObject)

Aggregations

MultipartRequestEntity (org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity)63 Part (org.apache.commons.httpclient.methods.multipart.Part)54 PostMethod (org.apache.commons.httpclient.methods.PostMethod)53 FilePart (org.apache.commons.httpclient.methods.multipart.FilePart)52 StringPart (org.apache.commons.httpclient.methods.multipart.StringPart)44 IOException (java.io.IOException)24 HttpClient (org.apache.commons.httpclient.HttpClient)20 File (java.io.File)16 ArrayList (java.util.ArrayList)16 HttpMethodParams (org.apache.commons.httpclient.params.HttpMethodParams)9 Test (org.junit.Test)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 ByteArrayPartSource (org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource)7 GetMethod (org.apache.commons.httpclient.methods.GetMethod)6 Element (org.jdom.Element)6 HttpException (org.apache.commons.httpclient.HttpException)5 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)5 Map (java.util.Map)4 Header (org.apache.commons.httpclient.Header)4 NameValuePair (org.apache.commons.httpclient.NameValuePair)4