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:helma.servlet.AbstractServletClient.java

void sendRedirect(HttpServletRequest req, HttpServletResponse res, String url, int status) {
    String location = url;/*from  w  ww  .j av  a 2 s . co m*/

    if (url.indexOf("://") == -1) {
        // need to transform a relative URL into an absolute one
        String scheme = req.getScheme();
        StringBuffer loc = new StringBuffer(scheme);

        loc.append("://");
        loc.append(req.getServerName());

        int p = req.getServerPort();

        // check if we need to include server port
        if ((p > 0) && (("http".equals(scheme) && (p != 80)) || ("https".equals(scheme) && (p != 443)))) {
            loc.append(":");
            loc.append(p);
        }

        if (!url.startsWith("/")) {
            String requri = req.getRequestURI();
            int lastSlash = requri.lastIndexOf("/");

            if (lastSlash == (requri.length() - 1)) {
                loc.append(requri);
            } else if (lastSlash > -1) {
                loc.append(requri.substring(0, lastSlash + 1));
            } else {
                loc.append("/");
            }
        }

        loc.append(url);
        location = loc.toString();
    }

    // if status code was explicitly set use that, or use 303 for HTTP 1.1,
    // 302 for earlier protocol versions
    if (status >= 301 && status <= 303) {
        res.setStatus(status);
    } else if (isOneDotOne(req.getProtocol())) {
        res.setStatus(HttpServletResponse.SC_SEE_OTHER);
    } else {
        res.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    }

    res.setContentType("text/html");
    res.setHeader("Location", location);
}

From source file:com.zimbra.cs.dav.service.DavServlet.java

