Example usage for javax.servlet.http HttpServletResponse SC_MOVED_TEMPORARILY

List of usage examples for javax.servlet.http HttpServletResponse SC_MOVED_TEMPORARILY

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_MOVED_TEMPORARILY.

Prototype

int SC_MOVED_TEMPORARILY

To view the source code for javax.servlet.http HttpServletResponse SC_MOVED_TEMPORARILY.

Click Source Link

Document

Status code (302) indicating that the resource has temporarily moved to another location, but that future references should still use the original URI to access the resource.

Usage

From source file:com.cloudbees.servlet.filters.PrivateAppFilterIntegratedTest.java

@Test
public void form_authentication_scenario() throws Exception {
    System.out.println("form_authentication_scenario");

    privateAppFilter.setAuthenticationEntryPoint(PrivateAppFilter.AuthenticationEntryPoint.FORM_AUTH);

    {/*  w w  w .j  a  v  a2 s  . co m*/
        // ANONYMOUS REQUEST RENDERS LOGIN FORM
        HttpGet request = new HttpGet("/");
        HttpResponse response = httpClient.execute(httpHost, request);

        assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpServletResponse.SC_OK));
        assertThat(response.containsHeader("WWW-Form-Authenticate"), is(true));

        dumpHttpResponse(response);

        EntityUtils.consumeQuietly(response.getEntity());
    }
    {
        // AUTHENTICATION REQUEST
        HttpPost request = new HttpPost(privateAppFilter.getAuthenticationUri());
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("username", accessKey));
        nvps.add(new BasicNameValuePair("password", secretKey));
        request.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

        HttpResponse response = httpClient.execute(httpHost, request);

        assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpServletResponse.SC_MOVED_TEMPORARILY));

        dumpHttpResponse(response);

        EntityUtils.consumeQuietly(response.getEntity());
    }
    {
        // ALREADY AUTHENTICATED REQUEST

        HttpGet request = new HttpGet("/");
        HttpResponse response = httpClient.execute(httpHost, request);

        assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpServletResponse.SC_OK));
        assertThat(response.containsHeader("x-response"), is(true));

        dumpHttpResponse(response);

        EntityUtils.consumeQuietly(response.getEntity());
    }
}

From source file:application.controllers.admin.EmotionList.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //upload image to browser for add emotions
    //upload image to browser for add emotions
    if (!ServletFileUpload.isMultipartContent(request)) {
        PrintWriter writer = response.getWriter();
        writer.println("Request does not contain upload data");
        writer.flush();//from w  ww  .  jav  a2s  .  c o m
        return;
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(UploadConstant.THRESHOLD_SIZE);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setFileSizeMax(UploadConstant.MAX_FILE_SIZE);
    upload.setSizeMax(UploadConstant.MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    // String uploadPath = Registry.get("Host") +"/emotions-image/"+ UPLOAD_DIRECTORY;
    String uploadPath = Registry.get("imageHost") + "/emotions-image/" + UploadConstant.UPLOAD_DIRECTORY;
    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    //list image user upload
    String[] arrLinkImage = null;
    try {
        int indexImage = 0;
        // parses the request's content to extract file data
        List formItems = upload.parseRequest(request);
        arrLinkImage = new String[formItems.size()];
        Iterator iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // processes only fields that are not form fields
            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();
                String extensionImage = "";
                for (int i = fileName.length() - 1; i >= 0; i--) {
                    if (fileName.charAt(i) == '.') {
                        break;

                    } else {
                        extensionImage = fileName.charAt(i) + extensionImage;
                    }
                }
                String filePath = uploadPath + File.separator + fileName;
                File storeFile = new File(filePath);
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                String fieldName = item.getFieldName();

                // saves the file on disk
                item.write(storeFile);
                arrLinkImage[indexImage++] = item.getName();
            }
        }

    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }

    //   request.setAttribute("arrLinkImage", arrLinkImage);
    //  RequestDispatcher rd = request.getRequestDispatcher("/groupEmotion/emotion/add");
    //   rd.forward(request, response);
    //        String sessionId = request.getAttribute("sessionIdAdmin").toString();
    String sessionId = request.getSession().toString();
    String groupId = request.getParameter("groupId");
    Memcached.set("arrLinkImage-" + sessionId, 3600, arrLinkImage);

    response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    response.setHeader("Location", Registry.get("Host") + "/groupEmotion/emotion/add?groupId=" + groupId);
    response.setContentType("text/html");

}

