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

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

Introduction

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

Prototype

int SC_MOVED_TEMPORARILY

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

Click Source Link

Document

<tt>302 Moved Temporarily</tt> (Sometimes <tt>Found</tt>) (HTTP/1.0 - RFC 1945)

Usage

From source file:org.josso.test.tck.Tck004Test.java

protected void doPostCredentialsA() throws Exception {
    NameValuePair username = new NameValuePair("josso_username", "userA");
    NameValuePair password = new NameValuePair("josso_password", "user1pwd");
    NameValuePair cmd = new NameValuePair(PARAM_JOSSO_CMD, "login");

    PostMethod postMethod = doPost("http://localhost:" + getProperty("josso.tck.serverPort")
            + "/josso/signon/usernamePasswordLogin.do", username, password, cmd);
    int status = postMethod.getStatusCode();
    assert status == HttpStatus.SC_MOVED_TEMPORARILY : "Unexpected HTTP status " + status;

    Header location = postMethod.getResponseHeader("Location");
    location.getValue();/*from w w w .ja  va2  s.  co  m*/
    HttpMethod getMethod = doGet(location.getValue());
    status = getMethod.getStatusCode();

    assert status == HttpStatus.SC_OK : "Unexpected HTTP status " + status;

    String body = getMethod.getResponseBodyAsString();

    assert body.indexOf("JOSSO_SESSIONID=") > 0 : "No JOSSO_SESSIONID= recived in response boyd";
    assert body.indexOf("This is a simple JSP") > 0 : "No sample text found in response body";
    assert body.indexOf("roleA") > 0 : "Role1 not found in response body";

}

From source file:org.methodize.nntprss.feed.Channel.java

/**
 * Retrieves the latest RSS doc from the remote site
 *//*from  w w  w . j av  a 2  s.  co m*/