@Override
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ZimbraLog.clearContext();/*from   w ww.jav a 2  s. co m*/
    addRemoteIpToLoggingContext(req);
    ZimbraLog.addUserAgentToContext(req.getHeader(DavProtocol.HEADER_USER_AGENT));

    //bug fix - send 400 for Range requests
    String rangeHeader = req.getHeader(DavProtocol.HEADER_RANGE);
    if (null != rangeHeader) {
        sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "Range header not supported", null, Level.debug);
        return;
    }

    RequestType rtype = getAllowedRequestType(req);
    ZimbraLog.dav.debug("Allowable request types %s", rtype);

    if (rtype == RequestType.none) {
        sendError(resp, HttpServletResponse.SC_NOT_ACCEPTABLE, "Not an allowed request type", null,
                Level.debug);
        return;
    }

    logRequestInfo(req);
    Account authUser = null;
    DavContext ctxt;
    try {
        AuthToken at = AuthProvider.getAuthToken(req, false);
        if (at != null && (at.isExpired() || !at.isRegistered())) {
            at = null;
        }
        if (at != null && (rtype == RequestType.both || rtype == RequestType.authtoken)) {
            authUser = Provisioning.getInstance().get(AccountBy.id, at.getAccountId());
        } else if (at == null && (rtype == RequestType.both || rtype == RequestType.password)) {
            AuthUtil.AuthResult result = AuthUtil.basicAuthRequest(req, resp, true, this);
            if (result.sendErrorCalled) {
                logResponseInfo(resp);
                return;
            }
            authUser = result.authorizedAccount;
        }
        if (authUser == null) {
            try {
                sendError(resp, HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed", null,
                        Level.debug);
            } catch (Exception e) {
            }
            return;
        }
        ZimbraLog.addToContext(ZimbraLog.C_ANAME, authUser.getName());
        ctxt = new DavContext(req, resp, authUser);
    } catch (AuthTokenException e) {
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error getting authenticated user", e);
        return;
    } catch (ServiceException e) {
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error getting authenticated user", e);
        return;
    }

    DavMethod method = sMethods.get(req.getMethod());
    if (method == null) {
        setAllowHeader(resp);
        sendError(resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Not an allowed method", null, Level.debug);
        return;
    }

    long t0 = System.currentTimeMillis();

    CacheStates cache = null;
    try {
        if (ZimbraLog.dav.isDebugEnabled()) {
            try {
                Upload upload = ctxt.getUpload();
                if (upload.getSize() > 0 && upload.getContentType().startsWith("text")) {
                    if (ZimbraLog.dav.isDebugEnabled()) {
                        StringBuilder logMsg = new StringBuilder("REQUEST\n").append(
                                new String(ByteUtil.readInput(upload.getInputStream(), -1, 20480), "UTF-8"));
                        ZimbraLog.dav.debug(logMsg.toString());
                    }
                }
            } catch (DavException de) {
                throw de;
            } catch (Exception e) {
                ZimbraLog.dav.debug("ouch", e);
            }
        }
        cache = checkCachedResponse(ctxt, authUser);
        if (!ctxt.isResponseSent() && !isProxyRequest(ctxt, method)) {

            method.checkPrecondition(ctxt);
            method.handle(ctxt);
            method.checkPostcondition(ctxt);
            if (!ctxt.isResponseSent()) {
                resp.setStatus(ctxt.getStatus());
            }
        }
        if (!ctxt.isResponseSent()) {
            logResponseInfo(resp);
        }
    } catch (DavException e) {
        if (e.getCause() instanceof MailServiceException.NoSuchItemException
                || e.getStatus() == HttpServletResponse.SC_NOT_FOUND)
            ZimbraLog.dav.info(ctxt.getUri() + " not found");
        else if (e.getStatus() == HttpServletResponse.SC_MOVED_TEMPORARILY
                || e.getStatus() == HttpServletResponse.SC_MOVED_PERMANENTLY)
            ZimbraLog.dav.info("sending redirect");

        try {
            if (e.isStatusSet()) {
                resp.setStatus(e.getStatus());
                if (e.hasErrorMessage())
                    e.writeErrorMsg(resp.getOutputStream());
                if (ZimbraLog.dav.isDebugEnabled()) {
                    ZimbraLog.dav.info("sending http error %d because: %s", e.getStatus(), e.getMessage(), e);
                } else {
                    ZimbraLog.dav.info("sending http error %d because: %s", e.getStatus(), e.getMessage());
                }
                if (e.getCause() != null)
                    ZimbraLog.dav.debug("exception: ", e.getCause());
            } else {
                sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "error handling method " + method.getName(), e);
            }
        } catch (IllegalStateException ise) {
            ZimbraLog.dav.debug("can't write error msg", ise);
        }
    } catch (ServiceException e) {
        if (e instanceof MailServiceException.NoSuchItemException) {
            sendError(resp, HttpServletResponse.SC_NOT_FOUND, ctxt.getUri() + " not found", null, Level.info);
            return;
        }
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "error handling method " + method.getName(), e);
    } catch (Exception e) {
        try {
            sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "error handling method " + method.getName(), e);
        } catch (Exception ex) {
        }
    } finally {
        long t1 = System.currentTimeMillis();
        ZimbraLog.dav.info("DavServlet operation " + method.getName() + " to " + req.getPathInfo() + " (depth: "
                + ctxt.getDepth().name() + ") finished in " + (t1 - t0) + "ms");
        if (cache != null)
            cacheCleanUp(ctxt, cache);
        ctxt.cleanup();
    }
}

From source file:axiom.servlet.AbstractServletClient.java

void sendRedirect(HttpServletRequest req, HttpServletResponse res, String url) {
    String location = url;//from ww  w  .j  a v  a  2s  .  c o m

    if (url.indexOf("://") == -1) {
        // need to transform a relative URL into an absolute one
        String scheme = req.getScheme();
        StringBuffer loc = new StringBuffer(scheme);

        loc.append("://");
        String hostname = req.getServerName();
        boolean forwarded = false;
        if (req.getHeader("X-Forwarded-Host") != null) {
            hostname = req.getHeader("X-Forwarded-Host");
            forwarded = true;
        }
        loc.append(hostname);

        int p = (!forwarded) ? req.getServerPort() : 80;

        // check if we need to include server port
        if ((p > 0) && (("http".equals(scheme) && (p != 80)) || ("https".equals(scheme) && (p != 443)))) {
            loc.append(":");
            loc.append(p);
        }

        if (!url.startsWith("/")) {
            String requri = req.getRequestURI();
            int lastSlash = requri.lastIndexOf("/");

            if (lastSlash == (requri.length() - 1)) {
                loc.append(requri);
            } else if (lastSlash > -1) {
                loc.append(requri.substring(0, lastSlash + 1));
            } else {
                loc.append("/");
            }
        }

        loc.append(url);
        location = loc.toString();
    }

    // send status code 303 for HTTP 1.1, 302 otherwise
    if (isOneDotOne(req.getProtocol())) {
        res.setStatus(HttpServletResponse.SC_SEE_OTHER);
    } else {
        res.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    }

    res.setContentType("text/html");
    res.setHeader("Location", location);
}

