Example usage for javax.servlet.http HttpServletRequest getHeaderNames

List of usage examples for javax.servlet.http HttpServletRequest getHeaderNames

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getHeaderNames.

Prototype

public Enumeration<String> getHeaderNames();

Source Link

Document

Returns an enumeration of all the header names this request contains.

Usage

From source file:org.codehaus.wadi.web.impl.CommonsHttpProxy.java

protected void doProxy(URI uri, WebInvocation context) throws ProxyingException {
    HttpServletRequest hreq = context.getHreq();
    HttpServletResponse hres = context.getHres();

    long startTime = System.currentTimeMillis();

    String m = hreq.getMethod();//ww w .j a va2 s  . com
    Class clazz = (Class) _methods.get(m);
    if (clazz == null) {
        throw new IrrecoverableException("unsupported http method: " + m);
    }

    HttpMethod hm = null;
    try {
        hm = (HttpMethod) clazz.newInstance();
    } catch (Exception e) {
        throw new IrrecoverableException("could not create HttpMethod instance", e); // should never happen
    }

    String requestURI = getRequestURI(hreq);
    hm.setPath(requestURI);

    String queryString = hreq.getQueryString();
    if (queryString != null) {
        hm.setQueryString(queryString);
        requestURI += queryString;
    }

    hm.setFollowRedirects(false);
    //hm.setURI(new URI(uri));
    hm.setStrictMode(false);

    // check connection header
    String connectionHdr = hreq.getHeader("Connection"); // TODO - what if there are multiple values ?
    if (connectionHdr != null) {
        connectionHdr = connectionHdr.toLowerCase();
        if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close"))
            connectionHdr = null; // TODO  ??
    }

    // copy headers
    boolean xForwardedFor = false;
    boolean hasContent = false;
    int contentLength = 0;
    Enumeration enm = hreq.getHeaderNames();
    while (enm.hasMoreElements()) {
        // TODO could be better than this! - using javax.servlet ?
        String hdr = (String) enm.nextElement();
        String lhdr = hdr.toLowerCase();

        if (_DontProxyHeaders.contains(lhdr))
            continue;
        if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0)
            continue;

        if ("content-length".equals(lhdr)) {
            try {
                contentLength = hreq.getIntHeader(hdr);
                hasContent = contentLength > 0;
            } catch (NumberFormatException e) {
                if (_log.isWarnEnabled())
                    _log.warn("bad Content-Length header value: " + hreq.getHeader(hdr), e);
            }
        }

        if ("content-type".equals(lhdr)) {
            hasContent = true;
        }

        Enumeration vals = hreq.getHeaders(hdr);
        while (vals.hasMoreElements()) {
            String val = (String) vals.nextElement();
            if (val != null) {
                hm.addRequestHeader(hdr, val);
                // if (_log.isInfoEnabled()) _log.info("Request " + hdr + ": " + val);
                xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); // why is this not in the outer loop ?
            }
        }
    }

    // cookies...

    // although we copy cookie headers into the request abover - commons-httpclient thinks it knows better and strips them out before sending.
    // we have to explicitly use their interface to add the cookies - painful...

    // DOH! - an org.apache.commons.httpclient.Cookie is NOT a
    // javax.servlet.http.Cookie - and it looks like the two don't
    // map onto each other without data loss...
    HttpState state = new HttpState();
    javax.servlet.http.Cookie[] cookies = hreq.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            javax.servlet.http.Cookie c = cookies[i];
            String domain = c.getDomain();
            if (domain == null) {
                domain = hreq.getServerName(); // TODO - tmp test
                // _log.warn("defaulting cookie domain");
            }
            //     domain=null;
            String cpath = c.getPath();
            if (cpath == null) {
                cpath = hreq.getContextPath(); // fix for Jetty
                // _log.warn("defaulting cookie path");
            }
            //if (_log.isTraceEnabled()) _log.trace("PATH: value="+path+" length="+(path==null?0:path.length()));
            Cookie cookie = new Cookie(domain, c.getName(), c.getValue(), cpath, c.getMaxAge(), c.getSecure()); // TODO - sort out domain
            //if (_log.isTraceEnabled()) _log.trace("Cookie: "+cookie.getDomain()+","+ cookie.getName()+","+ cookie.getValue()+","+ cookie.getPath()+","+ cookie.getExpiryDate()+","+ cookie.getSecure());
            state.addCookie(cookie);
            //if (_log.isTraceEnabled()) _log.trace("Cookie: "+cookie.toString());
        }
    }

    // Proxy headers
    hm.addRequestHeader("Via", "1.1 " + hreq.getLocalName() + ":" + hreq.getLocalPort() + " \"WADI\"");
    if (!xForwardedFor)
        hm.addRequestHeader("X-Forwarded-For", hreq.getRemoteAddr());
    // Max-Forwards...

    // a little bit of cache control
    //      String cache_control = hreq.getHeader("Cache-Control");
    //      if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0))
    //      httpMethod.setUseCaches(false);

    // customize Connection
    //      uc.setDoInput(true);

    int client2ServerTotal = 0;
    if (hasContent) {
        //         uc.setDoOutput(true);

        try {
            if (hm instanceof EntityEnclosingMethod)
                ((EntityEnclosingMethod) hm).setRequestBody(hreq.getInputStream());
            // TODO - do we need to close response stream at end... ?
        } catch (IOException e) {
            throw new IrrecoverableException("could not pss request input across proxy", e);
        }
    }

    try {
        HttpClient client = new HttpClient();
        HostConfiguration hc = new HostConfiguration();
        //String host=location.getAddress().getHostAddress();
        // inefficient - but stops httpclient from rejecting half our cookies...
        String host = uri.getHost();
        hc.setHost(host, uri.getPort());
        client.executeMethod(hc, hm, state);
    } catch (IOException e) // TODO
    {
        _log.warn("problem proxying connection:", e);
    }

    InputStream fromServer = null;

    // handler status codes etc.
    int code = 502;
    //      String message="Bad Gateway: could not read server response code or message";

    code = hm.getStatusCode(); // IOException
    //      message=hm.getStatusText(); // IOException
    hres.setStatus(code);
    //      hres.setStatus(code, message); - deprecated...

    try {
        fromServer = hm.getResponseBodyAsStream(); // IOException
    } catch (IOException e) {
        _log.warn("problem acquiring http client output", e);
    }

    // clear response defaults.
    hres.setHeader("Date", null);
    hres.setHeader("Server", null);

    // set response headers
    // TODO - is it a bug in Jetty that I have to start my loop at 1 ? or that key[0]==null ?
    // Try this inside Tomcat...
    Header[] headers = hm.getResponseHeaders();
    for (int i = 0; i < headers.length; i++) {
        String h = headers[i].toExternalForm();
        int index = h.indexOf(':');
        String key = h.substring(0, index).trim().toLowerCase();
        String val = h.substring(index + 1, h.length()).trim();
        if (val != null && !_DontProxyHeaders.contains(key)) {
            hres.addHeader(key, val);
            // if (_log.isInfoEnabled()) _log.info("Response: "+key+" - "+val);
        }
    }

    hres.addHeader("Via", "1.1 (WADI)");

    // copy server->client
    int server2ClientTotal = 0;
    if (fromServer != null) {
        try {
            OutputStream toClient = hres.getOutputStream();// IOException
            server2ClientTotal += copy(fromServer, toClient, 8192);// IOException
        } catch (IOException e) {
            _log.warn("problem proxying server response back to client", e);
        } finally {
            try {
                fromServer.close();
            } catch (IOException e) {
                // well - we did our best...
                _log.warn("problem closing server response stream", e);
            }
        }
    }

    long endTime = System.currentTimeMillis();
    long elapsed = endTime - startTime;
    if (_log.isDebugEnabled()) {
        _log.debug("in:" + client2ServerTotal + ", out:" + server2ClientTotal + ", status:" + code + ", time:"
                + elapsed + ", uri:" + uri);
    }
}