public synchronized void poll() {
    // Use method-level variable
    // Guard against change in history mid-poll
    polling = true;

    //      boolean keepHistory = historical;
    long keepExpiration = expiration;

    lastPolled = new Date();

    int statusCode = -1;
    HttpMethod method = null;
    String urlString = url.toString();
    try {
        HttpClient httpClient = getHttpClient();
        channelManager.configureHttpClient(httpClient);
        HttpResult result = null;

        try {

            connected = true;
            boolean redirected = false;
            int count = 0;
            do {
                URL currentUrl = new URL(urlString);
                method = new GetMethod(urlString);
                method.setRequestHeader("User-agent", AppConstants.getUserAgent());
                method.setRequestHeader("Accept-Encoding", "gzip");
                method.setFollowRedirects(false);
                method.setDoAuthentication(true);

                // ETag
                if (lastETag != null) {
                    method.setRequestHeader("If-None-Match", lastETag);
                }

                // Last Modified
                if (lastModified != 0) {
                    final String NAME = "If-Modified-Since";
                    //defend against such fun like net.freeroller.rickard got If-Modified-Since "Thu, 24 Aug 2028 12:29:54 GMT"
                    if (lastModified < System.currentTimeMillis()) {
                        final String DATE = httpDate.format(new Date(lastModified));
                        method.setRequestHeader(NAME, DATE);
                        log.debug("channel " + this.name + " using " + NAME + " " + DATE); //ALEK
                    }
                }

                method.setFollowRedirects(false);
                method.setDoAuthentication(true);

                HostConfiguration hostConfig = new HostConfiguration();
                hostConfig.setHost(currentUrl.getHost(), currentUrl.getPort(), currentUrl.getProtocol());

                result = executeHttpRequest(httpClient, hostConfig, method);
                statusCode = result.getStatusCode();
                if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                        || statusCode == HttpStatus.SC_MOVED_TEMPORARILY
                        || statusCode == HttpStatus.SC_SEE_OTHER
                        || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {

                    redirected = true;
                    // Resolve against current URI - may be a relative URI
                    try {
                        urlString = new java.net.URI(urlString).resolve(result.getLocation()).toString();
                    } catch (URISyntaxException use) {
                        // Fall back to just using location from result
                        urlString = result.getLocation();
                    }
                    if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY && channelManager.isObserveHttp301()) {
                        try {
                            url = new URL(urlString);
                            if (log.isInfoEnabled()) {
                                log.info("Channel = " + this.name
                                        + ", updated URL from HTTP Permanent Redirect");
                            }
                        } catch (MalformedURLException mue) {
                            // Ignore URL permanent redirect for now...                        
                        }
                    }
                } else {
                    redirected = false;
                }

                //               method.getResponseBody();
                //               method.releaseConnection();
                count++;
            } while (count < 5 && redirected);

        } catch (HttpRecoverableException hre) {
            if (log.isDebugEnabled()) {
                log.debug("Channel=" + name + " - Temporary Http Problem - " + hre.getMessage());
            }
            status = STATUS_CONNECTION_TIMEOUT;
            statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        } catch (ConnectException ce) {
            // @TODO Might also be a connection refused - not only a timeout...
            if (log.isDebugEnabled()) {
                log.debug("Channel=" + name + " - Connection Timeout, skipping - " + ce.getMessage());
            }
            status = STATUS_CONNECTION_TIMEOUT;
            statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        } catch (UnknownHostException ue) {
            if (log.isDebugEnabled()) {
                log.debug("Channel=" + name + " - Unknown Host Exception, skipping");
            }
            status = STATUS_UNKNOWN_HOST;
            statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        } catch (NoRouteToHostException re) {
            if (log.isDebugEnabled()) {
                log.debug("Channel=" + name + " - No Route To Host Exception, skipping");
            }
            status = STATUS_NO_ROUTE_TO_HOST;
            statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        } catch (SocketException se) {
            // e.g. Network is unreachable            
            if (log.isDebugEnabled()) {
                log.debug("Channel=" + name + " - Socket Exception, skipping");
            }
            status = STATUS_SOCKET_EXCEPTION;
            statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        }

        // Only process if ok - if not ok (e.g. not modified), don't do anything
        if (connected && statusCode == HttpStatus.SC_OK) {

            PushbackInputStream pbis = new PushbackInputStream(new ByteArrayInputStream(result.getResponse()),
                    PUSHBACK_BUFFER_SIZE);
            skipBOM(pbis);
            BufferedInputStream bis = new BufferedInputStream(pbis);
            DocumentBuilder db = AppConstants.newDocumentBuilder();

            try {
                Document rssDoc = null;
                if (!parseAtAllCost) {
                    try {
                        rssDoc = db.parse(bis);
                    } catch (InternalError ie) {
                        // Crimson library throws InternalErrors
                        if (log.isDebugEnabled()) {
                            log.debug("InternalError thrown by Crimson", ie);
                        }
                        throw new SAXException("InternalError thrown by Crimson: " + ie.getMessage());
                    }
                } else {
                    // Parse-at-all-costs selected
                    // Read in document to local array - may need to parse twice
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    byte[] buf = new byte[1024];
                    int bytesRead = bis.read(buf);
                    while (bytesRead > -1) {
                        if (bytesRead > 0) {
                            bos.write(buf, 0, bytesRead);
                        }
                        bytesRead = bis.read(buf);
                    }
                    bos.flush();
                    bos.close();

                    byte[] rssDocBytes = bos.toByteArray();

                    try {
                        // Try the XML document parser first - just in case
                        // the doc is well-formed
                        rssDoc = db.parse(new ByteArrayInputStream(rssDocBytes));
                    } catch (SAXParseException spe) {
                        if (log.isDebugEnabled()) {
                            log.debug("XML parse failed, trying tidy");
                        }
                        // Fallback to parse-at-all-costs parser
                        rssDoc = LooseParser.parse(new ByteArrayInputStream(rssDocBytes));
                    }
                }

                processChannelDocument(expiration, rssDoc);

                // Update last modified / etag from headers
                //               lastETag = httpCon.getHeaderField("ETag");
                //               lastModified = httpCon.getHeaderFieldDate("Last-Modified", 0);

                Header hdrETag = method.getResponseHeader("ETag");
                lastETag = hdrETag != null ? hdrETag.getValue() : null;

                Header hdrLastModified = method.getResponseHeader("Last-Modified");
                lastModified = hdrLastModified != null ? parseHttpDate(hdrLastModified.getValue()) : 0;
                log.debug("channel " + this.name + " parsed Last-Modifed " + hdrLastModified + " to "
                        + (lastModified != 0 ? "" + (new Date(lastModified)) : "" + lastModified)); //ALEK

                status = STATUS_OK;
            } catch (SAXParseException spe) {
                if (log.isEnabledFor(Priority.WARN)) {
                    log.warn("Channel=" + name + " - Error parsing RSS document - check feed");
                }
                status = STATUS_INVALID_CONTENT;
            }

            bis.close();

            // end if response code == HTTP_OK
        } else if (connected && statusCode == HttpStatus.SC_NOT_MODIFIED) {
            if (log.isDebugEnabled()) {
                log.debug("Channel=" + name + " - HTTP_NOT_MODIFIED, skipping");
            }
            status = STATUS_OK;
        } else if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            if (log.isEnabledFor(Priority.WARN)) {
                log.warn("Channel=" + name + " - Proxy authentication required");
            }
            status = STATUS_PROXY_AUTHENTICATION_REQUIRED;
        } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            if (log.isEnabledFor(Priority.WARN)) {
                log.warn("Channel=" + name + " - Authentication required");
            }
            status = STATUS_USER_AUTHENTICATION_REQUIRED;
        }

        // Update channel in database...
        channelDAO.updateChannel(this);

    } catch (FileNotFoundException fnfe) {
        if (log.isEnabledFor(Priority.WARN)) {
            log.warn("Channel=" + name + " - File not found returned by web server - check feed");
        }
        status = STATUS_NOT_FOUND;
    } catch (Exception e) {
        if (log.isEnabledFor(Priority.WARN)) {
            log.warn("Channel=" + name + " - Exception while polling channel", e);
        }
    } catch (NoClassDefFoundError ncdf) {
        // Throw if SSL / redirection to HTTPS
        if (log.isEnabledFor(Priority.WARN)) {
            log.warn("Channel=" + name + " - NoClassDefFound", ncdf);
        }
    } finally {
        connected = false;
        polling = false;
    }

}