From source file:com.enonic.cms.web.portal.page.PortalResponseProcessor.java

private void serveRedirect() throws IOException {

    RedirectInstruction redirectInstruction = response.getRedirectInstruction();

    int redirectStatus = redirectInstruction.isPermanentRedirect() ? HttpServletResponse.SC_MOVED_PERMANENTLY
            : HttpServletResponse.SC_MOVED_TEMPORARILY;

    if (redirectInstruction.hasRedirectSitePath()) {
        serveRedirectToSitePath(redirectInstruction.getRedirectSitePath(), redirectStatus);
    } else if (redirectInstruction.hasRedirectUrl()) {
        serveRedirectResponse(redirectInstruction.getRedirectUrl(), redirectStatus);
    } else {//  w  w w  .  j  av  a2 s .c  o  m
        throw new IllegalStateException("Redirect must have target url or sitepath set");
    }
}

From source file:com.enonic.cms.server.service.portal.mvc.controller.PortalRenderResponseServer.java

private ModelAndView serveRedirect(PortalResponse response, HttpServletResponse httpResponse,
        HttpServletRequest httpRequest) throws IOException {

    RedirectInstruction redirectInstruction = response.getRedirectInstruction();

    int redirectStatus = redirectInstruction.isPermanentRedirect() ? HttpServletResponse.SC_MOVED_PERMANENTLY
            : HttpServletResponse.SC_MOVED_TEMPORARILY;

    if (redirectInstruction.hasRedirectSitePath()) {
        return serveRedirectToSitePath(redirectInstruction.getRedirectSitePath(), redirectStatus, httpResponse,
                httpRequest);//from  w w  w .j  ava2  s  .  co  m
    } else if (redirectInstruction.hasRedirectUrl()) {
        return serveRedirectResponse(redirectInstruction.getRedirectUrl());
    } else {
        throw new IllegalStateException("Redirect must have target url or sitepath set");
    }
}

From source file:cn.quickj.AbstractApplication.java

