Example usage for org.apache.commons.httpclient HttpStatus SC_ACCEPTED

List of usage examples for org.apache.commons.httpclient HttpStatus SC_ACCEPTED

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_ACCEPTED.

Prototype

int SC_ACCEPTED

To view the source code for org.apache.commons.httpclient HttpStatus SC_ACCEPTED.

Click Source Link

Document

<tt>202 Accepted</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:org.apache.maven.wagon.shared.http.AbstractHttpClientWagon.java

private void put(final InputStream stream, Resource resource, File source)
        throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException {
    String url = getRepository().getUrl();
    String[] parts = StringUtils.split(resource.getName(), "/");
    for (int i = 0; i < parts.length; i++) {
        // TODO: Fix encoding...
        // url += "/" + URLEncoder.encode( parts[i], System.getProperty("file.encoding") );
        url += "/" + URLEncoder.encode(parts[i]);
    }//from w  ww  . j a  v  a  2  s.  c  o m

    //Parent directories need to be created before posting
    try {
        mkdirs(PathUtils.dirname(resource.getName()));
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);
    }

    PutMethod putMethod = new PutMethod(url);

    firePutStarted(resource, source);

    try {
        putMethod.setRequestEntity(new RequestEntityImplementation(stream, resource, this, source));

        int statusCode;
        try {
            statusCode = execute(putMethod);
        } catch (IOException e) {
            fireTransferError(resource, e, TransferEvent.REQUEST_PUT);

            throw new TransferFailedException(e.getMessage(), e);
        }

        fireTransferDebug(url + " - Status code: " + statusCode);

        // Check that we didn't run out of retries.
        switch (statusCode) {
        // Success Codes
        case HttpStatus.SC_OK: // 200
        case HttpStatus.SC_CREATED: // 201
        case HttpStatus.SC_ACCEPTED: // 202
        case HttpStatus.SC_NO_CONTENT: // 204
            break;

        case SC_NULL: {
            TransferFailedException e = new TransferFailedException("Failed to transfer file: " + url);
            fireTransferError(resource, e, TransferEvent.REQUEST_PUT);
            throw e;
        }

        case HttpStatus.SC_FORBIDDEN:
            fireSessionConnectionRefused();
            throw new AuthorizationException("Access denied to: " + url);

        case HttpStatus.SC_NOT_FOUND:
            throw new ResourceDoesNotExistException("File: " + url + " does not exist");

            //add more entries here
        default: {
            TransferFailedException e = new TransferFailedException(
                    "Failed to transfer file: " + url + ". Return code is: " + statusCode);
            fireTransferError(resource, e, TransferEvent.REQUEST_PUT);
            throw e;
        }
        }

        firePutCompleted(resource, source);
    } finally {
        putMethod.releaseConnection();
    }
}

From source file:org.apache.servicemix.http.endpoints.DefaultHttpProviderMarshaler.java

public void handleResponse(MessageExchange exchange, SmxHttpExchange httpExchange) throws Exception {
    int response = httpExchange.getResponseStatus();
    if (response != HttpStatus.SC_OK && response != HttpStatus.SC_ACCEPTED) {
        if (!(exchange instanceof InOnly)) {
            Fault fault = exchange.createFault();
            fault.setContent(new StreamSource(httpExchange.getResponseReader()));
            exchange.setFault(fault);/*  w w  w  .ja va 2 s  .  c o  m*/
        } else {
            throw new Exception("Invalid status response: " + response);
        }
    } else if (exchange instanceof InOut) {
        NormalizedMessage msg = exchange.createMessage();
        msg.setContent(new StreamSource(httpExchange.getResponseReader()));
        exchange.setMessage(msg, "out");
    } else if (exchange instanceof InOptionalOut) {
        Reader r = httpExchange.getResponseReader();
        if (r != null) {
            NormalizedMessage msg = exchange.createMessage();
            msg.setContent(new StreamSource(r));
            exchange.setMessage(msg, "out");
        } else {
            exchange.setStatus(ExchangeStatus.DONE);
        }
    } else {
        exchange.setStatus(ExchangeStatus.DONE);

    }
}

From source file:org.apache.servicemix.http.processors.ProviderProcessor.java