From source file:org.wings.recorder.Recorder.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    try {//from   w w w  .  j av  a2  s  .c  om
        if (servletRequest instanceof HttpServletRequest) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
            Map map = servletRequest.getParameterMap();
            if (map.containsKey(RECORDER_SCRIPT)) {
                log.info("recorder_script " + map.get(RECORDER_SCRIPT));
                String[] values = (String[]) map.get(RECORDER_SCRIPT);
                scriptName = values[0];
            }
            if (map.containsKey(RECORDER_START)) {
                if (list != null)
                    return;
                log.info(RECORDER_START);
                list = new LinkedList();
            } else if (map.containsKey(RECORDER_STOP)) {
                if (list == null)
                    return;
                log.info(RECORDER_STOP);
                writeCode();
                list = null;
            } else if (list != null) {
                String resource = httpServletRequest.getPathInfo();
                log.debug("PATH_INFO: " + resource);

                Request record;
                if ("GET".equalsIgnoreCase(httpServletRequest.getMethod()))
                    record = new GET(resource);
                else
                    record = new POST(resource);

                Enumeration parameterNames = httpServletRequest.getParameterNames();
                while (parameterNames.hasMoreElements()) {
                    String name = (String) parameterNames.nextElement();
                    String[] values = httpServletRequest.getParameterValues(name);
                    addEvent(record, name, values);
                }
                Enumeration headerNames = httpServletRequest.getHeaderNames();
                while (headerNames.hasMoreElements()) {
                    String name = (String) headerNames.nextElement();
                    if (name.equalsIgnoreCase("cookie") || name.equalsIgnoreCase("referer"))
                        continue;
                    addHeader(record, name, httpServletRequest.getHeader(name));
                }
                list.add(record);
            }
        }
    } finally {
        if (servletResponse instanceof HttpServletResponse) {
            filterChain.doFilter(servletRequest,
                    new HttpServletResponseWrapper((HttpServletResponse) servletResponse) {
                        public ServletOutputStream getOutputStream() throws IOException {
                            final ServletOutputStream out = super.getOutputStream();
                            return new ServletOutputStream() {
                                public void write(int b) throws IOException {
                                    out.write(b);
                                }

                                public void close() throws IOException {
                                    super.println("<hr/><div align=\"center\">");
                                    super.println("<form method=\"get\" action=\"\">");
                                    super.println("<input type=\"text\" name=\"recorder_script\" value=\""
                                            + scriptName + "\">");
                                    super.println(
                                            "<input type=\"submit\" name=\"recorder_start\" value=\"start\">");
                                    super.println(
                                            "<input type=\"submit\" name=\"recorder_stop\" value=\"stop\">");
                                    super.println("</div></form>");
                                    super.close();
                                }
                            };
                        }
                    });
        } else
            filterChain.doFilter(servletRequest, servletResponse);
    }
}

From source file:com.mx.nibble.middleware.web.util.FileParse.java