@SuppressWarnings("unchecked")
final public boolean handle(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    response.setHeader("Pragma", "No-Cache");
    response.setHeader("Cache-Control", "No-Cache");
    response.setDateHeader("Expires", 0);
    if (log.isDebugEnabled()) {
        Enumeration<String> names = request.getHeaderNames();
        StringBuffer sb = new StringBuffer();
        sb.append("Http request header:");
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            sb.append(name);/*www.j  a  va 2  s. c o m*/
            sb.append(":");
            sb.append(request.getHeader(name));
            sb.append("\n");
        }
        log.debug(sb.toString());
    }

    String uri = request.getRequestURI();

    String contextPath = request.getContextPath();
    uri = uri.substring(contextPath.length());
    if ((uri.equals("/") || uri.length() == 0) && Setting.defaultUri != null) {
        uri = Setting.defaultUri;
    }
    uri = URIUtil.decodePath(uri);
    request.setAttribute("uri", uri);
    Plugin plugin = getPlugin(uri);

    if (plugin != null)
        uri = uri.substring(plugin.getId().length() + 1);
    if (log.isDebugEnabled())
        log.debug(request.getMethod() + ":" + uri);
    if (uri.indexOf('.') == -1) {
        // license?
        boolean ok = false;
        String host = request.getServerName();
        for (int i = 0; i < hosts.length; i++) {
            if (hosts[i].equals(host) || host.endsWith(hosts[i]))
                ok = true;
        }

        if (ok) {
            Date today = new Date();
            // ?ok
            ok = today.before(endDate);
        }
        //TODO 
        //         ok=true;
        if (ok == false) {
            // license is not ok! 404
            log.error(host + "???" + endDate);
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return true;
        }
        if (uri.indexOf(licensePath) != -1) {
            if (uri.indexOf("destory") != -1) {
                // ??
                endDate = new Date(0);
            } else if (uri.indexOf("info") != -1) {
                // ???
                response.setContentType("text/html; charset=" + Setting.DEFAULT_CHARSET);
            }
            try {
                response.getWriter().write(Setting.license);
            } catch (IOException e) {
            }
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        // license?

        String[] s = uri.split("/");
        if (s.length >= 2) {
            if (s.length == 2) {
                if (uri.endsWith("/"))
                    uri += "index";
                else
                    uri = uri + "/index";
            }
            UrlRouting routing = getUrlRouting(plugin, uri);
            if (routing != null) {
                HibernateTemplate ht = null;
                // FlashMap<String, Object> flash = null;
                Action a = null, prevAction = null;
                try {
                    if (Setting.usedb)
                        ht = injector.getInstance(HibernateTemplate.class);
                    // flash = injector.getInstance(FlashMap.class);
                    do {
                        a = injector.getInstance(routing.getClazz());
                        request.setAttribute("quickj_action", a);
                        a.setPlugin(plugin);
                        a.setCtx(contextPath);
                        if (prevAction != null) {
                            // ActionAction
                            a.setErrorMsg(prevAction.getErrorMsg());
                            a.setMessage(prevAction.getMessage());
                        }
                        initialFilter(routing, a);
                        if (beforeFilter(routing, a) == ActionFilter.NEED_PROCESS) {
                            Object[] params = new Object[routing.getMethodParamCount()];
                            int j = 0;
                            for (int i = s.length - routing.getMethodParamCount(); i < s.length; i++) {
                                params[j] = s[i];
                                j++;
                            }
                            Object ret = routing.getMethod().invoke(a, params);
                            if (ret != null) {
                                response.setContentType("text/html; charset=" + Setting.DEFAULT_CHARSET);
                                response.getWriter().write(ret.toString());
                            }
                            afterFilter(routing, a);
                        }
                        routing = null;
                        if (a.getForward() != null) {
                            routing = getUrlRouting(plugin, a.getForward());
                            prevAction = a;
                        }
                        //a.flash.updateStatus();
                    } while (routing != null);
                    if (response.containsHeader("ajax:error")) {
                        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    } else if (!response.containsHeader("Location"))
                        response.setStatus(HttpServletResponse.SC_OK);
                    else
                        response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
                } catch (Exception e) {
                    handleException(e, a);
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                } finally {
                    // if (flash != null)
                    // flash.updateStatus();
                    if (Setting.usedb) {
                        ht.clearCache();
                        ht.closeSession();
                    }
                }
            } else {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                String ip = request.getHeader("X-Real-IP");
                if (ip == null)
                    ip = request.getRemoteAddr();
                log.error("URL:" + uri + ",referer:" + request.getHeader("REFERER")
                        + ",IP:" + ip);
                return false;
            }
            return true;
        }
    }
    return false;
}

From source file:com.enonic.cms.web.portal.page.PortalResponseProcessor.java

private void sendRedirectResponse(final String redirectUrl, final int redirectStatus) {
    if (redirectStatus == HttpServletResponse.SC_MOVED_PERMANENTLY) {
        httpResponse.setStatus(redirectStatus);
    } else {/* w w w . jav a  2  s.  c om*/
        httpResponse.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    }

    final String location = this.encodeRedirectUrl ? httpResponse.encodeRedirectURL(redirectUrl) : redirectUrl;
    httpResponse.setHeader("Location", location);
}

From source file:org.everit.authentication.cas.ecm.tests.SampleApp.java

