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

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

Introduction

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

Prototype

int SC_NO_CONTENT

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

Click Source Link

Document

<tt>204 No Content</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:io.fabric8.gateway.servlet.ProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link javax.servlet.http.HttpServletResponse}
 *
 * @param proxyDetails//from   w ww . ja  va  2s .c o m
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse    An object by which we can send the proxied
 *                               response back to the client
 * @throws java.io.IOException            Can be thrown by the {@link HttpClient}.executeMethod
 * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred
 */
private void executeProxyRequest(ProxyDetails proxyDetails, HttpMethod httpMethodProxyRequest,
        HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws IOException, ServletException {
    httpMethodProxyRequest.setDoAuthentication(false);
    httpMethodProxyRequest.setFollowRedirects(false);

    // Create a default HttpClient
    HttpClient httpClient = proxyDetails.createHttpClient(httpMethodProxyRequest);

    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
            && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no "
                    + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        httpServletResponse.sendRedirect(stringLocation
                .replace(proxyDetails.getProxyHostAndPort() + proxyDetails.getProxyPath(), stringMyHostName));
        return;
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        if (!ProxySupport.isHopByHopHeader(header.getName())) {
            if (ProxySupport.isSetCookieHeader(header)) {
                HttpProxyRule proxyRule = proxyDetails.getProxyRule();
                String setCookie = ProxySupport.replaceCookieAttributes(header.getValue(),
                        proxyRule.getCookiePath(), proxyRule.getCookieDomain());
                httpServletResponse.setHeader(header.getName(), setCookie);
            } else {
                httpServletResponse.setHeader(header.getName(), header.getValue());
            }
        }
    }

    // check if we got data, that is either the Content-Length > 0
    // or the response code != 204
    int code = httpMethodProxyRequest.getStatusCode();
    boolean noData = code == HttpStatus.SC_NO_CONTENT;
    if (!noData) {
        String length = httpServletRequest.getHeader(STRING_CONTENT_LENGTH_HEADER_NAME);
        if (length != null && "0".equals(length.trim())) {
            noData = true;
        }
    }
    LOG.trace("Response has data? {}", !noData);

    if (!noData) {
        // Send the content to the client
        InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse);
        OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
        int intNextByte;
        while ((intNextByte = bufferedInputStream.read()) != -1) {
            outputStreamClientResponse.write(intNextByte);
        }
    }
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testPostOperation1() throws Exception {
    String url = URL_RESOURCE1 + "/pathPostOperation1";
    PostMethod method = new PostMethod(url);

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_NO_CONTENT);
    byte[] responseBody = method.getResponseBody();
    assertNull(responseBody);/*from   www . j  a va  2  s .co  m*/
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testPostOperation2() throws Exception {
    String url = URL_RESOURCE1 + "/pathPostOperation2";
    PostMethod method = new PostMethod(url);
    String param = "this is string parameter!";
    method.setRequestEntity(new StringRequestEntity(param, "application/xml", null));

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_NO_CONTENT);
    byte[] responseBody = method.getResponseBody();
    assertNull(responseBody);//from   ww w. jav a2 s  .c o m
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testPostOperation5Xml() throws Exception {
    String url = URL_RESOURCE1 + "/pathPostOperation5Xml";
    PostMethod method = new PostMethod(url);
    String param = this.getXmlCd();
    method.setRequestEntity(new StringRequestEntity(param, "application/xml", null));

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_NO_CONTENT);
    byte[] responseBody = method.getResponseBody();
    assertNull(responseBody);//from w  w w  .j a v a  2  s .  c om
}

From source file:com.silverwrist.venice.std.TrackbackManager.java

/**
 * Loads the HTTP content at the specified URL, scans it for RDF description blocks, and adds those blocks
 * as {@link com.silverwrist.venice.std.TrackbackItem TrackbackItem}s to our internal cache.  Uses modification
 * detection to keep from reloading a page unless necessary.
 *
 * @param url The URL of the resource to be loaded.
 * @param attrs The attributes of the specified page; if this is <code>null</code>, we'll check the page
 *              cache for the right attributes.
 * @return <code>true</code> if the page data was loaded and scanned for trackback items; <code>false</code>
 *         if no data was loaded (because it was not modified since the last time we loaded it, for instance).
 * @exception com.silverwrist.venice.except.TrackbackException If there was an error loading or interpreting
 *            the page data./* ww  w  .ja v a 2  s . c  o m*/
 */