public String execute(ActionInvocation invocation) throws Exception {

    Iterator iterator = parameters.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry mapEntry = (Map.Entry) iterator.next();
        System.out.println("The key is: " + mapEntry.getKey() + ",value is :" + mapEntry.getValue());
    }//w ww. j  ava  2s. c  om

    ActionContext ac = invocation.getInvocationContext();

    HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);

    HttpServletResponse response = (HttpServletResponse) ac.get(ServletActionContext.HTTP_RESPONSE);
    /**
    * This pages gives a sample of java upload management. It needs the commons FileUpload library, which can be found on apache.org.
    *
    * Note:
    * - putting error=true as a parameter on the URL will generate an error. Allows test of upload error management in the applet. 
    * 
    * 
    * 
    * 
    * 
    * 
    */

    // Directory to store all the uploaded files
    String ourTempDirectory = "/opt/erp/import/obras/";

    byte[] cr = { 13 };
    byte[] lf = { 10 };
    String CR = new String(cr);
    String LF = new String(lf);
    String CRLF = CR + LF;
    System.out.println("Before a LF=chr(10)" + LF + "Before a CR=chr(13)" + CR + "Before a CRLF" + CRLF);

    //Initialization for chunk management.
    boolean bLastChunk = false;
    int numChunk = 0;

    //CAN BE OVERRIDEN BY THE postURL PARAMETER: if error=true is passed as a parameter on the URL
    boolean generateError = false;
    boolean generateWarning = false;
    boolean sendRequest = false;

    response.setContentType("text/plain");

    java.util.Enumeration<String> headers = request.getHeaderNames();
    System.out.println("[parseRequest.jsp]  ------------------------------ ");
    System.out.println("[parseRequest.jsp]  Headers of the received request:");
    while (headers.hasMoreElements()) {
        String header = headers.nextElement();
        System.out.println("[parseRequest.jsp]  " + header + ": " + request.getHeader(header));
    }
    System.out.println("[parseRequest.jsp]  ------------------------------ ");

    try {
        // Get URL Parameters.
        Enumeration paraNames = request.getParameterNames();
        System.out.println("[parseRequest.jsp]  ------------------------------ ");
        System.out.println("[parseRequest.jsp]  Parameters: ");
        String pname;
        String pvalue;
        while (paraNames.hasMoreElements()) {
            pname = (String) paraNames.nextElement();
            pvalue = request.getParameter(pname);
            System.out.println("[parseRequest.jsp] " + pname + " = " + pvalue);
            if (pname.equals("jufinal")) {
                bLastChunk = pvalue.equals("1");
            } else if (pname.equals("jupart")) {
                numChunk = Integer.parseInt(pvalue);
            }

            //For debug convenience, putting error=true as a URL parameter, will generate an error
            //in this response.
            if (pname.equals("error") && pvalue.equals("true")) {
                generateError = true;
            }

            //For debug convenience, putting warning=true as a URL parameter, will generate a warning
            //in this response.
            if (pname.equals("warning") && pvalue.equals("true")) {
                generateWarning = true;
            }

            //For debug convenience, putting readRequest=true as a URL parameter, will send back the request content
            //into the response of this page.
            if (pname.equals("sendRequest") && pvalue.equals("true")) {
                sendRequest = true;
            }

        }
        System.out.println("[parseRequest.jsp]  ------------------------------ ");

        int ourMaxMemorySize = 10000000;
        int ourMaxRequestSize = 2000000000;

        ///////////////////////////////////////////////////////////////////////////////////////////////////////
        //The code below is directly taken from the jakarta fileupload common classes
        //All informations, and download, available here : http://jakarta.apache.org/commons/fileupload/
        ///////////////////////////////////////////////////////////////////////////////////////////////////////

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Set factory constraints
        factory.setSizeThreshold(ourMaxMemorySize);
        factory.setRepository(new File(ourTempDirectory));

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        upload.setSizeMax(ourMaxRequestSize);

        // Parse the request
        if (sendRequest) {
            //For debug only. Should be removed for production systems. 
            System.out.println(
                    "[parseRequest.jsp] ===========================================================================");
            System.out.println("[parseRequest.jsp] Sending the received request content: ");
            InputStream is = request.getInputStream();
            int c;
            while ((c = is.read()) >= 0) {
                out.write(c);
            } //while
            is.close();
            System.out.println(
                    "[parseRequest.jsp] ===========================================================================");
        } else if (!request.getContentType().startsWith("multipart/form-data")) {
            System.out.println("[parseRequest.jsp] No parsing of uploaded file: content type is "
                    + request.getContentType());
        } else {
            List /* FileItem */ items = upload.parseRequest(request);
            // Process the uploaded items
            Iterator iter = items.iterator();
            FileItem fileItem;
            File fout;
            System.out.println("[parseRequest.jsp]  Let's read the sent data   (" + items.size() + " items)");
            while (iter.hasNext()) {
                fileItem = (FileItem) iter.next();

                if (fileItem.isFormField()) {
                    System.out.println("[parseRequest.jsp] (form field) " + fileItem.getFieldName() + " = "
                            + fileItem.getString());

                    //If we receive the md5sum parameter, we've read finished to read the current file. It's not
                    //a very good (end of file) signal. Will be better in the future ... probably !
                    //Let's put a separator, to make output easier to read.
                    if (fileItem.getFieldName().equals("md5sum[]")) {
                        System.out.println("[parseRequest.jsp]  ------------------------------ ");
                    }
                } else {
                    //Ok, we've got a file. Let's process it.
                    //Again, for all informations of what is exactly a FileItem, please
                    //have a look to http://jakarta.apache.org/commons/fileupload/
                    //
                    System.out.println("[parseRequest.jsp] FieldName: " + fileItem.getFieldName());
                    System.out.println("[parseRequest.jsp] File Name: " + fileItem.getName());
                    System.out.println("[parseRequest.jsp] ContentType: " + fileItem.getContentType());
                    System.out.println("[parseRequest.jsp] Size (Bytes): " + fileItem.getSize());
                    //If we are in chunk mode, we add ".partN" at the end of the file, where N is the chunk number.
                    String uploadedFilename = fileItem.getName() + (numChunk > 0 ? ".part" + numChunk : "");
                    fout = new File(ourTempDirectory + (new File(uploadedFilename)).getName());
                    System.out.println("[parseRequest.jsp] File Out: " + fout.toString());
                    // write the file
                    fileItem.write(fout);

                    //////////////////////////////////////////////////////////////////////////////////////
                    //Chunk management: if it was the last chunk, let's recover the complete file
                    //by concatenating all chunk parts.
                    //
                    if (bLastChunk) {
                        System.out.println(
                                "[parseRequest.jsp]  Last chunk received: let's rebuild the complete file ("
                                        + fileItem.getName() + ")");
                        //First: construct the final filename.
                        FileInputStream fis;
                        FileOutputStream fos = new FileOutputStream(ourTempDirectory + fileItem.getName());
                        int nbBytes;
                        byte[] byteBuff = new byte[1024];
                        String filename;
                        for (int i = 1; i <= numChunk; i += 1) {
                            filename = fileItem.getName() + ".part" + i;
                            System.out.println("[parseRequest.jsp] " + "  Concatenating " + filename);
                            fis = new FileInputStream(ourTempDirectory + filename);
                            while ((nbBytes = fis.read(byteBuff)) >= 0) {
                                //System.out.println("[parseRequest.jsp] " + "     Nb bytes read: " + nbBytes);
                                fos.write(byteBuff, 0, nbBytes);
                            }
                            fis.close();
                        }
                        fos.close();
                    }

                    // End of chunk management
                    //////////////////////////////////////////////////////////////////////////////////////

                    fileItem.delete();
                }
            } //while
        }

        if (generateWarning) {
            System.out.println("WARNING: just a warning message.\\nOn two lines!");
        }

        System.out.println("[parseRequest.jsp] " + "Let's write a status, to finish the server response :");

        //Let's wait a little, to simulate the server time to manage the file.
        Thread.sleep(500);

        //Do you want to test a successful upload, or the way the applet reacts to an error ?
        if (generateError) {
            System.out.println(
                    "ERROR: this is a test error (forced in /wwwroot/pages/parseRequest.jsp).\\nHere is a second line!");
        } else {
            System.out.println("SUCCESS");
            PrintWriter out = ServletActionContext.getResponse().getWriter();
            out.write("SUCCESS");
            //System.out.println("                        <span class=\"cpg_user_message\">Il y eu une erreur lors de l'excution de la requte</span>");
        }

        System.out.println("[parseRequest.jsp] " + "End of server treatment ");

    } catch (Exception e) {
        System.out.println("");
        System.out.println("ERROR: Exception e = " + e.toString());
        System.out.println("");
    }

    return SUCCESS;

}

From source file:net.java.jaspicoil.MSPacSpnegoServerAuthModule.java

/**
 * Log the request for debug purpose// ww  w .j  a v  a  2s  . c  o  m
 * 
 * @param request
 *            the HTTP Servlet Request
 */
private void debugRequest(HttpServletRequest request) {

    if (this.debug || LOG.isLoggable(Level.FINE)) {
        final StringBuffer sb = new StringBuffer();
        sb.append("\n");
        try {
            sb.append("Request: ").append(request.getRequestURL()).append("\n");
            sb.append("UserPrincipal: ").append(request.getUserPrincipal()).append("\n");
            sb.append("AuthType: ").append(request.getAuthType()).append("\n");
            sb.append("Headers:\n");
            @SuppressWarnings("rawtypes")
            final Enumeration names = request.getHeaderNames();
            while (names.hasMoreElements()) {
                final String name = (String) names.nextElement();
                sb.append("\t").append(name).append("\t").append(request.getHeader(name)).append("\n");
            }
            LOG.log(this.debugLevel, "HTTP Request is : {0}", sb);

        } catch (final Throwable t) {
            LOG.log(Level.WARNING, "An unexpected problem has occured during log : {0}", t);
        }
    }
}

From source file:at.gv.egovernment.moa.id.proxy.servlet.ProxyServlet.java