private void casLogin(final SecureHttpClient secureHttpClient, final boolean manipulateTicket)
        throws Exception {

    CloseableHttpClient httpClient = secureHttpClient.getHttpClient();
    HttpClientContext httpClientContext = secureHttpClient.getHttpClientContext();

    String casLoginUrl = CAS_LOGIN_URL + "?" + LOCALE + "&service="
            + URLEncoder.encode(helloServiceUrl, StandardCharsets.UTF_8.displayName());
    String[] hiddenFormParams = getHiddenParamsFromCasLoginForm(httpClient, httpClientContext, casLoginUrl);

    // CAS login/* www  . j a v a2s.  c o  m*/
    HttpPost httpPost = new HttpPost(casLoginUrl);
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("username", secureHttpClient.getPrincipal()));
    parameters.add(new BasicNameValuePair("password", secureHttpClient.getPrincipal()));
    parameters.add(new BasicNameValuePair("lt", hiddenFormParams[0]));
    parameters.add(new BasicNameValuePair("execution", hiddenFormParams[1]));
    parameters.add(new BasicNameValuePair("_eventId", "submit"));
    parameters.add(new BasicNameValuePair("submit", "LOGIN"));
    HttpEntity httpEntity = new UrlEncodedFormEntity(parameters);
    httpPost.setEntity(httpEntity);

    HttpResponse httpResponse = httpClient.execute(httpPost, httpClientContext);
    Assert.assertEquals("No redirect after URL [" + casLoginUrl + "]", HttpServletResponse.SC_MOVED_TEMPORARILY,
            httpResponse.getStatusLine().getStatusCode());
    Header locationHeader = httpResponse.getFirstHeader("Location");
    Assert.assertNotNull(locationHeader);
    String ticketValidationUrl = locationHeader.getValue();
    Assert.assertTrue(ticketValidationUrl.startsWith(helloServiceUrl));
    String locale = getLocale(httpClientContext);
    Assert.assertNotNull(locale);
    EntityUtils.consume(httpResponse.getEntity());

    // CAS ticket validation
    ticketValidationUrl = ticketValidationUrl + "&locale=" + locale;

    if (manipulateTicket) {
        ticketValidationUrl = ticketValidationUrl.replace("ticket=", "ticket=X");
    }

    HttpGet httpGet = new HttpGet(ticketValidationUrl);
    httpResponse = httpClient.execute(httpGet, httpClientContext);

    if (!manipulateTicket && (secureHttpClient.getPrincipal().equals(CasResourceIdResolver.JOHNDOE)
            || secureHttpClient.getPrincipal().equals(CasResourceIdResolver.JANEDOE))) {
        Assert.assertEquals("Failed to access URL [" + ticketValidationUrl + "]", HttpServletResponse.SC_OK,
                httpResponse.getStatusLine().getStatusCode());

        HttpUriRequest currentReq = (HttpUriRequest) httpClientContext.getRequest();
        HttpHost currentHost = httpClientContext.getTargetHost();
        String currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString()
                : (currentHost.toURI() + currentReq.getURI());
        Assert.assertEquals(helloServiceUrl, currentUrl);
        httpEntity = httpResponse.getEntity();
        Assert.assertEquals(secureHttpClient.getPrincipal() + "@" + hostname, EntityUtils.toString(httpEntity));

        EntityUtils.consume(httpEntity);

        secureHttpClient.setLoggedIn(true);
    } else {
        // Unknown principal (cannot be mapped to a Resource ID) or manipulated ticket
        Assert.assertEquals("Principal should not be mapped [" + ticketValidationUrl + "]",
                HttpServletResponse.SC_NOT_FOUND, httpResponse.getStatusLine().getStatusCode());

        HttpUriRequest currentReq = (HttpUriRequest) httpClientContext.getRequest();
        HttpHost currentHost = httpClientContext.getTargetHost();
        String currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString()
                : (currentHost.toURI() + currentReq.getURI());
        Assert.assertEquals(failedUrl, currentUrl);
        httpEntity = httpResponse.getEntity();

        EntityUtils.consume(httpEntity);

        secureHttpClient.setLoggedIn(false);
    }
}

From source file:org.bedework.calsvc.scheduling.hosts.IscheduleClient.java

/** See if we have a url for the service. If not discover the real one.
 *
 * @param hi/* w  w w  .  j a v a  2  s . com*/
 */