From source file:org.methodize.nntprss.feed.Channel.java

/**
 * Simple channel validation - ensures URL
 * is valid, XML document is returned, and
 * document has an rss root element with a 
 * version, or rdf root element, //from   www.  ja  va  2  s  . c o m
 */
public static boolean isValid(URL url) throws HttpUserException {
    boolean valid = false;
    try {
        //         System.setProperty("networkaddress.cache.ttl", "0");

        HttpClient client = new HttpClient();
        ChannelManager.getChannelManager().configureHttpClient(client);
        if (url.getUserInfo() != null) {
            client.getState().setCredentials(null, null,
                    new UsernamePasswordCredentials(URLDecoder.decode(url.getUserInfo())));
        }

        String urlString = url.toString();
        HttpMethod method = null;

        int count = 0;
        HttpResult result = null;
        int statusCode = HttpStatus.SC_OK;
        boolean redirected = false;
        do {
            method = new GetMethod(urlString);
            method.setRequestHeader("User-agent", AppConstants.getUserAgent());
            method.setRequestHeader("Accept-Encoding", "gzip");
            method.setFollowRedirects(false);
            method.setDoAuthentication(true);

            HostConfiguration hostConfiguration = client.getHostConfiguration();
            URI hostURI = new URI(urlString);
            hostConfiguration.setHost(hostURI);

            result = executeHttpRequest(client, hostConfiguration, method);
            statusCode = result.getStatusCode();
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY
                    || statusCode == HttpStatus.SC_SEE_OTHER
                    || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
                redirected = true;
                // Resolve against current URI - may be a relative URI
                try {
                    urlString = new java.net.URI(urlString).resolve(result.getLocation()).toString();
                } catch (URISyntaxException use) {
                    // Fall back to just using location from result
                    urlString = result.getLocation();
                }
            } else {
                redirected = false;
            }

            //            method.getResponseBody();
            //            method.releaseConnection();
            count++;
        } while (count < 5 && redirected);

        // Only process if ok - if not ok (e.g. not modified), don't do anything
        if (statusCode == HttpStatus.SC_OK) {
            PushbackInputStream pbis = new PushbackInputStream(new ByteArrayInputStream(result.getResponse()),
                    PUSHBACK_BUFFER_SIZE);
            skipBOM(pbis);

            BufferedInputStream bis = new BufferedInputStream(pbis);
            DocumentBuilder db = AppConstants.newDocumentBuilder();
            Document rssDoc = db.parse(bis);
            Element rootElm = rssDoc.getDocumentElement();

            for (int i = 0; i < parsers.length; i++) {
                if (parsers[i].isParsable(rootElm)) {
                    valid = true;
                    break;
                }
            }
        } else if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            throw new HttpUserException(statusCode);
        } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new HttpUserException(statusCode);
        }

    } catch (URIException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return valid;
}