private synchronized boolean load(URL url, PageAttributes attrs) throws TrackbackException {
    if (attrs == null)
        attrs = (PageAttributes) (m_page_cache.get(url));

    // Create the GET method and set its headers.
    String s = url.toString();
    int x = s.lastIndexOf('#');
    if (x >= 0)
        s = s.substring(0, x);
    GetMethod getter = new GetMethod(s);
    HttpMethodParams params = getter.getParams();
    getter.setDoAuthentication(false);
    getter.setFollowRedirects(true);
    getter.setRequestHeader("User-Agent", USER_AGENT);
    getter.setRequestHeader("Accept", "text/*");
    getter.setRequestHeader("Accept-Encoding", "identity");
    params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    getter.setParams(params);

    boolean get_resp = false;
    PageAttributes newattrs = null;
    ContentType ctype = null;
    byte[] rawdata = null;
    try { // set the Last-Modified date as an If-Modified-Since header on the request
        java.util.Date lmod = null;
        if (attrs != null)
            lmod = attrs.getLastModified();
        if (lmod != null)
            getter.setRequestHeader("If-Modified-Since", s_httpdate_format.format(lmod));

        // execute the Get method!
        int rc = m_http_client.executeMethod(getter);
        get_resp = true;
        if ((lmod != null) && (rc == HttpStatus.SC_NOT_MODIFIED))
            return false; // we were not modified
        if (rc == HttpStatus.SC_NO_CONTENT)
            return false; // there's no content there
        if (rc != HttpStatus.SC_OK) // this is farked!
            throw new TrackbackException("GET of " + url + " returned " + rc);

        // Get the new page attributes and save them off.
        newattrs = new PageAttributes(getter);
        m_page_cache.put(url, newattrs);

        // Get the Content-Type header and see if it's valid.
        Header hdr = getter.getResponseHeader("Content-Type");
        if (hdr != null)
            s = hdr.getValue();
        else
            s = "text/plain"; // necessary assumption
        ctype = new ContentType(s);
        if (!(ctype.getPrimaryType().equals("text")))
            throw new TrackbackException("URL " + url + " does not point to a text-based resource");

        // Load the resource in as byte data; we will determine the right character set for it later.
        rawdata = getter.getResponseBody();
        get_resp = false;

    } // end try
    catch (IOException e) { // IO error getting the page
        throw new TrackbackException("I/O error retrieving " + url + ": " + e.getMessage(), e);

    } // end catch
    catch (javax.mail.internet.ParseException e) { // translate into TrackbackException
        throw new TrackbackException("invalid Content-Type received for URL " + url, e);

    } // end catch
    finally { // release the connection if possible
        try { // need to get the message body
            if (get_resp)
                getter.getResponseBody();

        } // end try
        catch (IOException e) { // ignore these
        } // end catch

        getter.releaseConnection();

    } // end finally

    // make a first guess at the charset from the HTTP header Content-Type
    String cset = ctype.getParameter("charset");
    if (cset == null)
        cset = "US-ASCII";
    String content = null;
    try { // interpret the content
        content = new String(rawdata, cset);

    } // end try
    catch (UnsupportedEncodingException e) { // fall back and try just using US-ASCII
        cset = null;
        try { // interpret the content
            content = new String(rawdata, "US-ASCII");

        } // end try
        catch (UnsupportedEncodingException e2) { // can't happen
            logger.debug("WTF? US-ASCII should damn well be a supported character set!", e2);

        } // end catch

    } // end catch

    // Look for <META HTTP-EQUIV=...> tags in the content.
    Map http_attrs = extractHttpEquivTags(content);

    // Try to get a Content-Type attribute from there.
    s = (String) (http_attrs.get("CONTENT-TYPE"));
    String cset2 = null;
    if (s != null) { // look for the content type
        try { // parse into Content-Type
            ContentType c = new ContentType(s);
            if (c.getPrimaryType().equals("text"))
                cset2 = c.getParameter("charset");

        } // end try
        catch (javax.mail.internet.ParseException e) { // can't get a second Content-Type
            logger.debug("parse of Content-Type from META tags failed", e);
            cset2 = null;

        } // end catch

    } // end if

    if ((cset == null) && (cset2 == null))
        throw new TrackbackException("unable to determine character set for " + url);
    if ((cset2 != null) && ((cset == null) || !(cset.equalsIgnoreCase(cset2)))) { // reinterpret content in new character set
        try { // reinterpret content in new character set
            s = new String(rawdata, cset2);
            content = s;

            // the contents of the HTTP-EQUIV tags may have changed as a result
            http_attrs = extractHttpEquivTags(content);

        } // end try
        catch (UnsupportedEncodingException e) { // just use original character set
            if (cset == null)
                throw new TrackbackException("unable to determine character set for " + url);

        } // end catch

    } // end if

    newattrs.updateFromPage(http_attrs); // update the page attributes from the META tag data

    // Search the page content for RDF blocks.
    RE m = new RE(s_rdf_start, RE.MATCH_NORMAL);
    int pos = 0;
    while (m.match(content, pos)) { // look for the end of this RDF block
        RE m2 = new RE(getEndRecognizer(m.getParen(1)), RE.MATCH_NORMAL);
        if (m2.match(content, m.getParenEnd(0))) { // we now have a block to feed to the XML parser
            try { // run the block through the XML parser
                InputSource isrc = new InputSource(
                        new StringReader(content.substring(m.getParenStart(0), m2.getParenEnd(0))));
                Document doc = m_rdf_parser.parse(isrc);

                // examine topmost element, which should be rdf:RDF
                Element root = doc.getDocumentElement();
                if (NS_RDF.equals(root.getNamespaceURI()) && (root.getLocalName() != null)
                        && root.getLocalName().equals("RDF")) { // this is most definitely an rdf:RDF node...look for rdf:Description nodes under it
                    NodeList nl = root.getChildNodes();
                    for (int i = 0; i < nl.getLength(); i++) { // check each node in the list
                        Node n = nl.item(i);
                        if ((n.getNodeType() == Node.ELEMENT_NODE) && NS_RDF.equals(n.getNamespaceURI())
                                && (n.getLocalName() != null) && n.getLocalName().equals("Description")) { // we've got an rdf:Description node...extract the attributes from it
                            Element elt = (Element) n;
                            try { // look for the item and trackback URLs
                                URL item = null, trackback = null;
                                s = elt.getAttributeNS(NS_DC, "identifier");
                                if ((s != null) && (s.length() > 0))
                                    item = new URL(s);
                                s = elt.getAttributeNS(NS_TRACKBACK, "ping");
                                if ((s != null) && (s.length() > 0))
                                    trackback = new URL(s);
                                if ((item != null) && (trackback != null)) { // create the item
                                    s = elt.getAttributeNS(NS_DC, "title");
                                    m_item_cache.put(item, new MyTrackbackItem(item, trackback, s, newattrs));

                                } // end if

                            } // end try
                            catch (MalformedURLException e) { // this means skip this item
                                logger.warn("URL parse failure", e);

                            } // end catch

                        } // end if

                    } // end for

                } // end if

            } // end try
            catch (IOException e) { // disregard this block
                logger.warn("RDF block parse failure", e);

            } // end catch
            catch (SAXException e) { // disregard this block
                logger.warn("RDF block parse failure", e);

            } // end catch

        } // end if
          // else ignore this possible block

        pos = m.getParenEnd(0);

    } // end while

    return true;

}