/**
 * Tunnels a request to the online application using given URL mapping and SSLSocketFactory.
 * This method returns the ResponseCode of the request to the online application. 
 * @param req HTTP request// www .  ja va2  s . c  o  m
 * @param resp HTTP response
 * @param loginHeaders header field/values to be inserted for purposes of authentication; 
 *         may be <code>null</code>
 * @param loginParameters parameter name/values to be inserted for purposes of authentication; 
 *         may be <code>null</code>
 * @param publicURLPrefix prefix of request URL to be substituted for the <code>realURLPrefix</code>
 * @param realURLPrefix prefix of online application URL to substitute the <code>publicURLPrefix</code>
 * @param ssf SSLSocketFactory to use
 * @throws IOException if an I/O error occurs
 */
private int tunnelRequest(HttpServletRequest req, HttpServletResponse resp, Map loginHeaders,
        Map loginParameters, String publicURLPrefix, String realURLPrefix, SSLSocketFactory ssf, String binding)
        throws IOException {

    String originBinding = binding;
    String browserUserID = "";
    String browserPassword = "";
    //URL url = new URL(realURLPrefix); 
    //String realURLHost = url.getHost(); 
    if (INTERNAL_DEBUG && !binding.equals(""))
        Logger.debug("Binding: " + binding);

    // collect headers from request
    Map headers = new HashMap();
    for (Enumeration enu = req.getHeaderNames(); enu.hasMoreElements();) {
        String headerKey = (String) enu.nextElement();
        String headerKeyValue = req.getHeader(headerKey);
        if (INTERNAL_DEBUG)
            Logger.debug("Incoming:" + headerKey + "=" + headerKeyValue);
        //Analyze Basic-Auth-Headers from the client
        if (headerKey.equalsIgnoreCase("Authorization")) {
            if (headerKeyValue.substring(0, 6).equalsIgnoreCase("Basic ")) {
                String credentials = headerKeyValue.substring(6);
                byte[] bplaintextcredentials = Base64Utils.decode(credentials, true);
                String plaintextcredentials = new String(bplaintextcredentials);
                browserUserID = plaintextcredentials.substring(0, plaintextcredentials.indexOf(":"));
                browserPassword = plaintextcredentials.substring(plaintextcredentials.indexOf(":") + 1);
                //deactivate following line for security
                //if (INTERNAL_DEBUG) Logger.debug("Analyzing authorization-header from browser: " + headerKeyValue + "gives UN:PW=" + browserUserID + ":" + browserPassword );
            }
            if (headerKeyValue.substring(0, 9).equalsIgnoreCase("Negotiate")) {
                //deactivate following line for security
                //if (INTERNAL_DEBUG) Logger.debug("Analyzing authorization-header from browser: Found NTLM Aut.: " + headerKeyValue + "gives UN:PW=" + browserUserID + ":" + browserPassword );
            }
        } else {
            /* Headers MUST NOT be repaced according to our Spec.
            if (headerKey.equalsIgnoreCase("Host")) {
               headerKeyValue = realURLHost; 
                 //headerKeyValue= realURLPrefix.substring(hoststartpos);
              if (INTERNAL_DEBUG) Logger.debug("replaced:" + headerKey + "=" + headerKeyValue);           
            }
            */
            headers.put(headerKey, headerKeyValue);
        }
    }

    // collect login headers, possibly overwriting headers from request
    String authorizationvalue = "";
    if (req.getSession().getAttribute(ATT_OA_AUTHORIZATION_HEADER) == null) {

        if (OAConfiguration.BINDUNG_NOMATCH.equals(binding)) {
            int loginTry = getLoginTry(req);
            Logger.debug("Binding: mode = " + OAConfiguration.BINDUNG_NOMATCH + "(try #"
                    + Integer.toString(loginTry) + ")");
            if (loginTry == 1) {
                binding = OAConfiguration.BINDUNG_FULL;
            } else {
                binding = OAConfiguration.BINDUNG_USERNAME;
            }
        }

        /* Soll auch bei anderen bindings zuerst ein passwort probiert werden knnen:
        //if we have the first Login-Try and we have Binding to Username and a predefined Password we try this one first
         // full binding will be covered by next block
         if (loginTry==1 && !OAConfiguration.BINDUNG_FULL.equals(binding)) {
           //1st try: if we have a password, try this one first
            for (Iterator iter = loginHeaders.keySet().iterator(); iter.hasNext();) {
              String headerKey = (String) iter.next();
              String headerKeyValue = (String) loginHeaders.get(headerKey);
              if (isBasicAuthenticationHeader(headerKey, headerKeyValue)) {
               String credentials = headerKeyValue.substring(6);
               byte [] bplaintextcredentials = Base64Utils.decode(credentials, true);
              String plaintextcredentials = new String(bplaintextcredentials);
              String password = plaintextcredentials.substring(plaintextcredentials.indexOf(":")+1);
              if (password!=null && !password.equals("")) {
                  Logger.debug("Binding: found predefined password. Trying full binding first");
                 binding = OAConfiguration.BINDUNG_FULL;
                 break;
                }
              }
            }
         }
         */

        //we have a connection with not having logged on
        if (loginHeaders != null && (browserPassword.length() != 0 || browserUserID.length() != 0
                || OAConfiguration.BINDUNG_FULL.equals(binding))) {
            for (Iterator iter = loginHeaders.keySet().iterator(); iter.hasNext();) {
                String headerKey = (String) iter.next();
                String headerKeyValue = (String) loginHeaders.get(headerKey);
                //customize loginheaders if necessary
                if (isBasicAuthenticationHeader(headerKey, headerKeyValue)) {
                    if (OAConfiguration.BINDUNG_FULL.equals(binding)) {
                        authorizationvalue = headerKeyValue;
                        Logger.debug("Binding: full binding to user established");
                    } else {
                        String credentials = headerKeyValue.substring(6);
                        byte[] bplaintextcredentials = Base64Utils.decode(credentials, true);
                        String plaintextcredentials = new String(bplaintextcredentials);
                        String userID = plaintextcredentials.substring(0, plaintextcredentials.indexOf(":"));
                        String password = plaintextcredentials.substring(plaintextcredentials.indexOf(":") + 1);
                        String userIDPassword = ":";
                        if (OAConfiguration.BINDUNG_USERNAME.equals(binding)) {
                            Logger.debug("Binding: Access with necessary binding to user");
                            userIDPassword = userID + ":" + browserPassword;
                        } else if (OAConfiguration.BINDUNG_NONE.equals(binding)) {
                            Logger.debug("Binding: Access without binding to user");
                            //If first time
                            if (browserUserID.length() == 0)
                                browserUserID = userID;
                            if (browserPassword.length() == 0)
                                browserPassword = password;
                            userIDPassword = browserUserID + ":" + browserPassword;
                        } else {
                            userIDPassword = userID + ":" + password;
                        }
                        credentials = Base64Utils.encode(userIDPassword.getBytes());
                        authorizationvalue = "Basic " + credentials;
                        headerKeyValue = authorizationvalue;
                    }
                }
                headers.put(headerKey, headerKeyValue);
            }
        }
    } else {
        //if OA needs Authorization header in each further request
        authorizationvalue = (String) req.getSession().getAttribute(ATT_OA_AUTHORIZATION_HEADER);
        if (loginHeaders != null)
            headers.put("Authorization", authorizationvalue);
    }

    Vector parameters = new Vector();
    for (Enumeration enu = req.getParameterNames(); enu.hasMoreElements();) {
        String paramName = (String) enu.nextElement();
        if (!(paramName.equals(PARAM_SAMLARTIFACT) || paramName.equals(PARAM_TARGET))) {
            if (INTERNAL_DEBUG)
                Logger.debug("Req Parameter-put: " + paramName + ":" + req.getParameter(paramName));
            String parameter[] = new String[2];
            parameter[0] = paramName;
            parameter[1] = req.getParameter(paramName);
            parameters.add(parameter);
        }
    }
    // collect login parameters, possibly overwriting parameters from request
    if (loginParameters != null) {
        for (Iterator iter = loginParameters.keySet().iterator(); iter.hasNext();) {
            String paramName = (String) iter.next();
            if (!(paramName.equals(PARAM_SAMLARTIFACT) || paramName.equals(PARAM_TARGET))) {
                if (INTERNAL_DEBUG)
                    Logger.debug(
                            "Req Login-Parameter-put: " + paramName + ":" + loginParameters.get(paramName));
                String parameter[] = new String[2];
                parameter[0] = paramName;
                parameter[1] = (String) loginParameters.get(paramName);
                parameters.add(parameter);
            }
        }
    }

    ConnectionBuilder cb = ConnectionBuilderFactory.getConnectionBuilder(publicURLPrefix);
    HttpURLConnection conn = cb.buildConnection(req, publicURLPrefix, realURLPrefix, ssf, parameters);

    // set headers as request properties of URLConnection
    for (Iterator iter = headers.keySet().iterator(); iter.hasNext();) {
        String headerKey = (String) iter.next();
        String headerValue = (String) headers.get(headerKey);
        String LogStr = "Req header " + headerKey + ": " + headers.get(headerKey);
        if (isBasicAuthenticationHeader(headerKey, headerValue)) {
            String credentials = headerValue.substring(6);
            byte[] bplaintextcredentials = Base64Utils.decode(credentials, true);
            String plaintextcredentials = new String(bplaintextcredentials);
            String uid = plaintextcredentials.substring(0, plaintextcredentials.indexOf(":"));
            String pwd = plaintextcredentials.substring(plaintextcredentials.indexOf(":") + 1);
            //Sollte AuthorizationInfo vom HTTPClient benutzt werden:  cb.addBasicAuthorization(publicURLPrefix, uid, pwd);
            //deactivate following line for security
            //if (INTERNAL_DEBUG && Logger.isDebugEnabled()) LogStr = LogStr + "  >UserID:Password< >" + uid + ":" + pwd + "<";
        }
        conn.setRequestProperty(headerKey, headerValue);
        if (INTERNAL_DEBUG)
            Logger.debug(LogStr);
    }

    StringWriter sb = new StringWriter();

    // Write out parameters into output stream of URLConnection.
    // On GET request, do not send parameters in any case,
    // otherwise HttpURLConnection would send a POST.
    if (!"get".equalsIgnoreCase(req.getMethod()) && !parameters.isEmpty()) {
        boolean firstParam = true;
        String parameter[] = new String[2];
        for (Iterator iter = parameters.iterator(); iter.hasNext();) {
            parameter = (String[]) iter.next();
            String paramName = parameter[0];
            String paramValue = parameter[1];
            if (firstParam)
                firstParam = false;
            else
                sb.write("&");
            sb.write(paramName);
            sb.write("=");
            sb.write(paramValue);
            if (INTERNAL_DEBUG)
                Logger.debug("Req param " + paramName + ": " + paramValue);
        }
    }

    // For WebDAV and POST: copy content
    if (!"get".equalsIgnoreCase(req.getMethod())) {
        if (INTERNAL_DEBUG && !"post".equalsIgnoreCase(req.getMethod()))
            Logger.debug("---- WEBDAV ----  copying content");
        try {
            OutputStream out = conn.getOutputStream();
            InputStream in = req.getInputStream();
            if (!parameters.isEmpty())
                out.write(sb.toString().getBytes()); //Parameter nicht mehr mittels Printwriter schreiben 
            copyStream(in, out, null, req.getMethod());
            out.flush();
            out.close();
        } catch (IOException e) {
            if (!"post".equalsIgnoreCase(req.getMethod()))
                Logger.debug("---- WEBDAV ----  streamcopy problem");
            else
                Logger.debug("---- POST ----  streamcopy problem");
        }
    }

    // connect
    if (INTERNAL_DEBUG)
        Logger.debug("Connect Request");
    conn.connect();
    if (INTERNAL_DEBUG)
        Logger.debug("Connect Response");

    // check login tries
    if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
        int loginTry = getLoginTry(req);
        req.getSession().setAttribute(ATT_OA_LOGINTRY, Integer.toString(loginTry));
        if (loginTry > MAX_OA_LOGINTRY) {
            Logger.debug("Found 401 UNAUTHORIZED, maximum tries exceeded; leaving...");
            cb.disconnect(conn);
            return -401;
        }
    }

    if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED
            && OAConfiguration.BINDUNG_FULL.equals(originBinding)) {
        Logger.debug("Found 401 UNAUTHORIZED, leaving...");
        cb.disconnect(conn);
        return conn.getResponseCode();
    }

    resp.setStatus(conn.getResponseCode());
    //Issue by Gregor Karlinger - content type was annotated twice
    //resp.setContentType(conn.getContentType());

    if (loginHeaders != null
            && (conn.getResponseCode() == HttpURLConnection.HTTP_OK
                    || conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP)
            && req.getSession().getAttribute(ATT_OA_AUTHORIZATION_HEADER) == null) {
        req.getSession().setAttribute(ATT_OA_AUTHORIZATION_HEADER, authorizationvalue);
        Logger.debug("Login OK. Saving authorization header to remember in further requests");
    }

    // Read response headers
    // Omit response header "content-length" if response header "Transfer-encoding: chunked" is set.
    // Otherwise, the connection will not be kept alive, resulting in subsequent missing requests.
    // See JavaDoc of javax.servlet.http.HttpServlet:
    // When using HTTP 1.1 chunked encoding (which means that the response has a Transfer-Encoding header), do not set the Content-Length header.
    Vector respHeaders = new Vector();

    boolean chunked = false;
    String contentLengthKey = null;
    String transferEncodingKey = null;
    int i = 1;
    String headerKey;
    String loginType = (String) req.getSession().getAttribute(ATT_OA_LOGINTYPE);
    while ((headerKey = conn.getHeaderFieldKey(i)) != null) {
        String headerValue = conn.getHeaderField(i);

        if (headerKey.equalsIgnoreCase("WWW-Authenticate")) {
            int start = headerValue.indexOf("Basic realm=\"");
            boolean requestsBasicAuth = headerValue.substring(start).startsWith("Basic realm=\"");
            if (requestsBasicAuth) {
                headerValue = "Basic realm=\"" + publicURLPrefix + "\"";

                if (OAConfiguration.BINDUNG_USERNAME.equals(originBinding)
                        || OAConfiguration.BINDUNG_NOMATCH.equals(originBinding))
                    headerValue = "Basic realm=\"Bitte Passwort eingeben\"";
                else if ("none".equals(originBinding)) {
                    headerValue = "Basic realm=\"Bitte Benutzername und Passwort eingeben\"";
                }
            }
        }

        //    // berschrift im Browser-Passworteingabedialog setzen (sonst ist der reale host eingetragen)
        //    if (headerKey.equalsIgnoreCase("WWW-Authenticate") && headerValue.startsWith("Basic realm=\"")) {
        //      headerValue = "Basic realm=\"" + publicURLPrefix + "\"";
        //      if (OAConfiguration.BINDUNG_USERNAME.equals(originBinding) || OAConfiguration.BINDUNG_NOMATCH.equals(originBinding)) {
        //         headerValue = "Basic realm=\"Bitte Passwort eingeben\"";
        //      } else if (OAConfiguration.BINDUNG_NONE.equals(originBinding)) {
        //         headerValue = "Basic realm=\"Bitte Benutzername und Passwort eingeben\"";
        //      }
        //    }

        String respHeader[] = new String[2];
        if ((conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)
                && headerKey.equalsIgnoreCase("content-length")) {
            //alter the unauthorized message with template for login 
            //TODO: supply a special login form on unauthorized messages with bindings!=full
            headerValue = Integer.toString(RET_401_MSG.length());
        }
        respHeader[0] = headerKey;
        respHeader[1] = headerValue;

        if (!(OAConfiguration.BINDUNG_FULL.equals(originBinding)
                && OAConfiguration.LOGINTYPE_STATELESS.equals(loginType)
                && headerKey.equalsIgnoreCase("WWW-Authenticate")
                && headerValue.startsWith("Basic realm=\""))) {
            respHeaders.add(respHeader);
            if (INTERNAL_DEBUG)
                Logger.debug("Resp header " + headerKey + ": " + headerValue);
        } else {
            Logger.debug("Resp header ---REMOVED--- " + headerKey + ": " + headerValue);
        }
        if (isTransferEncodingChunkedHeader(headerKey, headerValue)
                || "content-length".equalsIgnoreCase(headerKey)) {
            respHeaders.remove(respHeader);
            Logger.debug("Resp header " + headerKey + " REMOVED");
        }

        i++;
    }

    String headerValue;
    String respHeader[] = new String[2];

    //write out all Responseheaders 
    for (Iterator iter = respHeaders.iterator(); iter.hasNext();) {
        respHeader = (String[]) iter.next();
        headerKey = respHeader[0];
        headerValue = respHeader[1];
        resp.addHeader(headerKey, headerValue);
    }

    //Logger.debug(">>>> Copy Content");
    //Logger.debug("  from ()" + conn.getURL());
    //Logger.debug("  to (" + req.getRemoteAddr() + ":"+ ") " +req.getRequestURL());

    // read response stream
    Logger.debug("Resp from " + conn.getURL().toString() + ": status " + conn.getResponseCode());
    // Load content unless the server lets us know that the content is NOT MODIFIED...
    if (conn.getResponseCode() != HttpURLConnection.HTTP_NOT_MODIFIED) {
        BufferedInputStream respIn = new BufferedInputStream(conn.getInputStream());
        //Logger.debug("Got Inputstream");
        BufferedOutputStream respOut = new BufferedOutputStream(resp.getOutputStream());
        //Logger.debug("Got Outputstream");

        byte[] buffer = new byte[4096];
        if (respOut != null) {
            int bytesRead;
            while ((bytesRead = respIn.read(buffer)) >= 0) {
                if (conn.getResponseCode() != HttpURLConnection.HTTP_UNAUTHORIZED)
                    respOut.write(buffer, 0, bytesRead);
            }
        } else {
            while (respIn.read(buffer) >= 0)
                ;
        }

        /*
        int ch;
        StringBuffer strBuf = new StringBuffer("");
        while ((ch = respIn.read()) >= 0) {
          if (conn.getResponseCode()!=HttpURLConnection.HTTP_UNAUTHORIZED) respOut.write(ch);
          strBuf.append((char)ch);
        }
        Logger.debug("Resp Content:");
        if (strBuf.toString().length()>500)
          Logger.debug(strBuf.toString().substring(0,500));
        else
          Logger.debug(strBuf.toString());
        */

        if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            respOut.write(RET_401_MSG.getBytes());
        }
        respOut.flush();
        respOut.close();
        respIn.close();
        if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            Logger.debug("Found 401 UNAUTHORIZED...");
            cb.disconnect(conn);
            return conn.getResponseCode();
        }
    } else {
        //if (conn.getResponseCode()==HttpURLConnection.HTTP_NOT_MODIFIED) 
        Logger.debug("Found 304 NOT MODIFIED...");
    }

    cb.disconnect(conn);
    Logger.debug("Request done");

    return conn.getResponseCode();
}

