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:org.infoscoop.web.ProxyServlet.java

public void doProcess(HttpServletRequest request, HttpServletResponse response, int methodType)
        throws ServletException, IOException {
    int statusCode = 0;
    String url = request.getParameter("url");
    ProxyRequest proxyRequest = null;//from  w  ww.j a v  a2s .  c o m

    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {

        String filterType = request.getParameter("filter");

        proxyRequest = new ProxyRequest(url, filterType);

        String filterEncoding = request.getParameter("filterEncoding");
        proxyRequest.setFilterEncoding(filterEncoding);

        proxyRequest.setLocales(request.getLocales());
        proxyRequest.setPortalUid((String) request.getSession().getAttribute("Uid"));

        int timeout = request.getIntHeader("MSDPortal-Timeout") - 1000;
        proxyRequest.setTimeout((timeout > 0) ? timeout : DEFAULT_TIMEOUT);

        Enumeration headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            String headerName = (String) headers.nextElement();
            proxyRequest.putRequestHeader(headerName, request.getHeader(headerName));
        }

        //The certification for iframe
        String authTypeParam = request.getParameter("authType");
        if (authTypeParam != null && !"".equals(authTypeParam)) {
            proxyRequest.putRequestHeader("authType", authTypeParam);
            proxyRequest.putRequestHeader("authuserid", request.getParameter("authuserid"));
            proxyRequest.putRequestHeader("authpassword", request.getParameter("authpassword"));
        }

        for (Enumeration names = request.getParameterNames(); names.hasMoreElements();) {
            String name = (String) names.nextElement();

            proxyRequest.setFilterParameter(name, request.getParameter(name));
        }

        try {
            String otherMethod = request.getHeader("MSDPortal-method");
            if (otherMethod == null)
                otherMethod = request.getParameter("method");

            if (methodType == METHOD_GET) {
                if (otherMethod != null && otherMethod.equalsIgnoreCase("delete")) {
                    statusCode = proxyRequest.executeDelete();
                } else if ("postCredential".equals(authTypeParam)) {
                    statusCode = proxyRequest.executePost();
                } else {
                    statusCode = proxyRequest.executeGet();
                }
            } else {
                if ("get".equalsIgnoreCase(otherMethod)) {
                    statusCode = proxyRequest.executeGet();
                } else {
                    proxyRequest.setReqeustBody(request.getInputStream());
                    if (otherMethod == null || "post".equalsIgnoreCase(otherMethod)) {
                        statusCode = proxyRequest.executePost();
                    } else if ("put".equalsIgnoreCase(otherMethod)) {
                        statusCode = proxyRequest.executePut();
                    } else if ("report".equalsIgnoreCase(otherMethod)) {
                        statusCode = proxyRequest.executeReport();
                        if (statusCode == 207)
                            statusCode = 200;
                    }
                }
            }

        } catch (SocketTimeoutException ex) {
            // When the status code was 408, Firefox did not move well.
            // ABecause the cords such as 10408 are converted into 500 by Apache-GlassFish cooperation, we set it in a header.Apache-GlassFish.
            response.setHeader(HttpStatusCode.HEADER_NAME, HttpStatusCode.MSD_SC_TIMEOUT);
            throw ex;
        } catch (ConnectTimeoutException ex) {
            // In the case of connection-timeout,  we don't try it again.
            //response.setHeader(HttpStatusCode.HEADER_NAME,
            //      HttpStatusCode.MSD_SC_TIMEOUT);
            throw ex;
        }

        Map<String, List<String>> responseHeaders = proxyRequest.getResponseHeaders();
        if (statusCode == 401) {

            String wwwAuthHeader = proxyRequest.getResponseHeader("WWW-Authenticate");
            if (wwwAuthHeader == null) {
                statusCode = 403;
            } else if (wwwAuthHeader.toLowerCase().startsWith("basic")) {
                statusCode = 200;
                response.setHeader("MSDPortal-AuthType", "basic");
            } else if (wwwAuthHeader.toLowerCase().startsWith("ntlm")
                    || wwwAuthHeader.toLowerCase().startsWith("negotiate")) {
                statusCode = 200;
                response.setHeader("MSDPortal-AuthType", "ntlm");
            }
        }
        response.setStatus(statusCode);

        if (log.isInfoEnabled()) {
            log.info("Response-Status: " + statusCode);
        }

        StringBuffer headersSb = new StringBuffer();
        for (Map.Entry<String, List<String>> entry : responseHeaders.entrySet()) {

            String name = entry.getKey();
            if (name.equalsIgnoreCase("Transfer-Encoding") || name.equalsIgnoreCase("X-Powered-By")) {
                continue;
            }

            for (String value : entry.getValue()) {
                response.setHeader(entry.getKey(), value);
                headersSb.append(name + "=" + value + ",  ");
            }
        }

        if (!response.containsHeader("Connection")) {
            response.setHeader("Connection", "close");
            headersSb.append("Connection=close,  ");
        }

        if (log.isInfoEnabled())
            log.info("ResponseHeader: " + headersSb);

        String cacheHeader = request.getHeader("MSDPortal-Cache");

        InputStream responseBody = proxyRequest.getResponseBody();

        bos = new BufferedOutputStream(response.getOutputStream());

        if (responseBody != null) {

            //bis = new BufferedInputStream(
            //      new ByteArrayInputStream(bytes));
            bis = new BufferedInputStream(responseBody);

            if (log.isDebugEnabled()) {
                /*
                bis.mark(10240000);
                BufferedReader br =  new BufferedReader(new InputStreamReader(bis,"UTF-8"));
                        
                StringBuffer logStr = new StringBuffer();
                String out = null;
                while((out = br.readLine())!= null){
                   logStr.append(out);
                }
                        
                log.debug(logStr);
                bis.reset();
                */
                bis = printDebug(bis);
            }

            String cacheID = null;
            if (cacheHeader != null && cacheHeader.equals("Cache-NoResponse")) {

                //Process to save the cash
                String uid = (String) request.getSession().getAttribute("Uid");
                if (uid == null)
                    uid = request.getHeader("MSDPortal-SessionId");

                Map<String, List<String>> headerMap = proxyRequest.getResponseHeaders();

                try {
                    cacheID = CacheService.getHandle().insertCache(uid, url /*proxyRequest.getTargetURL() + "?"
                                                                            + request.getQueryString()*/, bis,
                            headerMap);
                    if (log.isInfoEnabled())
                        log.info("save cache : id = " + cacheID);
                } catch (Exception e) {
                    log.error(e);
                    //response.sendError(500, e.getMessage());
                }
            }

            if (cacheHeader != null && cacheHeader.equals("Cache-NoResponse") && cacheID != null) {
                response.setHeader("MSDPortal-Cache-ID", cacheID);
                response.setHeader("Pragma", "no-cache");
                response.setHeader("Cache-Control", "no-cache");
                response.setHeader("Content-Length", "1");
                //response.setHeader("Content-Length", "0");
                //response.setHeader("Connection", "close");
                bos.write(0);
                bos.flush();
                //response.setStatus(204);
            } else {
                if (cacheHeader != null && cacheHeader.equals("No-Cache")) {
                    response.setHeader("Pragma", "no-cache");
                    response.setHeader("Cache-Control", "no-cache");
                }
                if (!response.containsHeader("Content-Length") || statusCode == 500) {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();

                    byte[] b = new byte[1024];
                    int c = 0;
                    while ((c = bis.read(b)) != -1) {
                        baos.write(b, 0, c);
                    }

                    byte[] data = baos.toByteArray();
                    response.addHeader("Content-Length", String.valueOf(data.length));

                    bis = new BufferedInputStream(new ByteArrayInputStream(data));
                }

                byte[] b = new byte[1024];
                int c = 0;
                while ((c = bis.read(b)) != -1) {
                    bos.write(b, 0, c);
                }
                bos.flush();
            }
        } else {
            if (statusCode == HttpStatus.SC_NO_CONTENT) {
                response.setHeader("Content-Length", "0");
            } else {
                response.setHeader("Content-Length", "1");
                bos.write(0);
                bos.flush();
            }
        }

        long elapsedtime = new Date().getTime() - lastDeleteCachesTime;
        if (elapsedtime > 86400000) {
            log.info("Delete old public caches.");
            lastDeleteCachesTime = new Date().getTime();
            CacheService.getHandle().deleteOldPublicCaches();
        }

    } catch (Exception e) {

        log.error("Failed to get the URL. " + buildMessage(statusCode, proxyRequest, url), e);
        response.sendError(500, e.getMessage());
    } finally {
        if (log.isInfoEnabled()) {
            log.info("Succeeded in getting the URL. " + buildMessage(statusCode, proxyRequest, url));
        }

        if (proxyRequest != null)
            proxyRequest.close();
        if (bis != null)
            bis.close();
        if (bos != null)
            bos.close();
    }
}