From source file:com.intuit.wasabi.api.AssignmentsResource.java

/**
 * Flush all active and queued messages from the ingestion queues.
 *
 * @return Response object// ww  w  . j  a  v a 2 s . c  o  m
 */
@POST
@Path("flushMessages")
@Produces(APPLICATION_JSON)
public Response flushMessages(
        @HeaderParam(AUTHORIZATION) @ApiParam(value = EXAMPLE_AUTHORIZATION_HEADER, required = true) final String authorizationHeader) {
    try {
        Username userName = authorization.getUser(authorizationHeader);
        authorization.checkSuperAdmin(userName);
        assignments.flushMessages();
        return httpHeader.headers(HttpStatus.SC_NO_CONTENT).build();
    } catch (Exception exception) {
        LOGGER.error("flushMessages failed with error:", exception);
        throw exception;
    }
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testPostOperation5Json() throws Exception {
    String url = URL_RESOURCE1 + "/pathPostOperation5Json";
    PostMethod method = new PostMethod(url);
    String param = this.getJsonCd();
    method.setRequestEntity(new StringRequestEntity(param, "application/json", null));

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_NO_CONTENT);
    byte[] responseBody = method.getResponseBody();
    assertNull(responseBody);/*from   w  w  w . j  a v  a  2 s. c o m*/
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

/**
 * Verifies that a 204 status code is returned when the operation returns null.
 *///from  w ww. j ava 2s . com
@Test
public void testPostOperationNull1() throws Exception {
    String url = URL_RESOURCE2 + "/pathPostOperationNull1";
    PostMethod method = new PostMethod(url);

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_NO_CONTENT);
    byte[] responseBody = method.getResponseBody();
    assertNull(responseBody);
}