From source file:com.jpeterson.littles3.StorageEngine.java

/**
 * Process HTTP HEAD and GET//from   ww  w  .  j  a  v a  2  s . c om
 * 
 * @param req
 *            an HttpServletRequest object that contains the request the
 *            client has made of the servlet
 * @param resp
 *            an HttpServletResponse object that contains the response the
 *            servlet sends to the client
 * @throws IOException
 *             if an input or output error is detected when the servlet
 *             handles the GET request
 * @throws ServletException
 *             if the request for the GET could not be handled
 */
@SuppressWarnings("unchecked")
public void processHeadGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    if (logger.isDebugEnabled()) {
        logger.debug("Context path: " + req.getContextPath());
        logger.debug("Path info: " + req.getPathInfo());
        logger.debug("Path translated: " + req.getPathTranslated());
        logger.debug("Query string: " + req.getQueryString());
        logger.debug("Request URI: " + req.getRequestURI());
        logger.debug("Request URL: " + req.getRequestURL());
        logger.debug("Servlet path: " + req.getServletPath());
        logger.debug("Servlet name: " + this.getServletName());

        for (Enumeration headerNames = req.getHeaderNames(); headerNames.hasMoreElements();) {
            String headerName = (String) headerNames.nextElement();
            String headerValue = req.getHeader(headerName);
            logger.debug("Header- " + headerName + ": " + headerValue);
        }
    }

    try {
        S3ObjectRequest or;

        try {
            or = S3ObjectRequest.create(req, resolvedHost(),
                    (Authenticator) getWebApplicationContext().getBean(BEAN_AUTHENTICATOR));
        } catch (InvalidAccessKeyIdException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidAccessKeyId");
            return;
        } catch (InvalidSecurityException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity");
            return;
        } catch (RequestTimeTooSkewedException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "RequestTimeTooSkewed");
            return;
        } catch (SignatureDoesNotMatchException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "SignatureDoesNotMatch");
            return;
        } catch (AuthenticatorException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity");
            return;
        }

        if (or.getKey() != null) {
            S3Object s3Object;
            StorageService storageService;

            try {
                storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE);
                s3Object = storageService.load(or.getBucket(), or.getKey());

                if (s3Object == null) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchKey");
                    return;
                }
            } catch (DataAccessException e) {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchKey");
                return;
            }

            if (req.getParameter(PARAMETER_ACL) != null) {
                // retrieve access control policy
                String response;
                Acp acp = s3Object.getAcp();

                try {
                    acp.canRead(or.getRequestor());
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                }

                response = Acp.encode(acp);
                resp.setContentLength(response.length());
                resp.setContentType("application/xml");
                resp.setStatus(HttpServletResponse.SC_OK);

                Writer out = resp.getWriter();
                out.write(response);
                out.flush(); // commit response
                out.close();
                out = null;
            } else {
                // retrieve object
                InputStream in = null;
                OutputStream out = null;
                byte[] buffer = new byte[4096];
                int count;
                String value;

                try {
                    s3Object.canRead(or.getRequestor());
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                }

                // headers
                resp.setContentType(s3Object.getContentType());
                if ((value = s3Object.getContentDisposition()) != null) {
                    resp.setHeader("Content-Disposition", value);
                }
                // TODO: set the Content-Range, if request includes Range
                // TODO: add "x-amz-missing-meta", if any

                // add the "x-amz-meta-" headers
                for (Iterator<String> names = s3Object.getMetadataNames(); names.hasNext();) {
                    String name = names.next();
                    String headerName = HEADER_PREFIX_USER_META + name;
                    String prefix = "";
                    StringBuffer buf = new StringBuffer();
                    for (Iterator<String> values = s3Object.getMetadataValues(name); values.hasNext();) {
                        buf.append(values.next()).append(prefix);
                        prefix = ",";
                    }
                    resp.setHeader(headerName, buf.toString());
                }

                resp.setDateHeader("Last-Modified", s3Object.getLastModified());
                if ((value = s3Object.getETag()) != null) {
                    resp.setHeader("ETag", value);
                }
                if ((value = s3Object.getContentMD5()) != null) {
                    resp.setHeader("Content-MD5", value);
                }
                if ((value = s3Object.getContentDisposition()) != null) {
                    resp.setHeader("Content-Disposition", value);
                }
                resp.setHeader("Accept-Ranges", "bytes");

                String rangeRequest = req.getHeader("Range");

                if (rangeRequest != null) {
                    // request for a range
                    RangeSet rangeSet = RangeFactory.processRangeHeader(rangeRequest);

                    // set content length
                    rangeSet.resolve(s3Object.getContentLength());

                    if (rangeSet.size() > 1) {
                        // requires multi-part response
                        // TODO: implement
                        resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
                    }

                    Range[] ranges = (Range[]) rangeSet.toArray(new Range[0]);

                    resp.setHeader("Content-Range",
                            formatRangeHeaderValue(ranges[0], s3Object.getContentLength()));
                    resp.setHeader("Content-Length", Long.toString(rangeSet.getLength()));

                    in = new RangeInputStream(s3Object.getInputStream(), ranges[0]);
                    resp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                } else {
                    // request for entire content
                    // Used instead of resp.setContentLength((int)); because
                    // Amazon
                    // limit is 5 gig, which is bigger than an int
                    resp.setHeader("Content-Length", Long.toString(s3Object.getContentLength()));

                    in = s3Object.getInputStream();
                    resp.setStatus(HttpServletResponse.SC_OK);
                }

                // body
                out = resp.getOutputStream();

                while ((count = in.read(buffer, 0, buffer.length)) > 0) {
                    out.write(buffer, 0, count);
                }

                out.flush(); // commit response
                out.close();
                out = null;
            }
            return;
        } else if (or.getBucket() != null) {
            // operation on a bucket
            StorageService storageService;
            String prefix;
            String marker;
            int maxKeys = Integer.MAX_VALUE;
            String delimiter;
            String response;
            String value;

            storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE);

            if (req.getParameter(PARAMETER_ACL) != null) {
                // retrieve access control policy
                Acp acp;

                try {
                    acp = storageService.loadBucket(or.getBucket()).getAcp();
                } catch (DataAccessException e) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket");
                    return;
                }

                try {
                    acp.canRead(or.getRequestor());
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                }

                response = Acp.encode(acp);
                resp.setContentLength(response.length());
                resp.setContentType("application/xml");
                resp.setStatus(HttpServletResponse.SC_OK);

                Writer out = resp.getWriter();
                out.write(response);
                out.flush(); // commit response
                out.close();
                out = null;
            } else {
                Bucket bucket;

                prefix = req.getParameter("prefix");
                if (prefix == null) {
                    prefix = "";
                }
                marker = req.getParameter("marker");
                value = req.getParameter("max-keys");
                if (value != null) {
                    try {
                        maxKeys = Integer.parseInt(value);
                    } catch (NumberFormatException e) {
                        logger.info("max-keys must be numeric: " + value);
                    }
                }

                delimiter = req.getParameter("delimiter");

                try {
                    bucket = storageService.loadBucket(or.getBucket());
                } catch (DataAccessException e) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket");
                    return;
                }

                try {
                    bucket.canRead(or.getRequestor());
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                }

                response = storageService.listKeys(bucket, prefix, marker, delimiter, maxKeys);

                resp.setContentLength(response.length());
                resp.setContentType("application/xml");
                resp.setStatus(HttpServletResponse.SC_OK);

                Writer out = resp.getWriter();
                out.write(response);
                if (logger.isTraceEnabled()) {
                    logger.trace("Response: " + response);
                }
            }
            return;
        } else {
            // operation on the service
            StorageService storageService;
            List buckets;

            storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE);

            buckets = storageService.findBuckets("");

            StringBuffer buffer = new StringBuffer();

            buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            buffer.append("<ListAllMyBucketsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">");
            buffer.append("<Owner>");
            buffer.append("<ID/>"); // TODO: implement
            buffer.append("<DisplayName/>"); // TODO: implementF
            buffer.append("</Owner>");
            buffer.append("<Buckets>");
            for (Iterator iter = buckets.iterator(); iter.hasNext();) {
                Bucket bucket = (Bucket) iter.next();
                buffer.append("<Bucket>");
                buffer.append("<Name>").append(bucket.getName()).append("</Name>");
                buffer.append("<CreationDate>").append(iso8601.format(bucket.getCreated()))
                        .append("</CreationDate>");
                buffer.append("</Bucket>");
            }
            buffer.append("</Buckets>");
            buffer.append("</ListAllMyBucketsResult>");

            resp.setContentLength(buffer.length());
            resp.setContentType("application/xml");
            resp.setStatus(HttpServletResponse.SC_OK);

            Writer out = resp.getWriter();
            out.write(buffer.toString());
            return;
        }
    } catch (IllegalArgumentException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "InvalidURI");
        return;
    }
}