public void process(MessageExchange exchange) throws Exception {
    if (exchange.getStatus() == ExchangeStatus.DONE || exchange.getStatus() == ExchangeStatus.ERROR) {
        PostMethod method = methods.remove(exchange.getExchangeId());
        if (method != null) {
            method.releaseConnection();/* w  w  w . j av a 2s .  co  m*/
        }
        return;
    }
    boolean txSync = exchange.isTransacted()
            && Boolean.TRUE.equals(exchange.getProperty(JbiConstants.SEND_SYNC));
    txSync |= endpoint.isSynchronous();
    NormalizedMessage nm = exchange.getMessage("in");
    if (nm == null) {
        throw new IllegalStateException("Exchange has no input message");
    }

    String locationURI = endpoint.getLocationURI();

    // Incorporated because of JIRA SM-695
    Object newDestinationURI = nm.getProperty(JbiConstants.HTTP_DESTINATION_URI);
    if (newDestinationURI != null) {
        locationURI = (String) newDestinationURI;
        log.debug("Location URI overridden: " + locationURI);
    }

    PostMethod method = new PostMethod(getRelUri(locationURI));
    SoapMessage soapMessage = new SoapMessage();
    soapHelper.getJBIMarshaler().fromNMS(soapMessage, nm);
    Context context = soapHelper.createContext(soapMessage);
    soapHelper.onSend(context);
    SoapWriter writer = soapHelper.getSoapMarshaler().createWriter(soapMessage);
    copyHeaderInformation(nm, method);
    RequestEntity entity = writeMessage(writer);
    // remove content-type header that may have been part of the in message
    if (!endpoint.isWantContentTypeHeaderFromExchangeIntoHttpRequest()) {
        method.removeRequestHeader(HEADER_CONTENT_TYPE);
        method.addRequestHeader(HEADER_CONTENT_TYPE, entity.getContentType());
    }
    if (entity.getContentLength() < 0) {
        method.removeRequestHeader(HEADER_CONTENT_LENGTH);
    } else {
        method.setRequestHeader(HEADER_CONTENT_LENGTH, Long.toString(entity.getContentLength()));
    }
    if (endpoint.isSoap() && method.getRequestHeader(HEADER_SOAP_ACTION) == null) {
        if (endpoint.getSoapAction() != null) {
            method.setRequestHeader(HEADER_SOAP_ACTION, endpoint.getSoapAction());
        } else {
            //                method.setRequestHeader(HEADER_SOAP_ACTION, "\"\"");
        }
    }
    method.setRequestHeader(HEADER_X_CORRELATION_ID,
            (String) exchange.getProperty(JbiConstants.CORRELATION_ID));
    String smxInstanceName = System.getProperty(SMX_INSTANCE_NAME_PROPERTY);
    if (smxInstanceName != null) {
        method.setRequestHeader(HEADER_X_POWERED_BY, smxInstanceName);
    } else {
        log.warn(SMX_INSTANCE_NAME_PROPERTY + " property was not set in servicemix.xml file");
    }

    method.setRequestEntity(entity);
    boolean close = true;
    try {
        // Set the retry handler
        int retries = getConfiguration().isStreamingEnabled() ? 0 : getConfiguration().getRetryCount();
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(retries, true));
        // Set authentication
        if (endpoint.getBasicAuthentication() != null) {
            endpoint.getBasicAuthentication().applyCredentials(getClient(), exchange, nm);
        }
        // Execute the HTTP method
        //method.getParams().setLongParameter(HttpConnectionParams.CONNECTION_TIMEOUT, getClient().getParams().getSoTimeout());

        int response = -1;
        try {
            response = getClient().executeMethod(getHostConfiguration(locationURI, exchange, nm), method);
        } catch (Exception ex) {
            try {
                if (listener != null) {
                    if (ex instanceof SocketException) {
                        log.error("Connection to address: " + locationURI + " was refused");
                        listener.onConnectionRefused(locationURI);
                    } else if (ex instanceof SocketTimeoutException) {
                        log.error("Connection to address: " + locationURI + " timed out");
                        listener.onTimeout(locationURI);
                    }
                }
            } catch (Exception ex2) {
                log.warn("Error in HttpConnectionListener: " + ex2.getMessage());
            } finally {
                throw ex;
            }
        }
        try {
            if (listener != null) {
                listener.onPostExecuted(locationURI, response);
            }
        } catch (Exception ex) {
            log.warn("Error in HttpConnectionListener: " + ex.getMessage());
        }
        if (response != HttpStatus.SC_OK && response != HttpStatus.SC_ACCEPTED) {
            if (!(exchange instanceof InOnly)) {
                SoapReader reader = soapHelper.getSoapMarshaler().createReader();
                Header contentType = method.getResponseHeader(HEADER_CONTENT_TYPE);
                String content = convertResponseBodyToString(method);
                logInOut(locationURI, response, method, soapMessage, content);
                soapMessage = reader.read(new ByteArrayInputStream(content.getBytes()),
                        contentType != null ? contentType.getValue() : null);
                context.setFaultMessage(soapMessage);
                soapHelper.onAnswer(context);
                Fault fault = exchange.createFault();
                fault.setProperty(JbiConstants.PROTOCOL_HEADERS, getHeaders(method));
                soapHelper.getJBIMarshaler().toNMS(fault, soapMessage);
                exchange.setFault(fault);
                if (txSync) {
                    channel.sendSync(exchange);
                } else {
                    methods.put(exchange.getExchangeId(), method);
                    channel.send(exchange);
                    close = false;
                }
                return;
            } else {
                String content = convertResponseBodyToString(method);
                // even if it is InOnly, some out could come to us
                logInOut(locationURI, response, method, soapMessage, content);
                throw new Exception("Invalid status response: " + response);
            }
        }
        if (exchange instanceof InOut) {
            close = processInOut(exchange, method, context, txSync, close);
        } else if (exchange instanceof InOptionalOut) {
            close = processInOptionalOut(method, exchange, context, txSync, close);
        } else {
            exchange.setStatus(ExchangeStatus.DONE);
            channel.send(exchange);
        }
    } finally {
        if (close) {
            method.releaseConnection();
        }
    }
}