From source file:org.mulgara.resolver.http.HttpContent.java

private boolean isRedirected(int status) {
    return (status == HttpStatus.SC_TEMPORARY_REDIRECT || status == HttpStatus.SC_MOVED_TEMPORARILY
            || status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_SEE_OTHER);
}

From source file:org.nuxeo.opensocial.shindig.gadgets.NXHttpFetcher.java

/** {@inheritDoc} */
public HttpResponse fetch(HttpRequest request) {
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod;/*from   ww w .  j  av  a2 s  . c o m*/
    String methodType = request.getMethod();
    String requestUri = request.getUri().toString();

    ProxyHelper.fillProxy(httpClient, requestUri);

    // true for non-HEAD requests
    boolean requestCompressedContent = true;

    if ("POST".equals(methodType) || "PUT".equals(methodType)) {
        EntityEnclosingMethod enclosingMethod = ("POST".equals(methodType)) ? new PostMethod(requestUri)
                : new PutMethod(requestUri);

        if (request.getPostBodyLength() > 0) {
            enclosingMethod.setRequestEntity(new InputStreamRequestEntity(request.getPostBody()));
            enclosingMethod.setRequestHeader("Content-Length", String.valueOf(request.getPostBodyLength()));
        }
        httpMethod = enclosingMethod;
    } else if ("DELETE".equals(methodType)) {
        httpMethod = new DeleteMethod(requestUri);
    } else if ("HEAD".equals(methodType)) {
        httpMethod = new HeadMethod(requestUri);
    } else {
        httpMethod = new GetMethod(requestUri);
    }

    httpMethod.setFollowRedirects(false);
    httpMethod.getParams().setSoTimeout(connectionTimeoutMs);

    if (requestCompressedContent)
        httpMethod.setRequestHeader("Accept-Encoding", "gzip, deflate");

    for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
        httpMethod.setRequestHeader(entry.getKey(), StringUtils.join(entry.getValue(), ','));
    }

    try {

        int statusCode = httpClient.executeMethod(httpMethod);

        // Handle redirects manually
        if (request.getFollowRedirects() && ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
                || (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) || (statusCode == HttpStatus.SC_SEE_OTHER)
                || (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT))) {

            Header header = httpMethod.getResponseHeader("location");
            if (header != null) {
                String redirectUri = header.getValue();

                if ((redirectUri == null) || (redirectUri.equals(""))) {
                    redirectUri = "/";
                }
                httpMethod.releaseConnection();
                httpMethod = new GetMethod(redirectUri);

                statusCode = httpClient.executeMethod(httpMethod);
            }
        }

        return makeResponse(httpMethod, statusCode);

    } catch (IOException e) {
        if (e instanceof java.net.SocketTimeoutException || e instanceof java.net.SocketException) {
            return HttpResponse.timeout();
        }

        return HttpResponse.error();

    } finally {
        httpMethod.releaseConnection();
    }
}