From source file:at.gv.egiz.bku.online.webapp.WebRequestHandler.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, java.io.IOException {

    BindingProcessorManager bindingProcessorManager = (BindingProcessorManager) getServletContext()
            .getAttribute("bindingProcessorManager");
    if (bindingProcessorManager == null) {
        String msg = "Configuration error: BindingProcessorManager missing!";
        log.error(msg);/*from  w  w w . j  a  v a 2s . c  o  m*/
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        return;
    }

    Configuration conf = ((BindingProcessorManagerImpl) bindingProcessorManager).getConfiguration();
    if (conf == null)
        log.error("No configuration");
    else
        MoccaParameterBean.setP3PHeader(conf, resp);

    Id id = (Id) req.getAttribute("id");
    if (id == null) {
        String msg = "No request id! Configuration error: ServletFilter missing?";
        log.error(msg);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        return;
    }

    // if binding processor with same id is present: remove
    bindingProcessorManager.removeBindingProcessor(id);

    Locale locale = AcceptLanguage.getLocale(req.getHeader("Accept-Language"));
    if (log.isInfoEnabled()) {
        log.info("Received request (Accept-Language locale: {}).", locale);
    }

    // create new binding processor
    String protocol = MoccaParameterBean.getInitParameter("protocol", getServletConfig(), getServletContext());
    if (protocol == null || protocol.isEmpty()) {
        protocol = req.getScheme();
    }
    HTTPBindingProcessor bindingProcessor = (HTTPBindingProcessor) bindingProcessorManager
            .createBindingProcessor(protocol, locale);

    // set headers
    LinkedHashMap<String, String> headerMap = new LinkedHashMap<String, String>();
    if (req.getHeaderNames() != null) {
        for (Enumeration<?> headerName = req.getHeaderNames(); headerName.hasMoreElements();) {
            String name = (String) headerName.nextElement();
            // Account for multiple headers with the same field-name, but
            // they are very rare, so we are not using a StringBuffer.
            Enumeration<?> headers = req.getHeaders(name);
            String value = null;
            while (headers.hasMoreElements()) {
                value = (value == null) ? (String) headers.nextElement() : value + ", " + headers.nextElement();
            }
            headerMap.put(name, value);
        }
    }

    // set request stream 
    InputStream inputStream;
    if (req.getMethod().equals("POST")) {
        inputStream = req.getInputStream();
    } else {
        headerMap.put(HttpUtil.HTTP_HEADER_CONTENT_TYPE, InputDecoderFactory.URL_ENCODED);
        String queryString = req.getQueryString();
        if (queryString != null) {
            inputStream = new ByteArrayInputStream(queryString.getBytes("UTF-8"));
        } else {
            inputStream = new ByteArrayInputStream(new byte[] {});
        }
    }

    bindingProcessor.setHTTPHeaders(headerMap);
    bindingProcessor.consumeRequestStream(req.getRequestURL().toString(), inputStream);
    inputStream.close();

    // process
    bindingProcessorManager.process(id, bindingProcessor);

    log.debug("Sending redirect to user interface.");
    resp.sendRedirect(resp.encodeRedirectURL(uiRedirectUrl));

}