From source file:org.nuxeo.ecm.core.opencmis.impl.CmisSuiteSession2.java

@Test
public void testContentStreamRedirect() throws Exception {
    useDummyCmisBlobProvider();/*from ww w  . j a va2  s  .  c o m*/
    setUpData();
    session.clear(); // clear cache

    assumeTrue(isAtomPub || isBrowser);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setRedirectStrategy(NeverRedirectStrategy.INSTANCE); // to check Location header manually
    try (CloseableHttpClient httpClient = httpClientBuilder.build()) {
        String uri = getURI("/testfolder1/testfile1") + "&testredirect=true"; // to provoke a redirect in our dummy blob provider
        HttpGet request = new HttpGet(uri);
        request.setHeader("Authorization", BASIC_AUTH);
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, response.getStatusLine().getStatusCode());
            Header locationHeader = response.getFirstHeader("Location");
            assertNotNull(locationHeader);
            assertEquals("http://example.com/dummyedirect", locationHeader.getValue());
        }
    }
}

From source file:com.sourcesense.confluence.servlets.CMISProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link HttpServletResponse}
 *
 * @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
 * @param httpServletRequest Request object pertaining to the proxied HTTP request
 * @throws IOException      Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has occurred
 *///from   w  w  w .  j a va2  s. c  o  m
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    // Create a default HttpClient
    HttpClient httpClient = new HttpClient();
    getCredential(httpServletRequest.getParameter("servername"));
    if (credentials != null) {
        httpClient.getParams().setAuthenticationPreemptive(true);
        httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    }
    httpMethodProxyRequest.setFollowRedirects(true);
    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    String response = httpMethodProxyRequest.getResponseBodyAsString();

    // 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();
        if (followRedirects) {
            if (stringLocation.contains("jsessionid")) {
                Cookie cookie = new Cookie("JSESSIONID",
                        stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11));
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);
                //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL");
            } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) {
                Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie");
                String[] cookieDetails = header.getValue().split(";");
                String[] nameValue = cookieDetails[0].split("=");

                Cookie cookie = new Cookie(nameValue[0], nameValue[1]);
                cookie.setPath("/");
                //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath());
                httpServletResponse.addCookie(cookie);
            }
            httpServletResponse.sendRedirect(stringLocation
                    .replace(getProxyHostAndPort(httpServletRequest) + this.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 (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked")
                || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header
                header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth
            // proxy servlet does not support chunked encoding
        } else {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }
    }

    List<Header> responseHeaders = Arrays.asList(headerArrayResponse);

    if (isBodyParameterGzipped(responseHeaders)) {
        debug("GZipped: true");
        if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) {
            response = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            intProxyResponseCode = HttpServletResponse.SC_OK;
            httpServletResponse.setHeader(STRING_LOCATION_HEADER, response);
        } else {
            response = new String(ungzip(httpMethodProxyRequest.getResponseBody()));
        }
        httpServletResponse.setContentLength(response.length());
    }

    // Send the content to the client
    if (intProxyResponseCode == 200)
        httpServletResponse.getWriter().write(response);
    else
        httpServletResponse.getWriter().write(intProxyResponseCode);
}