From source file:org.apache.synapse.mediators.json.SynapseJsonSender.java

public InvocationResponse invoke(MessageContext msgContext) throws AxisFault {
    //Fix Me For Sending Only
    // Trasnport URL can be different from the WSA-To. So processing
    // that now./*ww w  .j a v  a 2  s . com*/
    EndpointReference epr = null;
    String transportURL = (String) msgContext.getProperty(Constants.Configuration.TRANSPORT_URL);

    if (transportURL != null) {
        epr = new EndpointReference(transportURL);
    } else if ((msgContext.getTo() != null)
            && !AddressingConstants.Submission.WSA_ANONYMOUS_URL.equals(msgContext.getTo().getAddress())
            && !AddressingConstants.Final.WSA_ANONYMOUS_URL.equals(msgContext.getTo().getAddress())) {
        epr = msgContext.getTo();
    }

    if (epr == null) {
        throw new AxisFault("EndpointReference is not available");
    }

    // Get the JSONObject
    JSONObject jsonObject = (JSONObject) msgContext.getProperty("JSONObject");
    if (jsonObject == null) {
        throw new AxisFault("Couldn't Find JSONObject");

    }
    HttpClient agent = new HttpClient();
    PostMethod postMethod = new PostMethod(epr.getAddress());
    try {
        postMethod.setRequestEntity(new ByteArrayRequestEntity(XML.toString(jsonObject).getBytes()));
        agent.executeMethod(postMethod);

        if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
            processResponse(postMethod, msgContext);
        } else if (postMethod.getStatusCode() == HttpStatus.SC_ACCEPTED) {
        } else if (postMethod.getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            Header contenttypeHheader = postMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE);
            String value = contenttypeHheader.getValue();

            if (value != null) {
                if ((value.indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) >= 0)
                        || (value.indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) >= 0)) {
                    processResponse(postMethod, msgContext);
                }
            }
        } else {
            throw new AxisFault(Messages.getMessage("transportError",
                    String.valueOf(postMethod.getStatusCode()), postMethod.getResponseBodyAsString()));
        }
    } catch (JSONException e) {
        log.error(e);
        throw new AxisFault(e);
    } catch (IOException e) {
        log.error(e);
        throw new AxisFault(e);
    }

    return InvocationResponse.CONTINUE;
}

From source file:org.artifactory.rest.resource.plugin.PluginsResource.java

@POST
@Consumes(MediaType.WILDCARD)//from   ww  w .jav a 2 s . co  m
@Path(PATH_EXECUTE + "/{executionName: .+}")
@Produces(MediaType.TEXT_PLAIN)
public Response execute(InputStream body, @PathParam("executionName") String executionName,
        @QueryParam(PARAM_PARAMS) KeyValueList paramsList, @QueryParam(PARAM_ASYNC) int async)
        throws Exception {
    Map<String, List<String>> params = paramsList != null ? paramsList.toStringMap()
            : Maps.<String, List<String>>newHashMap();
    try (ResourceStreamHandle handle = new SimpleResourceStreamHandle(body)) {
        ResponseCtx responseCtx = addonsManager.addonByType(RestAddon.class).runPluginExecution(executionName,
                params, handle, async == 1);
        if (async == 1) {
            //Just return accepted (202)
            return Response.status(HttpStatus.SC_ACCEPTED).build();
        } else {
            return responseFromResponseCtx(responseCtx);
        }
    }
}