From source file:org.sakaiproject.entitybroker.util.http.EntityHttpServletRequest.java

/**
 * Set all the values from a request on this request object and set this request
 * as the one which the values were copied from
 * @param req any request//from   ww w  . jav  a  2s  .c  om
 */
public void setRequestValues(HttpServletRequest req) {
    if (req == null) {
        throw new IllegalArgumentException("request cannot be null");
    }
    // get the collections of values out
    Enumeration<String> attribNames = req.getAttributeNames();
    while (attribNames.hasMoreElements()) {
        String name = (String) attribNames.nextElement();
        Object obj = req.getAttribute(name);
        if (obj != null) {
            attributes.put(name, obj);
        }
    }
    Cookie[] ck = req.getCookies();
    if (ck != null) {
        for (int i = 0; i < ck.length; i++) {
            cookies.add(ck[i]);
        }
    }
    Enumeration<String> headerNames = req.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        Enumeration<String> henum = req.getHeaders(name);
        Vector<String> v = new Vector<String>(1);
        while (henum.hasMoreElements()) {
            String h = henum.nextElement();
            v.add(h);
        }
    }
    for (Entry<String, String[]> entry : (Set<Entry<String, String[]>>) req.getParameterMap().entrySet()) {
        parameters.put(entry.getKey(), entry.getValue());
    }
    // get the basic values out
    this.locale = req.getLocale();
    this.method = req.getMethod();
    this.contentType = req.getContentType();
    this.characterEncoding = req.getCharacterEncoding() == null ? "UTF-8" : req.getCharacterEncoding();
    this.contentLength = req.getContentLength();

    this.contextPath = req.getContextPath();
    this.pathInfo = req.getPathInfo();
    this.queryString = req.getQueryString();
    this.requestURI = req.getRequestURI();
    this.servletPath = req.getServletPath();

    this.scheme = req.getScheme();
    this.protocol = req.getProtocol();
    this.serverName = req.getServerName();
    this.serverPort = req.getServerPort();
    this.remoteAddr = req.getRemoteAddr();
    this.remoteHost = req.getRemoteHost();

    this.realDispatcher = true;
}

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