From source file:org.olat.user.propertyhandlers.ICQPropertyHandler.java

/**
 * @see org.olat.user.propertyhandlers.Generic127CharTextPropertyHandler#isValid(org.olat.core.gui.components.form.flexible.FormItem, java.util.Map)
 *//*w  ww  .ja  v a  2  s .com*/
@SuppressWarnings({ "unchecked", "unused" })
@Override
public boolean isValid(final FormItem formItem, final Map formContext) {
    boolean result;
    final TextElement textElement = (TextElement) formItem;
    OLog log = Tracing.createLoggerFor(this.getClass());
    if (StringHelper.containsNonWhitespace(textElement.getValue())) {

        // Use an HttpClient to fetch a profile information page from ICQ.
        final HttpClient httpClient = HttpClientFactory.getHttpClientInstance();
        final HttpClientParams httpClientParams = httpClient.getParams();
        httpClientParams.setConnectionManagerTimeout(2500);
        httpClient.setParams(httpClientParams);
        final HttpMethod httpMethod = new GetMethod(ICQ_NAME_VALIDATION_URL);
        final NameValuePair uinParam = new NameValuePair(ICQ_NAME_URL_PARAMETER, textElement.getValue());
        httpMethod.setQueryString(new NameValuePair[] { uinParam });
        // Don't allow redirects since otherwise, we won't be able to get the HTTP 302 further down.
        httpMethod.setFollowRedirects(false);
        try {
            // Get the user profile page
            httpClient.executeMethod(httpMethod);
            final int httpStatusCode = httpMethod.getStatusCode();
            // Looking at the HTTP status code tells us whether a user with the given ICQ name exists.
            if (httpStatusCode == HttpStatus.SC_OK) {
                // ICQ tells us that a user name is valid if it sends an HTTP 200...
                result = true;
            } else if (httpStatusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                // ...and if it's invalid, it sends an HTTP 302.
                textElement.setErrorKey("form.name.icq.error", null);
                result = false;
            } else {
                // For HTTP status codes other than 200 and 302 we will silently assume that the given ICQ name is valid, but inform the user about this.
                textElement.setExampleKey("form.example.icqname.notvalidated", null);
                log.warn("ICQ name validation: Expected HTTP status 200 or 301, but got " + httpStatusCode);
                result = true;
            }
        } catch (final Exception e) {
            // In case of any exception, assume that the given ICQ name is valid (The opposite would block easily upon network problems), and inform the user about
            // this.
            textElement.setExampleKey("form.example.icqname.notvalidated", null);
            log.warn("ICQ name validation: Exception: " + e.getMessage());
            result = true;
        }
    } else {
        result = true;
    }
    log = null;
    return result;
}

From source file:org.openlaszlo.data.HTTPDataSource.java

/**
 * convenience routine missing from http library
 *///  w  w w  . j a  v a  2 s.c o m
static boolean isRedirect(int rc) {
    return (rc == HttpStatus.SC_MOVED_PERMANENTLY || rc == HttpStatus.SC_MOVED_TEMPORARILY
            || rc == HttpStatus.SC_SEE_OTHER || rc == HttpStatus.SC_TEMPORARY_REDIRECT);
}

From source file:org.opens.tanaguru.util.http.HttpRequestHandler.java