From source file:org.jboss.orion.openshift.server.proxy.JsonProxyServlet.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//w  w  w  . ja  v a 2s  .co  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 = 500;
    try {
        intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // 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;
        }
    }

    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:org.jetbrains.plugins.github.api.GithubApiUtil.java

private static void checkStatusCode(@NotNull HttpMethod method) throws IOException {
    int code = method.getStatusCode();
    switch (code) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
    case HttpStatus.SC_NO_CONTENT:
        return;//from  w ww.  j ava2 s  .co  m
    case HttpStatus.SC_BAD_REQUEST:
    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_PAYMENT_REQUIRED:
    case HttpStatus.SC_FORBIDDEN:
        throw new GithubAuthenticationException("Request response: " + getErrorMessage(method));
    default:
        throw new GithubStatusCodeException(code + ": " + getErrorMessage(method), code);
    }
}

From source file:org.loadosophia.client.LoadosophiaAPIClient.java

private void setTestTitle(int testID, String trim) throws IOException {
    String uri = address + "api/test/edit/title/" + testID + "/?title=" + URLEncoder.encode(trim, "UTF-8");
    multipartPost(new LinkedList<Part>(), uri, HttpStatus.SC_NO_CONTENT);
}

From source file:org.loadosophia.client.LoadosophiaAPIClient.java