From source file:org.dataconservancy.dcs.access.server.FileUploadServlet.java

private void uploadfile(String depositurl, String filename, InputStream is, HttpServletResponse resp)
        throws IOException {
    /*    File tmp = null;
        FileOutputStream fos = null;/*from  w  w  w  .  j a  v a2s  .  c  om*/
        PostMethod post = null;
            
        //System.out.println(filename + " -> " + depositurl);
    */
    try {
        /*      tmp = File.createTempFile("fileupload", null);
              fos = new FileOutputStream(tmp);
              FileUtil.copy(is, fos);
                
             HttpClient client = new HttpClient();
                
              post = new PostMethod(depositurl);
                
              Part[] parts = {new FilePart(filename, tmp)};
                
             post.setRequestEntity(new MultipartRequestEntity(parts, post
            .getParams()));
            */
        org.apache.http.client.HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(depositurl);

        InputStreamEntity data = new InputStreamEntity(is, -1);
        data.setContentType("binary/octet-stream");
        data.setChunked(false);
        post.setEntity(data);

        HttpResponse response = client.execute(post);
        System.out.println(response.toString());
        int status = 202;//response.getStatusLine();
        // int status = client.executeMethod(post);

        if (status == HttpStatus.SC_ACCEPTED || status == HttpStatus.SC_CREATED) {
            resp.setStatus(status);

            String src = response.getHeaders("X-dcs-src")[0].getValue();
            String atomurl = response.getHeaders("Location")[0].getValue();

            resp.setContentType("text/html");
            resp.getWriter().print("<html><body><p>^" + src + "^" + atomurl + "^</p></body></html>");
            resp.flushBuffer();
        } else {
            resp.sendError(status, response.getStatusLine().toString());
            return;
        }
    } finally {
        /* if (tmp != null) {
        tmp.delete();
         }
                 
         if (is != null) {
        is.close();
         }
                
         if (fos != null) {
        fos.close();
         }
                
         if (post != null) {
        post.releaseConnection();
         }*/
    }
}

From source file:org.dataconservancy.dcs.ingest.ui.server.FileUploadServlet.java

private void uploadfile(String depositurl, String filename, InputStream is, HttpServletResponse resp)
        throws IOException {
    File tmp = null;//from   w  w w.  ja  v a2s .  co m
    FileOutputStream fos = null;
    PostMethod post = null;

    //System.out.println(filename + " -> " + depositurl);

    try {
        tmp = File.createTempFile("fileupload", null);
        fos = new FileOutputStream(tmp);
        FileUtil.copy(is, fos);

        HttpClient client = new HttpClient();

        post = new PostMethod(depositurl);

        Part[] parts = { new FilePart(filename, tmp) };

        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        int status = client.executeMethod(post);

        if (status == HttpStatus.SC_ACCEPTED || status == HttpStatus.SC_CREATED) {
            resp.setStatus(status);

            String src = post.getResponseHeader("X-dcs-src").getValue();
            String atomurl = post.getResponseHeader("Location").getValue();

            resp.setContentType("text/html");
            resp.getWriter().print("<html><body><p>^" + src + "^" + atomurl + "^</p></body></html>");
            resp.flushBuffer();
        } else {
            resp.sendError(status, post.getStatusText());
            return;
        }
    } finally {
        if (tmp != null) {
            tmp.delete();
        }

        if (is != null) {
            is.close();
        }

        if (fos != null) {
            fos.close();
        }

        if (post != null) {
            post.releaseConnection();
        }
    }
}

From source file:org.dcm4chex.archive.hsm.module.castor.CAStorHSMModule.java

/**
 * The method that is called by the FileCopy service to copy a study tarball
 * to nearline storage (i.e. CAStor)./*from www .  j a v a2  s  .c  o m*/
 * 
 * @param file
 *            The tar file to copy.
 * @param fsID
 *            The file system ID for nearline storage.
 * @param filePath
 *            The relative path to the study tarball in online storage.
 * @return The relative path to the study files in nearline storage.
 * @throws HSMException
 */