From source file:com.zimbra.qa.unittest.TestCalDav.java

/**
 *  dav - sending http error 302 because: wrong url - redirecting to:
 *  http://pan.local:7070/dav/dav1@pan.local/Calendar/d123f102-42a7-4283-b025-3376dabe53b3.ics
 *  com.zimbra.cs.dav.DavException: wrong url - redirecting to:
 *  http://pan.local:7070/dav/dav1@pan.local/Calendar/d123f102-42a7-4283-b025-3376dabe53b3.ics
 *      at com.zimbra.cs.dav.resource.CalendarCollection.createItem(CalendarCollection.java:431)
 *      at com.zimbra.cs.dav.service.method.Put.handle(Put.java:49)
 *      at com.zimbra.cs.dav.service.DavServlet.service(DavServlet.java:322)
 *///from  w ww .j av  a 2s.  c  om
@Test
public void testCreateUsingClientChosenName() throws ServiceException, IOException {
    Account dav1 = users[1].create();
    String davBaseName = "clientInvented.now";
    String calFolderUrl = getFolderUrl(dav1, "Calendar");
    String url = String.format("%s%s", calFolderUrl, davBaseName);
    HttpClient client = new HttpClient();
    PutMethod putMethod = new PutMethod(url);
    addBasicAuthHeaderForUser(putMethod, dav1);
    putMethod.addRequestHeader("Content-Type", "text/calendar");

    putMethod.setRequestEntity(new ByteArrayRequestEntity(simpleEvent(dav1), MimeConstants.CT_TEXT_CALENDAR));
    if (DebugConfig.enableDAVclientCanChooseResourceBaseName) {
        HttpMethodExecutor.execute(client, putMethod, HttpStatus.SC_CREATED);
    } else {
        HttpMethodExecutor.execute(client, putMethod, HttpStatus.SC_MOVED_TEMPORARILY);
        // Not testing much in this mode but...
        return;
    }

    doGetMethod(url, dav1, HttpStatus.SC_OK);

    PropFindMethod propFindMethod = new PropFindMethod(getFolderUrl(dav1, "Calendar"));
    addBasicAuthHeaderForUser(propFindMethod, dav1);
    TestCalDav.HttpMethodExecutor executor;
    String respBody;
    Element respElem;
    propFindMethod.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML);
    propFindMethod.addRequestHeader("Depth", "1");
    propFindMethod.setRequestEntity(
            new ByteArrayRequestEntity(propFindEtagResType.getBytes(), MimeConstants.CT_TEXT_XML));
    executor = new TestCalDav.HttpMethodExecutor(client, propFindMethod, HttpStatus.SC_MULTI_STATUS);
    respBody = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    respElem = Element.XMLElement.parseXML(respBody);
    assertEquals("name of top element in propfind response", DavElements.P_MULTISTATUS, respElem.getName());
    assertTrue("propfind response should have child elements", respElem.hasChildren());
    Iterator<Element> iter = respElem.elementIterator();
    boolean hasCalendarHref = false;
    boolean hasCalItemHref = false;
    while (iter.hasNext()) {
        Element child = iter.next();
        if (DavElements.P_RESPONSE.equals(child.getName())) {
            Iterator<Element> hrefIter = child.elementIterator(DavElements.P_HREF);
            while (hrefIter.hasNext()) {
                Element href = hrefIter.next();
                calFolderUrl.endsWith(href.getText());
                hasCalendarHref = hasCalendarHref || calFolderUrl.endsWith(href.getText());
                hasCalItemHref = hasCalItemHref || url.endsWith(href.getText());
            }
        }
    }
    assertTrue("propfind response contained entry for calendar", hasCalendarHref);
    assertTrue("propfind response contained entry for calendar entry ", hasCalItemHref);
    doDeleteMethod(url, dav1, HttpStatus.SC_NO_CONTENT);
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

/**
 * Verifies that a 204 status code is returned when the operation returns null.
 *///from w w w. j a va  2s  . c om
@Test
public void testPostOperationNull2() throws Exception {
    String url = URL_RESOURCE2 + "/pathPostOperationNull2";
    PostMethod method = new PostMethod(url);

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_NO_CONTENT);
    byte[] responseBody = method.getResponseBody();
    assertNull(responseBody);
}