private void setTestColor(int testID, String colorFlag) throws IOException {
    String uri = address + "api/test/edit/color/" + testID + "/?color=" + colorFlag;
    multipartPost(new LinkedList<Part>(), uri, HttpStatus.SC_NO_CONTENT);
}

From source file:org.nuxeo.ecm.core.storage.sql.ScalityBinaryManager.java

/**
 * Deletes an object using its digest string.
 *
 * @param objectID/* ww w  . ja v  a  2  s .co  m*/
 */
protected void removeBinary(String objectID) {
    String url = PROTOCOL_PREFIX + this.bucketName + "." + this.hostBase;
    log.debug(url);
    DeleteMethod deleteMethod = new DeleteMethod(url);
    String contentMD5 = "";

    // date to be provided to the cloud server
    Date currentDate = new Date();

    String cloudDateString = StringGenerator.getCloudFormattedDateString(currentDate);

    String stringToSign = StringGenerator.getStringToSign(HTTPMethod.DELETE, contentMD5, DEFAULT_CONTENT_TYPE,
            this.bucketName, objectID, currentDate);
    try {
        deleteMethod.addRequestHeader("Authorization",
                StringGenerator.getAuthorizationString(stringToSign, awsID, awsSecret));
        deleteMethod.addRequestHeader("x-amz-date", cloudDateString);
        deleteMethod.setPath("/" + objectID);

        HttpClient client = new HttpClient();
        int returnCode = client.executeMethod(deleteMethod);
        log.debug(deleteMethod.getResponseBodyAsString());
        // only for logging
        if (returnCode == HttpStatus.SC_NO_CONTENT) {
            log.info("Object " + objectID + " deleted");
        } else if (returnCode == HttpStatus.SC_NOT_FOUND) {
            log.debug("Object " + objectID + " does not exist");
        } else {
            String connectionMsg = "Scality connection problem. Object could not be verified";
            log.debug(connectionMsg);
            throw new RuntimeException(connectionMsg);
        }
        deleteMethod.releaseConnection();
    } catch (SignatureException e) {
        throw new RuntimeException(e);
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.nuxeo.ecm.webdav.WebDavClientTest.java

@Test
public void testDeleteFile() throws Exception {
    String name = "test.txt";

    HttpMethod method = new DeleteMethod(ROOT_URI + name);
    int status = client.executeMethod(method);
    assertEquals(HttpStatus.SC_NO_CONTENT, status);

    // check using Nuxeo Core APIs
    session.save(); // process invalidations
    PathRef pathRef = new PathRef("/workspaces/workspace/" + name);
    assertFalse(session.exists(pathRef)); // in trash with different name

    // recreate it, for other tests using the same repo
    byte[] bytes = "Hello, world!".getBytes("UTF-8");
    doTestPutFile(name, bytes, "text/plain", "Note");
}

From source file:org.olat.admin.registration.SystemRegistrationManager.java

/**
 * Send the registration data now. If the user configured nothing to send, nothing will be sent.
 *///ww w  .  j  a  v a  2s.  c  om
public void sendRegistrationData() {
    // Do it optimistic and try to generate the XML message. If the message
    // doesn't contain anything, the user does not want to register this
    // instance
    final String registrationData = getRegistrationPropertiesMessage(null);
    String registrationKey = persitedProperties.getStringPropertyValue(CONF_SECRETKEY, false);
    if (StringHelper.containsNonWhitespace(registrationData)) {
        // only send when there is something to send
        final HttpClient client = HttpClientFactory.getHttpClientInstance();
        client.getParams().setParameter("http.useragent", "OLAT Registration Agent ; " + VERSION);
        final String url = REGISTRATION_SERVER
                + persitedProperties.getStringPropertyValue(CONF_KEY_IDENTIFYER, false) + "/";
        logInfo("URL:" + url, null);
        final PutMethod method = new PutMethod(url);
        if (registrationKey != null) {
            // updating
            method.setRequestHeader("Authorization", registrationKey);
            if (isLogDebugEnabled()) {
                logDebug("Authorization: " + registrationKey, null);
            } else {
                logDebug("Authorization: EXISTS", null);
            }
        } else {
            logInfo("Authorization: NONE", null);
        }
        method.setRequestHeader("Content-Type", "application/xml; charset=utf-8");
        try {
            method.setRequestEntity(new StringRequestEntity(registrationData, "application/xml", "UTF8"));
            client.executeMethod(method);
            final int status = method.getStatusCode();
            if (status == HttpStatus.SC_NOT_MODIFIED || status == HttpStatus.SC_OK) {
                logInfo("Successfully registered OLAT installation on olat.org server, thank you for your support!",
                        null);
                registrationKey = method.getResponseBodyAsString();
                persitedProperties.setStringProperty(CONF_SECRETKEY, registrationKey, false);
                persitedProperties.savePropertiesAndFireChangedEvent();
            } else if (method.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                logError("File could be created not on registration server::"
                        + method.getStatusLine().toString(), null);
            } else if (method.getStatusCode() == HttpStatus.SC_NO_CONTENT) {
                logInfo(method.getResponseBodyAsString(), method.getStatusText());
            } else {
                logError("Unexpected HTTP Status::" + method.getStatusLine().toString()
                        + " during registration call", null);
            }
        } catch (final Exception e) {
            logError("Unexpected exception during registration call", e);
        }
    } else {
        logWarn("****************************************************************************************************************************************************************************",
                null);
        logWarn("* This OLAT installation is not registered. Please, help us with your statistical data and register your installation under Adminisration - Systemregistration. THANK YOU! *",
                null);
        logWarn("****************************************************************************************************************************************************************************",
                null);
    }
}

From source file:org.opencastproject.adminui.endpoint.BlacklistsEndpointTest.java

@Test
public void testDeletePeriod() throws ParseException {
    given().pathParam("periodId", 0).log().all().expect().statusCode(HttpStatus.SC_NOT_FOUND).when()
            .delete(rt.host("/{periodId}"));
    given().pathParam("periodId", 1).log().all().expect().statusCode(HttpStatus.SC_NO_CONTENT).when()
            .delete(rt.host("/{periodId}")).asString();
}

From source file:org.opencastproject.adminui.endpoint.ThemesEndpointTest.java

@Test
public void testDeleteThemes() {
    // Test invalid id
    given().pathParam("themeId", "asdasd").expect().statusCode(HttpStatus.SC_NOT_FOUND).when()
            .delete(rt.host("/{themeId}")).asString();
    // Test unknown id
    given().pathParam("themeId", notFoundId).expect().statusCode(HttpStatus.SC_NOT_FOUND).when()
            .delete(rt.host("/{themeId}")).asString();
    // Test correct id
    given().pathParam("themeId", foundId).expect().statusCode(HttpStatus.SC_NO_CONTENT).when()
            .delete(rt.host("/{themeId}")).asString();
}