@Override
public String storeHSMFile(File file, String fsID, String filePath) throws HSMException {
    logger.debug("storeHSMFile called with file=" + file + ", fsID=" + fsID + ", filePath=" + filePath);

    // Open the tar file in read mode
    ResettableFileInputStream fis = null;
    try {
        fis = new ResettableFileInputStream(file);
    } catch (IOException e) {
        throw new HSMException("Could not open file " + file, e);
    }

    String newFilePath = null;
    ScspHeaders scspHeaders = new ScspHeaders();
    addStudyLifepoint(scspHeaders, file, filePath);

    logger.info("Uploading " + file + " to CAStor");

    // Read the tar file and write the data to the CAStor object
    try {
        if (client == null) {
            createClient();
        }

        ScspResponse response = client.write("", fis, file.length(), new ScspQueryArgs(), scspHeaders);
        switch (response.getHttpStatusCode()) {
        case HttpStatus.SC_CREATED:
        case HttpStatus.SC_ACCEPTED:
            newFilePath = extractUUIDFromScspResponse(response);
            break;

        default:
            logger.error("Unexpected WRITE response: " + response.toString());
        }
    } catch (ScspExecutionException e) {
        throw new HSMException("Could not upload " + file + " to CAStor", e);
    } catch (Exception e) {
        throw new HSMException("Could not store " + filePath + " in nearline storage", e);
    } finally {
        // Always close the opened file
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                logger.error("Could not close input stream for " + file, e);
            }
        }

        // Delete the temporary tar file
        if (!file.delete()) {
            logger.warn("Could not delete temporary file: " + file);
        }
    }

    return newFilePath;
}

From source file:org.eclipse.osee.framework.core.util.HttpProcessor.java

public static AcquireResult delete(URL url, String xml, String contentType, String encoding,
        OutputStream outputStream) throws OseeCoreException {
    AcquireResult result = new AcquireResult();
    int statusCode = -1;

    org.eclipse.osee.framework.core.util.DeleteMethod method = new DeleteMethod(url.toString());

    InputStream httpInputStream = null;
    try {//  w  ww . j  av a 2  s.c  o m
        method.setRequestHeader(CONTENT_ENCODING, encoding);
        method.setRequestEntity(new InputStreamRequestEntity(Lib.stringToInputStream(xml), contentType));

        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        statusCode = executeMethod(url, method);
        httpInputStream = method.getResponseBodyAsStream();
        result.setContentType(getContentType(method));
        result.setEncoding(method.getResponseCharSet());
        if (statusCode == HttpStatus.SC_ACCEPTED || statusCode == HttpStatus.SC_OK) {
            Lib.inputStreamToOutputStream(httpInputStream, outputStream);
        } else {
            String exceptionString = Lib.inputStreamToString(httpInputStream);
            throw new OseeCoreException(exceptionString);
        }
    } catch (Exception ex) {
        OseeExceptions.wrapAndThrow(ex);
    } finally {
        Lib.close(httpInputStream);
        result.setCode(statusCode);
        method.releaseConnection();
    }
    return result;
}

From source file:org.eclipse.osee.framework.core.util.HttpProcessor.java

public static AcquireResult post(URL url, InputStream inputStream, String contentType, String encoding,
        OutputStream outputStream) throws OseeCoreException {
    AcquireResult result = new AcquireResult();
    int statusCode = -1;

    PostMethod method = new PostMethod(url.toString());

    InputStream httpInputStream = null;
    try {/*  www  . j av a 2s  .c om*/
        method.setRequestHeader(CONTENT_ENCODING, encoding);
        method.setRequestEntity(new InputStreamRequestEntity(inputStream, contentType));

        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        statusCode = executeMethod(url, method);
        httpInputStream = method.getResponseBodyAsStream();
        result.setContentType(getContentType(method));
        result.setEncoding(method.getResponseCharSet());
        if (statusCode == HttpStatus.SC_ACCEPTED || statusCode == HttpStatus.SC_OK) {
            Lib.inputStreamToOutputStream(httpInputStream, outputStream);
        } else {
            String exceptionString = Lib.inputStreamToString(httpInputStream);
            throw new OseeCoreException(exceptionString);
        }
    } catch (Exception ex) {
        OseeExceptions.wrapAndThrow(ex);
    } finally {
        Lib.close(httpInputStream);
        result.setCode(statusCode);
        method.releaseConnection();
    }
    return result;
}