From source file:com.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Executes the {@link org.apache.commons.httpclient.HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link javax.servlet.http.HttpServletResponse}
 *
 * @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 org.apache.commons.httpclient.HttpClient}.executeMethod
 * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred
 *//*from  w w  w.  j a  v  a 2s  .c  o m*/
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {

    if (httpServletRequest.isSecure()) {
        Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443));
    }
    // Create a default HttpClient
    HttpClient httpClient = new HttpClient();
    httpMethodProxyRequest.setFollowRedirects(false);
    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    InputStream response = httpMethodProxyRequest.getResponseBodyAsStream();

    // 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();
        if (followRedirects) {
            if (stringLocation.contains("jsessionid")) {
                Cookie cookie = new Cookie("JSESSIONID",
                        stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11));
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);
                //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL");
            } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) {
                Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie");
                String[] cookieDetails = header.getValue().split(";");
                String[] nameValue = cookieDetails[0].split("=");

                Cookie cookie = new Cookie(nameValue[0], nameValue[1]);
                cookie.setPath("/");
                //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath());
                httpServletResponse.addCookie(cookie);
            }
            httpServletResponse.sendRedirect(
                    stringLocation.replace(getProxyHostAndPort() + this.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 (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked")
                || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header
                header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth
            // proxy servlet does not support chunked encoding
        } else {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }
    }

    List<Header> responseHeaders = Arrays.asList(headerArrayResponse);

    if (isBodyParameterGzipped(responseHeaders)) {
        debug("GZipped: true");
        int length = 0;

        if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) {
            String gz = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            intProxyResponseCode = HttpServletResponse.SC_OK;
            httpServletResponse.setHeader(STRING_LOCATION_HEADER, gz);
        } else {
            final byte[] bytes = ungzip(httpMethodProxyRequest.getResponseBody());
            length = bytes.length;
            response = new ByteArrayInputStream(bytes);
        }
        httpServletResponse.setContentLength(length);
    }

    // Send the content to the client
    debug("Received status code: " + intProxyResponseCode, "Response: " + response);

    //httpServletResponse.getWriter().write(response);
    copy(response, httpServletResponse.getOutputStream());
}

From source file:de.fuberlin.wiwiss.marbles.MarblesServlet.java

/**
 * Discovers an URI and renders a given view for it (<code>view</code>).
 *
 * @param request//from  ww  w . java2  s  .  com
 * @param response
 * @throws IOException
 */