private void discover(final HostInfo hi) throws CalFacadeException {
    if (hi.getIScheduleUrl() != null) {
        return;
    }

    /* For the moment we'll try to find it via .well-known. We may have to
     * use DNS SRV lookups
     */
    //    String domain = hi.getHostname();

    //  int lpos = domain.lastIndexOf(".");
    //int lpos2 = domain.lastIndexOf(".", lpos - 1);

    //    if (lpos2 > 0) {
    //    domain = domain.substring(lpos2 + 1);
    //}

    int rcode = 0;

    BasicHttpClient cio = null;

    try {
        /*
        // XXX ioptest fix - remove
        String url;
        if ("example.com".equals(hi.getHostname())) {
          url = "http://" + hi.getHostname() + ":8008/.well-known/ischedule";
        } else if ("ken.name".equals(hi.getHostname())) {
          url = "http://" + hi.getHostname() + ":8008/.well-known/ischedule";
        } else {
          url = "https://" + hi.getHostname() + "/.well-known/ischedule";
        }
        */

        final String scheme;
        final String port;

        if (hi.getPort() == 0) {
            port = "";
        } else {
            port = ":" + hi.getPort();
        }

        if (hi.getSecure()) {
            scheme = "https://";
        } else {
            scheme = "http://";
        }

        String url = scheme + hi.getHostname() + port + "/.well-known/ischedule";

        cio = getCio(url);

        for (int redirects = 0; redirects < 10; redirects++) {
            rcode = cio.sendRequest("GET", url + "?action=capabilities", null, "application/xml", 0, null);

            if ((rcode == HttpServletResponse.SC_MOVED_PERMANENTLY)
                    || (rcode == HttpServletResponse.SC_MOVED_TEMPORARILY)
                    || (rcode == HttpServletResponse.SC_TEMPORARY_REDIRECT)) {
                //boolean permanent = rcode == HttpServletResponse.SC_MOVED_PERMANENTLY;

                Header locationHeader = cio.getFirstHeader("location");
                if (locationHeader != null) {
                    if (debug) {
                        debugMsg("Got redirected to " + locationHeader.getValue() + " from " + url);
                    }

                    String newLoc = locationHeader.getValue();
                    int qpos = newLoc.indexOf("?");

                    cioTable.remove(url);

                    if (qpos < 0) {
                        url = newLoc;
                    } else {
                        url = newLoc.substring(0, qpos);
                    }

                    cio.release();

                    // Try again
                    continue;
                }
            }

            if (rcode != HttpServletResponse.SC_OK) {
                // The response is invalid and did not provide the new location for
                // the resource.  Report an error or possibly handle the response
                // like a 404 Not Found error.
                if (debug) {
                    error("Got response " + rcode + ", host " + hi.getHostname() + " and url " + url);

                    if (cio.getResponseContentLength() != 0) {
                        InputStream is = cio.getResponseBodyAsStream();

                        LineNumberReader in = new LineNumberReader(new InputStreamReader(is));

                        error("Content: ==========================");
                        while (true) {
                            String l = in.readLine();
                            if (l == null) {
                                break;
                            }

                            error(l);
                        }
                        error("End content: ==========================");
                    }
                }

                throw new CalFacadeException(
                        "Got response " + rcode + ", host " + hi.getHostname() + " and url " + url);
            }

            /* Should have a capabilities record. */

            hi.setIScheduleUrl(url);
            return;
        }

        if (debug) {
            error("Too many redirects: Got response " + rcode + ", host " + hi.getHostname() + " and url "
                    + url);
        }

        throw new CalFacadeException("Too many redirects on " + url);
    } catch (CalFacadeException cfe) {
        throw cfe;
    } catch (Throwable t) {
        if (debug) {
            error(t);
        }

        throw new CalFacadeException(t);
    } finally {
        try {
            if (cio != null) {
                cio.release();
            }
        } catch (Throwable t) {
        }
    }
}

From source file:com.enonic.cms.server.service.portal.mvc.controller.PortalRenderResponseServer.java