private int computeStatus(int status) {
    switch (status) {
    case HttpStatus.SC_FORBIDDEN:
    case HttpStatus.SC_METHOD_NOT_ALLOWED:
    case HttpStatus.SC_BAD_REQUEST:
    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_PAYMENT_REQUIRED:
    case HttpStatus.SC_NOT_FOUND:
    case HttpStatus.SC_NOT_ACCEPTABLE:
    case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
    case HttpStatus.SC_REQUEST_TIMEOUT:
    case HttpStatus.SC_CONFLICT:
    case HttpStatus.SC_GONE:
    case HttpStatus.SC_LENGTH_REQUIRED:
    case HttpStatus.SC_PRECONDITION_FAILED:
    case HttpStatus.SC_REQUEST_TOO_LONG:
    case HttpStatus.SC_REQUEST_URI_TOO_LONG:
    case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:
    case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE:
    case HttpStatus.SC_EXPECTATION_FAILED:
    case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE:
    case HttpStatus.SC_METHOD_FAILURE:
    case HttpStatus.SC_UNPROCESSABLE_ENTITY:
    case HttpStatus.SC_LOCKED:
    case HttpStatus.SC_FAILED_DEPENDENCY:
    case HttpStatus.SC_INTERNAL_SERVER_ERROR:
    case HttpStatus.SC_NOT_IMPLEMENTED:
    case HttpStatus.SC_BAD_GATEWAY:
    case HttpStatus.SC_SERVICE_UNAVAILABLE:
    case HttpStatus.SC_GATEWAY_TIMEOUT:
    case HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED:
    case HttpStatus.SC_INSUFFICIENT_STORAGE:
        return 0;
    case HttpStatus.SC_CONTINUE:
    case HttpStatus.SC_SWITCHING_PROTOCOLS:
    case HttpStatus.SC_PROCESSING:
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
    case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
    case HttpStatus.SC_NO_CONTENT:
    case HttpStatus.SC_RESET_CONTENT:
    case HttpStatus.SC_PARTIAL_CONTENT:
    case HttpStatus.SC_MULTI_STATUS:
    case HttpStatus.SC_MULTIPLE_CHOICES:
    case HttpStatus.SC_MOVED_PERMANENTLY:
    case HttpStatus.SC_MOVED_TEMPORARILY:
    case HttpStatus.SC_SEE_OTHER:
    case HttpStatus.SC_NOT_MODIFIED:
    case HttpStatus.SC_USE_PROXY:
    case HttpStatus.SC_TEMPORARY_REDIRECT:
        return 1;
    default://from w w w . j a v a2 s  . c om
        return 1;
    }
}

From source file:org.portletbridge.portlet.PortletBridgeServlet.java

protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    // get the id
    final String id = portletBridgeService.getIdFromRequestUri(request.getContextPath(),
            request.getRequestURI());//from   ww  w .  ja v a2  s  . c om
    // look up the data associated with that id from the session
    HttpSession session = request.getSession();
    if (session == null) {
        throw new ServletException(resourceBundle.getString("error.nosession"));
    }
    final PortletBridgeMemento memento = (PortletBridgeMemento) session.getAttribute(mementoSessionKey);
    if (memento == null) {
        throw new ServletException(resourceBundle.getString("error.nomemento"));
    }
    final BridgeRequest bridgeRequest = memento.getBridgeRequest(id);
    if (bridgeRequest == null) {
        throw new ServletException(resourceBundle.getString("error.nobridgerequest"));
    }
    final PerPortletMemento perPortletMemento = memento.getPerPortletMemento(bridgeRequest.getPortletId());
    if (perPortletMemento == null) {
        throw new ServletException(resourceBundle.getString("error.noperportletmemento"));
    }

    // go and fetch the data from the backend as appropriate
    final URI url = bridgeRequest.getUrl();

    log.debug("doPost(): URL=" + url);

    try {
        PostMethod postMethod = new PostMethod(url.toString());
        copyRequestHeaders(request, postMethod);
        postMethod.setRequestEntity(new InputStreamRequestEntity(request.getInputStream()));
        httpClientTemplate.service(postMethod, perPortletMemento, new HttpClientCallback() {
            public Object doInHttpClient(int statusCode, HttpMethodBase method)
                    throws ResourceException, Throwable {
                if (statusCode == HttpStatus.SC_OK) {
                    // if it's text/html then store it and redirect
                    // back to the portlet render view (portletUrl)
                    Header responseHeader = method.getResponseHeader("Content-Type");
                    if (responseHeader != null && responseHeader.getValue().startsWith("text/html")) {
                        String content = ResourceUtil.getString(method.getResponseBodyAsStream(),
                                method.getResponseCharSet());
                        // TODO: think about cleaning this up if we
                        // don't get back to the render
                        perPortletMemento.enqueueContent(bridgeRequest.getId(),
                                new PortletBridgeContent(url, "post", content));
                        // redirect
                        // TODO: worry about this... adding the id
                        // at the end

                        log.debug("doPost(): doing response.sendRedirect to URL=" + bridgeRequest.getPageUrl());

                        response.sendRedirect(bridgeRequest.getPageUrl());
                    } else {
                        // if it's anything else then stream it
                        // back... consider stylesheets and
                        // javascript
                        // TODO: javascript and css rewriting
                        response.setContentType(method.getResponseHeader("Content-Type").toExternalForm());
                        ResourceUtil.copy(method.getResponseBodyAsStream(), response.getOutputStream(), 4096);
                    }
                } else if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                    Header locationHeader = method.getResponseHeader("Location");
                    if (locationHeader != null) {
                        URI redirectUrl = new URI(locationHeader.getValue().trim());
                        log.debug("redirecting to [" + redirectUrl + "]");
                        PseudoRenderResponse renderResponse = createRenderResponse(bridgeRequest);
                        BridgeRequest updatedBridgeRequest = memento.createBridgeRequest(renderResponse,
                                new DefaultIdGenerator().nextId(), redirectUrl);
                        fetch(request, response, updatedBridgeRequest, memento, perPortletMemento, redirectUrl);

                    } else {
                        throw new PortletBridgeException("error.missingLocation");
                    }
                } else {
                    // if there is a problem with the status code
                    // then return that error back
                    response.sendError(statusCode);
                }
                return null;
            }
        });
    } catch (ResourceException resourceException) {
        String format = MessageFormat.format(resourceBundle.getString(resourceException.getMessage()),
                resourceException.getArgs());
        throw new ServletException(format, resourceException);
    }
}

From source file:org.svenk.redmine.core.client.AbstractRedmineClient.java

public void uploadAttachment(int ticketId, String fileName, String comment, String description,
        AbstractTaskAttachmentSource source, IProgressMonitor monitor) throws RedmineException {
    PostMethod method = new PostMethod(REDMINE_URL_TICKET_EDIT + ticketId);

    //assigned by RedmineAuthenticityTokenAspect
    NameValuePair tokenValue = method.getParameter(CLIENT_FIELD_CSRF_TOKEN);

    List<Part> parts = new ArrayList<Part>(4);
    parts.add(new StringPart(CLIENT_FIELD_ATTACHMENT_DESCRIPTION, description, characterEncoding));
    parts.add(new StringPart(CLIENT_FIELD_ATTACHMENT_NOTES, comment, characterEncoding));
    if (tokenValue != null) {
        parts.add(new StringPart(CLIENT_FIELD_CSRF_TOKEN, tokenValue == null ? "" : tokenValue.getValue(), //$NON-NLS-1$
                characterEncoding));// w  w  w .ja v  a 2  s .c  om
    }

    //Workaround: http://rack.lighthouseapp.com/projects/22435/tickets/79-multipart-handling-incorrectly-assuming-file-upload
    for (Part part : parts) {
        ((StringPart) part).setContentType(null);
    }

    parts.add(new FilePart(CLIENT_FIELD_ATTACHMENT_FILE, new TaskAttachmentPartSource(source, fileName),
            source.getContentType(), this.httpClient.getParams().getContentCharset()));
    method.setRequestEntity(
            new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), method.getParams()));

    String errorMsg = executeMethod(method, submitErrorParser, monitor, HttpStatus.SC_OK,
            HttpStatus.SC_MOVED_TEMPORARILY);
    if (errorMsg != null) {
        throw new RedmineStatusException(IStatus.INFO, errorMsg);
    }
}