public void fresnelView(HttpServletRequest request, HttpServletResponse response) throws IOException {
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
    String errorString = null;
    Selection selected = null;
    List<org.apache.commons.httpclient.URI> retrievedURLs = null;
    Resource focalResource = null;
    Configuration conf = null;
    String redirectLocation = null;

    try {
        /* Reload the Fresnel configuration using the provided language */
        String langPref = (request.getParameter("lang") != null ? request.getParameter("lang") : "en");
        loadFresnelConfig(langPref);

        conf = new Configuration(confRepository, ontoRepository);

        /* Create the focal resource */
        if (request.getParameter("uri") != null) {
            String uriString = request.getParameter("uri");
            if (uriString.startsWith("_:")) /* blank node */
                focalResource = valueFactory.createBNode(uriString.substring(2));
            else
                focalResource = valueFactory.createURI(uriString);

            /* Collect data about the focal resource */
            if (request.getParameter("skipload") == null) {
                retrievedURLs = semwebClient.discoverResource(focalResource, true /* wait */);
            } /* skip */

            /* Initiate manual owl:sameAs inference */
            if (request.getParameter("skipInference") == null) {
                sameAsInferencer.addInferredForResource(focalResource);
            }

            if (conf.hasWarnings())
                writer.println(conf.getWarningsString());

            Purpose purpose = null;

            /* Look up the requested lens purpose */
            if (request.getParameter("purpose") != null
                    && (!request.getParameter("purpose").equals("defaultPurpose")))
                purpose = new Purpose(new URIImpl(Constants.nsFresnelExt + request.getParameter("purpose")));
            else
                purpose = new Purpose(new URIImpl(
                        "http://www.w3.org/2004/09/fresnel#defaultLens")); /* this must be provided, or a random lens is chosen */

            try {
                /* Perform Fresnel selection using the requested display purpose and language */
                selected = conf.select(dataRepository, focalResource, purpose, langPref);

                /* Perform Fresnel formatting */
                selected = conf.format(dataRepository, selected);
            } catch (NoResultsException e) {

                /* 
                 * If no results are found, redirect the user to the resource
                 * if it is not an RDF document.
                 * This code is not reached when there already is some data about the resource.
                 */
                RepositoryConnection metaDataConn = null;
                try {
                    metaDataConn = metaDataRepository.getConnection();

                    /* Manual support for one level of redirects */
                    String resourceRedirect = cacheController.getCachedHeaderDataValue(metaDataConn,
                            focalResource, "location");
                    Resource resourceURI = (resourceRedirect == null ? focalResource
                            : new URIImpl(resourceRedirect));

                    /* Get target content type */
                    String contentType = cacheController.getCachedHeaderDataValue(metaDataConn, resourceURI,
                            "content-type");
                    if (contentType != null && !ContentTypes.isRDF(contentType)) {
                        redirectLocation = focalResource.toString();
                    }
                } catch (RepositoryException re) {
                    re.printStackTrace();
                } catch (IllegalArgumentException ie) {
                    ie.printStackTrace();
                } finally {
                    try {
                        if (metaDataConn != null)
                            metaDataConn.close();
                    } catch (RepositoryException re) {
                        re.printStackTrace();
                    }
                }
            }
        } /* uri != null */
    } catch (Exception e) {
        e.printStackTrace();
        errorString = e.getMessage();
    }

    /* Output */
    try {
        /* Handle redirection to non-RDF data */
        if (redirectLocation != null) {
            response.setHeader("Location", redirectLocation);
            response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        } else { /* Perform XSL output */

            /*
             * When there are no results, we still need a selection object in 
             * order to render the fresnel tree
             */
            if (selected == null)
                selected = new Selection(conf);

            Document fresnelTree = selected.render();
            addSources(fresnelTree, retrievedURLs);

            /* Prepare XSLT */
            StreamSource styleSource = new StreamSource(
                    new File(dataRoot + "/" + xslDirectory + "/" + xslTransformation));
            net.sf.saxon.TransformerFactoryImpl tf = new net.sf.saxon.TransformerFactoryImpl();
            Transformer styleTransformer = tf.newTransformer(styleSource);

            /* Debug output */
            if (request.getParameter("debug") != null) {
                /* debug output: fresnel tree */
                StringWriter stringWriter = new StringWriter();
                Transformer treeTransformer = tf.newTransformer();
                treeTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
                treeTransformer.transform(new DOMSource(fresnelTree), new StreamResult(stringWriter));
                styleTransformer.setParameter("fresnelTree", stringWriter.getBuffer().toString());
            }

            /* Apply parameters */
            styleTransformer.setParameter("assetsURL", assetsURL != null ? assetsURL.toString() : "");
            styleTransformer.setParameter("serviceURL", serviceURL != null ? serviceURL.toString() : "");
            styleTransformer.setParameter("errorString", errorString);
            styleTransformer.setParameter("mainResource",
                    focalResource != null ? focalResource.toString() : "");
            if (request.getParameter("purpose") != null)
                styleTransformer.setParameter("purpose", request.getParameter("purpose"));
            else
                styleTransformer.setParameter("purpose", "defaultPurpose");

            if (request.getParameter("mobile") != null)
                styleTransformer.setParameter("isMobile", request.getParameter("mobile"));

            HashMap<String, String[]> newParameters = new HashMap<String, String[]>(request.getParameterMap());

            if (!newParameters.containsKey("lang"))
                newParameters.put("lang", new String[] { "en" });

            for (Object key : new String[] { "purpose", "uri" }) {
                newParameters.remove(key);
            }

            String parameterString = "";

            /* Serialize parameters for use in HTML links and forms */
            for (Object key : newParameters.keySet()) {
                parameterString += (parameterString.equals("") ? "" : "&") + key + "="
                        + ((String[]) newParameters.get(key))[0];
            }

            styleTransformer.setParameter("sessionParams", parameterString);

            /* Perform rendering */
            StreamResult res = new StreamResult(writer);
            styleTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
            styleTransformer.transform(new DOMSource(fresnelTree), res);
        }
    } catch (Exception e) {
        e.printStackTrace();
        writer.print(e.getMessage());
    } finally {
    }
}