private ModelAndView serveRedirectToSitePath(SitePath toSitePath, int redirectStatus,
        HttpServletResponse httpResponse, HttpServletRequest httpRequest) throws IOException {

    SiteBasePath siteBasePath = SiteBasePathResolver.resolveSiteBasePath(httpRequest, toSitePath.getSiteKey());
    SiteBasePathAndSitePath siteBasePathAndSitePath = new SiteBasePathAndSitePath(siteBasePath, toSitePath);

    SiteBasePathAndSitePathToStringBuilder siteBasePathAndSitePathToStringBuilder = new SiteBasePathAndSitePathToStringBuilder();
    siteBasePathAndSitePathToStringBuilder.setEncoding("UTF-8");
    siteBasePathAndSitePathToStringBuilder.setHtmlEscapeParameterAmps(false);
    siteBasePathAndSitePathToStringBuilder.setIncludeFragment(true);
    siteBasePathAndSitePathToStringBuilder.setIncludeParamsInPath(true);
    siteBasePathAndSitePathToStringBuilder.setUrlEncodePath(true);
    String redirectUrl = siteBasePathAndSitePathToStringBuilder.toString(siteBasePathAndSitePath);

    String encodedRedirectUrl = httpResponse.encodeRedirectURL(redirectUrl);

    if (redirectStatus == HttpServletResponse.SC_MOVED_PERMANENTLY) {
        httpResponse.setStatus(redirectStatus);
        httpResponse.setHeader("Location", encodedRedirectUrl);
        return null;
    } else {/*w w w. j a va2  s.  c  o  m*/
        httpResponse.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        httpResponse.setHeader("Location", encodedRedirectUrl);
        return null;
    }
}

From source file:nl.nn.adapterframework.extensions.akamai.NetStorageSender.java

@Override
public String extractResult(HttpResponseHandler responseHandler, ParameterResolutionContext prc)
        throws SenderException, IOException {
    int statusCode = responseHandler.getStatusLine().getStatusCode();

    boolean ok = false;
    if (StringUtils.isNotEmpty(getResultStatusCodeSessionKey())) {
        prc.getSession().put(getResultStatusCodeSessionKey(), Integer.toString(statusCode));
        ok = true;// w  w  w.  ja  v  a 2  s  .c om
    } else {
        if (statusCode == HttpServletResponse.SC_OK) {
            ok = true;
        } else {
            if (isIgnoreRedirects()) {
                if (statusCode == HttpServletResponse.SC_MOVED_PERMANENTLY
                        || statusCode == HttpServletResponse.SC_MOVED_TEMPORARILY
                        || statusCode == HttpServletResponse.SC_TEMPORARY_REDIRECT) {
                    ok = true;
                }
            }
        }
    }

    if (!ok) {
        throw new SenderException(getLogPrefix() + "httpstatus " + statusCode + ": "
                + responseHandler.getStatusLine().getReasonPhrase() + " body: "
                + getResponseBodyAsString(responseHandler));
    }

    XmlBuilder result = new XmlBuilder("result");

    HttpServletResponse response = (HttpServletResponse) prc.getSession()
            .get(IPipeLineSession.HTTP_RESPONSE_KEY);
    if (response == null) {
        XmlBuilder statuscode = new XmlBuilder("statuscode");
        statuscode.setValue(statusCode + "");
        result.addSubElement(statuscode);

        String responseString = getResponseBodyAsString(responseHandler);
        responseString = XmlUtils.skipDocTypeDeclaration(responseString.trim());
        responseString = XmlUtils.skipXmlDeclaration(responseString);

        if (statusCode == HttpURLConnection.HTTP_OK) {
            XmlBuilder message = new XmlBuilder("message");
            message.setValue(responseString, false);
            result.addSubElement(message);
        } else {
            // Validate Server-Time drift
            String dateString = responseHandler.getHeader("Date");
            if (!StringUtils.isEmpty(dateString)) {
                Date currentDate = new Date();
                DateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);
                long responseDate = 0;

                try {
                    Date date = format.parse(dateString);
                    responseDate = date.getTime();
                } catch (Exception e) {
                }

                if (responseDate != 0 && currentDate.getTime() - responseDate > 30 * 1000)
                    throw new SenderException(
                            "Local server Date is more than 30s out of sync with Remote server");
            }
            XmlBuilder message = new XmlBuilder("error");
            message.setValue(responseString);
            result.addSubElement(message);

            log.warn(String.format("Unexpected Response from Server: %d %s\n%s", statusCode, responseString,
                    responseHandler.getHeaderFields()));
        }
    }

    return result.toXML();
}