private void logRequestInfo(HttpServletRequest req) {
    if (!ZimbraLog.dav.isDebugEnabled()) {
        return;/*from ww w  .  j  a  v  a 2 s .com*/
    }
    StringBuilder hdrs = new StringBuilder();
    hdrs.append("DAV REQUEST:\n");
    hdrs.append(req.getMethod()).append(" ").append(req.getRequestURL().toString()).append(" ")
            .append(req.getProtocol());
    Enumeration<String> paramNames = req.getParameterNames();
    if (paramNames != null && paramNames.hasMoreElements()) {
        hdrs.append("\nDAV REQUEST PARAMS:");
        while (paramNames.hasMoreElements()) {
            String paramName = paramNames.nextElement();
            if (paramName.contains("Auth")) {
                hdrs.append("\n").append(paramName).append("=*** REPLACED ***");
                continue;
            }
            String params[] = req.getParameterValues(paramName);
            if (params != null) {
                for (String param : params) {
                    hdrs.append("\n").append(paramName).append("=").append(param);
                }
            }
        }
    }
    /* Headers can include vital information which affects the request like "If-None-Match" headers,
     * so useful to be able to log them, skipping authentication related headers to avoid leaking passwords
     */
    Enumeration<String> namesEn = req.getHeaderNames();
    if (namesEn != null && namesEn.hasMoreElements()) {
        hdrs.append("\nDAV REQUEST HEADERS:");
        while (namesEn.hasMoreElements()) {
            String hdrName = namesEn.nextElement();
            if (hdrName.contains("Auth") || (hdrName.contains(HttpHeaders.COOKIE))) {
                hdrs.append("\n").append(hdrName).append(": *** REPLACED ***");
                continue;
            }
            Enumeration<String> vals = req.getHeaders(hdrName);
            while (vals.hasMoreElements()) {
                hdrs.append("\n").append(hdrName).append(": ").append(vals.nextElement());
            }
        }
    }
    ZimbraLog.dav.debug(hdrs.toString());
}