From source file:net.voidfunction.rm.common.FileServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.getSession().setMaxInactiveInterval(120);
    response.setHeader("Date", HTTPUtils.getServerTime(0));

    // Parse the filename and the ID out of the URL
    String[] urlParts = request.getRequestURI().substring(1).split("/");
    if (urlParts.length < 2) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;/*from w  ww  .  j a  va 2s . c  o  m*/
    }
    String fileID = urlParts[1];
    String fileName = "";
    if (urlParts.length > 2)
        fileName = urlParts[2];

    String logOut = "File " + fileID + " (" + fileName + ") requested by " + request.getRemoteHost()
            + " [Result: ";

    RMFile file = node.getFileRepository().getFileById(fileID);
    if (file == null) {
        // File  with given ID not found - no redirect for you.
        logOut += "Not found]";
        node.getLog().info(logOut);

        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        response.getWriter().write("<b>404 Not Found</b><br/>Could not find a file with ID " + fileID);
        return;
    }

    boolean workerDL = (fileName.equals("Worker-Download"));
    if (workerDL)
        logOut += " (Worker Download) ";

    // Let the download listener know, if any, but don't count worker downloads
    if (dlListener != null && !workerDL)
        dlListener.fileDownloaded(file);

    String redirURL = null;
    if (locator != null)
        redirURL = (String) request.getSession().getAttribute("fileURL-" + fileID);
    if (redirURL == null && locator != null)
        redirURL = locator.locateURL(fileID, fileName);
    if (redirURL != null) {
        node.getLog().debug("Found redirect URL: " + redirURL);
        request.getSession().setAttribute("fileURL-" + fileID, redirURL);
        // Redirect to the new URL
        logOut += "Redirect]";
        node.getLog().info(logOut);

        response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        response.setHeader("Location", redirURL);
    } else {
        // We have to try to find it ourselves

        logOut += "Found locally]";
        node.getLog().info(logOut);

        // Caching magic - we can safely assume the file won't change
        String etag = Hex.encodeHexString(file.getHash());
        response.setHeader("ETag", etag);
        String ifModifiedSince = request.getHeader("If-Modified-Since");
        String ifNoneMatch = request.getHeader("If-None-Match");
        boolean etagMatch = (ifNoneMatch != null) && (ifNoneMatch.equals(etag));

        if (ifModifiedSince != null || etagMatch) {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            response.setHeader("Last-Modified", ifModifiedSince);
        } else {
            // Send the HTTP response and file data
            response.setStatus(HttpServletResponse.SC_OK);
            response.setHeader("Expires", HTTPUtils.getServerTime(3600));
            response.setHeader("Cache-Control", "max-age=3600");
            response.setContentType(file.getMimetype());
            response.setHeader("Content-Length", String.valueOf(file.getSize()));

            // Stream the file data to the output stream using Apache IOUtils
            InputStream fileIn = node.getFileRepository().getFileData(fileID);
            IOUtils.copyLarge(fileIn, response.getOutputStream());
        }
    }
}

From source file:net.voidfunction.rm.master.AdminServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Set headers to prevent caching of pages
    response.setHeader("Date", HTTPUtils.getServerTime(0));
    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);
    response.setHeader("Expires", HTTPUtils.getServerTime(0));
    response.setHeader("Cache-Control", "no-cache, must-revalidate, max-age=0");
    response.setHeader("Pragma", "no-cache");

    // Retrieve output for the correct page.
    String page = request.getParameter("page");
    if (page == null || page.equals("index"))
        response.getWriter().print(pageIndex(request));
    else if (page.equals("upload"))
        response.getWriter().print(pageUpload());
    else if (page.equals("delete")) {
        pageDelete(request);/*  ww  w  .jav  a2s  . c o m*/
        response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        response.setHeader("Location", ".");
    }

}