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.bibsonomy.logging.LogMe.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {

    // Antwort am Anfang senden, damit Browser nicht warten muss
    response.setContentType("text/html");
    PrintWriter pw = new PrintWriter(response.getOutputStream());

    /*/*from  ww w  .  ja  v  a2s  .  com*/
          pw.println("");
          pw.println("<head><title>Sven TEST</title></head>");
          pw.println("");
          pw.println("<body>");
          pw.println("");
          pw.println("Hallo!");
          pw.println("");
          pw.println("</body>");
          pw.println("</html>");
    */

    //      pw.println("");
    pw.close();

    int dompath_length = 0;

    try {
        dompath_length = req.getParameter("dompath").length();
    } catch (NullPointerException e) {
        // kein dompath angegeben 
    }

    log.debug("dompath_lenght = " + dompath_length);

    // if dompath is empty 
    if (dompath_length > 0) {

        //      String userAgent =  req.getHeader("user-agent");
        //      System.out.println("Hallo " + userAgent);

        // schreibe Cookies in Cookie-Array cookie
        Cookie[] cookies = req.getCookies();
        //      System.out.println (req.getParameter("dompath"));
        //      System.out.println (req.getHeader("remote_addr"));

        @SuppressWarnings("unchecked")
        Enumeration<String> headerNames = req.getHeaderNames();
        String cookieUsername = "";
        String cookieSessionId = "";
        String completeHeader = "";
        String logType = "";
        int separatorIndex = 0;

        while (headerNames.hasMoreElements()) {
            String element = headerNames.nextElement();
            completeHeader += (element + ": " + req.getHeader(element) + "\n");
        }

        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                //              System.out.println ("Cookie " + i + ": " + cookies[i].getName() + " = " + cookies[i].getValue());
                if (cookies[i].getName().equals("_currUser")) {
                    separatorIndex = cookies[i].getValue().indexOf("%20");
                    cookieUsername = cookies[i].getValue().substring(0, separatorIndex);
                }

                if (cookies[i].getName().equals("JSESSIONID")) {
                    cookieSessionId = cookies[i].getValue();
                }
            }
        }

        // build an array for used ids with all char strings, beginning with # and ending with / or . 
        // (ending with non a-z, A-Z, 0-9 or -)
        // regular expression: /#([A-Za-z0-9\-]+)/

        Pattern p = Pattern.compile("#([a-zA-Z0-9-_]+)");
        String text = req.getParameter("dompath2");
        @SuppressWarnings("unused")
        List<String> idArray = getMatches(p, text);

        //          System.out.println (idArray.toString());

        // then build another array for used classes with all char strings, beginning with . and ending with / or .
        // if class contains spaces, split it to multiple classes

        // regular expression: /\.[A-Za-z0-9\- ]+/

        p = Pattern.compile("\\.([a-zA-Z0-9- _]+)");
        text = req.getParameter("dompath2");
        List<String> classArray = getMatches(p, text, 1);

        //          System.out.println (classArray.toString());

        // logType is the type of logging information
        // where in page has user clicked? Bookmark area,...  
        logType = req.getParameter("dompath").replaceFirst("^[^#]+#", "");
        logType = logType.replaceFirst("/.*$", "");

        // if class tagcloud exists, add to type with blank inbetween
        // if class bmown set bmown-value to 1 otherwise to 0

        String abmown = "0";
        // if classArray contains class bmown, then link is users own bookmark
        if (classArray.contains("bmown")) {
            abmown = "1";
        } else {
            abmown = "0";
        }

        org.bibsonomy.logging.Log LogData = new org.bibsonomy.logging.Log();

        LogData.setAhref(req.getParameter("ahref"));
        LogData.setAcontent(req.getParameter("acontent"));
        LogData.setAnumberofposts(req.getParameter("numberofposts"));
        LogData.setDompath(req.getParameter("dompath"));
        LogData.setDompath2(req.getParameter("dompath2"));
        LogData.setType(logType);
        LogData.setPageurl(req.getParameter("pageurl"));
        LogData.setUseragent(req.getHeader("user-agent"));

        if (req.getParameter("username").isEmpty()) {
            LogData.setUsername(cookieUsername);
        } else {
            LogData.setUsername(req.getParameter("username"));
        }

        LogData.setSessionid(cookieSessionId);
        LogData.setHost(req.getHeader("host"));
        LogData.setCompleteheader(completeHeader);
        LogData.setXforwardedfor(req.getHeader("X-Forwarded-For"));
        LogData.setListpos(req.getParameter("listpos"));
        LogData.setWindowsize(req.getParameter("windowsize"));
        LogData.setMouseclientpos(req.getParameter("mouseclientpos"));
        LogData.setMousedocumentpos(req.getParameter("mousedocumentpos"));
        LogData.setAbmown(abmown);
        LogData.setReferer(req.getParameter("referer"));

        log.debug("LogData to insert:\n" + LogData.toString());
        log.info("Clicked at anchor with shown text: " + LogData.getAcontent());

        try {
            QueryDB.getInstance().insertLogdata(LogData);
            log.info("Database access: insertLogdata ok");

        } catch (SQLException e) {
            log.error("Database error: insertLogdata", e);
        }

    }
}

From source file:org.openqa.grid.internal.TestSession.java

private HttpRequest prepareProxyRequest(HttpServletRequest request
/*, ForwardConfiguration config*/) throws IOException {
    URL remoteURL = slot.getRemoteURL();

    String pathSpec = request.getServletPath() + request.getContextPath();
    String path = request.getRequestURI();
    if (!path.startsWith(pathSpec)) {
        throw new IllegalStateException("Expected path " + path + " to start with pathSpec " + pathSpec);
    }/*from ww w  .j  a va 2s  .  com*/
    String end = path.substring(pathSpec.length());
    String ok = remoteURL + end;
    if (request.getQueryString() != null) {
        ok += "?" + request.getQueryString();
    }
    String uri = new URL(remoteURL, ok).toExternalForm();

    InputStream body = null;
    if (request.getContentLength() > 0 || request.getHeader("Transfer-Encoding") != null) {
        body = request.getInputStream();
    }

    HttpRequest proxyRequest;

    if (body != null) {
        BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest(request.getMethod(), uri);
        r.setEntity(new InputStreamEntity(body, request.getContentLength()));
        proxyRequest = r;
    } else {
        proxyRequest = new BasicHttpRequest(request.getMethod(), uri);
    }

    for (Enumeration<?> e = request.getHeaderNames(); e.hasMoreElements();) {
        String headerName = (String) e.nextElement();

        if ("Content-Length".equalsIgnoreCase(headerName)) {
            continue; // already set
        }

        proxyRequest.setHeader(headerName, request.getHeader(headerName));
    }
    return proxyRequest;
}

From source file:org.oclc.oai.server.OAIHandler.java

/**
 * Peform the http GET action. Note that POST is shunted to here as well. The verb widget is taken from the request and
 * used to invoke an OAIVerb object of the corresponding kind to do the actual work of the verb.
 *
 * @param request  the servlet's request information
 * @param response the servlet's response information
 * @throws IOException an I/O error occurred
 *//*  ww  w. java 2 s.c o  m*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Map attributes = getAttributes(request.getPathInfo());
    if (!filterRequest(request, response)) {
        return;
    }
    //      log.debug("attributes=" + attributes);
    Properties properties = (Properties) attributes.get("OAIHandler.properties");
    boolean monitor = false;
    if (properties.getProperty("OAIHandler.monitor") != null) {
        monitor = true;
    }
    boolean serviceUnavailable = isServiceUnavailable(properties);
    String extensionPath = properties.getProperty("OAIHandler.extensionPath", "/extension");

    Map serverVerbs = ServerVerb.getVerbs(properties);
    Map extensionVerbs = ServerVerb.getExtensionVerbs(properties);

    Transformer transformer = (Transformer) attributes.get("OAIHandler.transformer");

    boolean forceRender = false;
    if ("true".equals(properties.getProperty("OAIHandler.forceRender"))) {
        forceRender = true;
    }

    // try {
    request.setCharacterEncoding("UTF-8");
    // } catch (UnsupportedEncodingException e) {
    // e.printStackTrace();
    // throw new IOException(e.getMessage());
    // }
    Date then = null;
    if (monitor)
        then = new Date();
    if (debug) {
        Enumeration headerNames = request.getHeaderNames();
        System.out.println("OAIHandler.doGet: ");
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            System.out.print(headerName);
            System.out.print(": ");
            System.out.println(request.getHeader(headerName));
        }
    }
    if (serviceUnavailable) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                "Sorry. This server is down for maintenance");
    } else {
        try {
            String userAgent = request.getHeader("User-Agent");
            if (userAgent == null) {
                userAgent = "";
            } else {
                userAgent = userAgent.toLowerCase();
            }
            Transformer serverTransformer = null;
            if (transformer != null) {

                // return HTML if the client is an old browser
                if (forceRender || userAgent.indexOf("opera") != -1
                        || (userAgent.startsWith("mozilla") && userAgent.indexOf("msie 6") == -1
                        /* && userAgent.indexOf("netscape/7") == -1 */)) {
                    serverTransformer = transformer;
                }
            }
            String result = getResult(attributes, request, response, serverTransformer, serverVerbs,
                    extensionVerbs, extensionPath);
            // log.debug("result=" + result);

            // if (serverTransformer) { // render on the server
            // response.setContentType("text/html; charset=UTF-8");
            // StringReader stringReader = new StringReader(getResult(request));
            // StreamSource streamSource = new StreamSource(stringReader);
            // StringWriter stringWriter = new StringWriter();
            // transformer.transform(streamSource, new StreamResult(stringWriter));
            // result = stringWriter.toString();
            // } else { // render on the client
            // response.setContentType("text/xml; charset=UTF-8");
            // result = getResult(request);
            // }

            Writer out = getWriter(request, response);
            out.write(result);
            out.close();
        } catch (FileNotFoundException e) {
            if (debug) {
                e.printStackTrace();
                System.out.println("SC_NOT_FOUND: " + e.getMessage());
            }
            response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        } catch (TransformerException e) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } catch (OAIInternalServerError e) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } catch (SocketException e) {
            System.out.println(e.getMessage());
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } catch (Throwable e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
    if (monitor) {
        StringBuffer reqUri = new StringBuffer(request.getRequestURI());
        String queryString = request.getQueryString(); // d=789
        if (queryString != null) {
            reqUri.append("?").append(queryString);
        }
        //Runtime rt = Runtime.getRuntime();
        //System.out.println(rt.freeMemory() + "/" + rt.totalMemory() + " " + ((new Date()).getTime() - then.getTime()) + "ms: " + reqUri.toString());
    }
}

From source file:net.oauth.signature.GoogleCodeCompatibilityTests.java

/**
 * tests compatibility of calculating the signature base string.
 *///from www.jav  a  2 s.  c  o  m
@Test
public void testCalculateSignatureBaseString() throws Exception {
    final String baseUrl = "http://www.springframework.org/schema/security/";
    CoreOAuthProviderSupport support = new CoreOAuthProviderSupport() {
        @Override
        protected String getBaseUrl(HttpServletRequest request) {
            return baseUrl;
        }
    };

    Map<String, String[]> parameterMap = new HashMap<String, String[]>();
    parameterMap.put("a", new String[] { "value-a" });
    parameterMap.put("b", new String[] { "value-b" });
    parameterMap.put("c", new String[] { "value-c" });
    parameterMap.put("param[1]", new String[] { "aaa", "bbb" });

    when(request.getParameterNames()).thenReturn(Collections.enumeration(parameterMap.keySet()));
    for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
        when(request.getParameterValues(param.getKey())).thenReturn(param.getValue());
    }

    String header = "OAuth realm=\"http://sp.example.com/\","
            + "                oauth_consumer_key=\"0685bd9184jfhq22\","
            + "                oauth_token=\"ad180jjd733klru7\","
            + "                oauth_signature_method=\"HMAC-SHA1\","
            + "                oauth_signature=\"wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D\","
            + "                oauth_timestamp=\"137131200\"," + "                oauth_callback=\""
            + OAuthCodec.oauthEncode("http://myhost.com/callback") + "\","
            + "                oauth_nonce=\"4572616e48616d6d65724c61686176\","
            + "                oauth_version=\"1.0\"";
    when(request.getHeaders("Authorization")).thenReturn(Collections.enumeration(Arrays.asList(header)));
    when(request.getMethod()).thenReturn("GET");
    String ours = support.getSignatureBaseString(request);

    when(request.getHeaders("Authorization")).thenReturn(Collections.enumeration(Arrays.asList(header)));
    when(request.getParameterMap()).thenReturn(parameterMap);
    when(request.getHeaderNames()).thenReturn(null);
    OAuthMessage message = OAuthServlet.getMessage(request, baseUrl);

    String theirs = OAuthSignatureMethod.getBaseString(message);
    assertEquals(theirs, ours);
}

From source file:br.gov.lexml.server.LexMLOAIHandler.java

/**
 * Peform the http GET action. Note that POST is shunted to here as well. The verb widget is
 * taken from the request and used to invoke an OAIVerb object of the corresponding kind to do
 * the actual work of the verb./* w  w w  . j a  va  2s .  co m*/
 * 
 * @param request the servlet's request information
 * @param response the servlet's response information
 * @exception IOException an I/O error occurred
 */
@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {

    // Fora gerao do cookie de sesso
    // (necessrio para balanceamento de carga pelo pound do Prodasen)
    request.getSession();

    HashMap attributes = getAttributes(request.getPathInfo());
    if (!filterRequest(request, response)) {
        return;
    }
    log.debug("attributes = " + attributes);
    Properties properties = (Properties) attributes.get("OAIHandler.properties");
    boolean monitor = false;
    if (properties.getProperty("OAIHandler.monitor") != null) {
        monitor = true;
    }
    boolean serviceUnavailable = isServiceUnavailable(properties);
    String extensionPath = properties.getProperty("OAIHandler.extensionPath", "/extension");

    HashMap serverVerbs = ServerVerb.getVerbs(properties);
    HashMap extensionVerbs = ServerVerb.getExtensionVerbs(properties);

    Transformer transformer = (Transformer) attributes.get("OAIHandler.transformer");

    boolean forceRender = false;
    if ("true".equals(properties.getProperty("OAIHandler.forceRender"))) {
        forceRender = true;
    }

    request.setCharacterEncoding("UTF-8");

    Date then = null;
    if (monitor) {
        then = new Date();
    }
    if (debug) {
        Enumeration headerNames = request.getHeaderNames();
        log.debug("OAIHandler.doGet: ");
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            log.debug(headerName + ": " + request.getHeader(headerName));
        }
    }
    if (serviceUnavailable) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                "Sorry. This server is down for maintenance");
    } else {
        try {
            String userAgent = request.getHeader("User-Agent");
            if (userAgent == null) {
                userAgent = "";
            } else {
                userAgent = userAgent.toLowerCase();
            }
            Transformer serverTransformer = null;
            if (transformer != null) {

                // return HTML if the client is an old browser
                if (forceRender || userAgent.indexOf("opera") != -1
                        || userAgent.startsWith("mozilla") && userAgent.indexOf("msie 6") == -1
                /* && userAgent.indexOf("netscape/7") == -1 */) {
                    serverTransformer = transformer;
                }
            }
            String result = LexMLOAIHandler.getResult(attributes, request, response, serverTransformer,
                    serverVerbs, extensionVerbs, extensionPath);

            Writer out = LexMLOAIHandler.getWriter(request, response);
            out.write(result);
            out.flush();
            IOUtils.closeQuietly(out);
        } catch (FileNotFoundException e) {
            log.error("Falha no processamento.", e);
            response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        } catch (Throwable e) {
            log.error("Falha no processamento.", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
    if (monitor) {
        StringBuffer reqUri = new StringBuffer(request.getRequestURI());
        String queryString = request.getQueryString(); // d=789
        if (queryString != null) {
            reqUri.append("?").append(queryString);
        }
        Runtime rt = Runtime.getRuntime();
        log.debug(rt.freeMemory() + "/" + rt.totalMemory() + " " + (new Date().getTime() - then.getTime())
                + "ms: " + reqUri.toString());
    }
}

From source file:com.sg.rest.filters.LoggerFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (!(request instanceof HttpServletRequest)) {
        LOGGER.error(NON_HTTP_REQUEST + System.lineSeparator() + request.getInputStream().toString());
        throw new RuntimeException(EXPECTING_AN_HTTP_REQUEST);
    }/*  www.  ja  v a2 s. c o m*/

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    StringBuilder sb = new StringBuilder();
    //General header
    sb.append(System.lineSeparator());
    sb.append(INCOMING_REQUEST);
    //Request url
    sb.append(System.lineSeparator());
    sb.append(REQUEST_URL);
    sb.append(httpRequest.getRequestURL());
    //Method
    sb.append(System.lineSeparator());
    sb.append(METHOD);
    sb.append(httpRequest.getMethod());
    //Parameters
    if (httpRequest.getParameterNames().hasMoreElements()) {
        sb.append(System.lineSeparator());
        sb.append(PARAMETERS);
        Enumeration enParams = httpRequest.getParameterNames();
        while (enParams.hasMoreElements()) {
            sb.append(System.lineSeparator());
            String paramName = (String) enParams.nextElement();
            sb.append(paramName);
            sb.append(" : ");
            sb.append(httpRequest.getParameter(paramName));
        }
    }
    //Attributes
    if (httpRequest.getAttributeNames().hasMoreElements()) {
        sb.append(System.lineSeparator());
        sb.append(ATTRIBUTES);
        Enumeration enAttribs = httpRequest.getAttributeNames();
        while (enAttribs.hasMoreElements()) {
            sb.append(System.lineSeparator());
            String attribName = (String) enAttribs.nextElement();
            sb.append(attribName);
            sb.append(" : ");
            sb.append(httpRequest.getAttribute(attribName));
        }
    }
    //Headers
    if (httpRequest.getHeaderNames().hasMoreElements()) {
        sb.append(System.lineSeparator());
        sb.append(HEADERS);
        Enumeration enHeaders = httpRequest.getHeaderNames();
        while (enHeaders.hasMoreElements()) {
            sb.append(System.lineSeparator());
            String headerName = (String) enHeaders.nextElement();
            sb.append(headerName);
            sb.append(" : ");
            sb.append(httpRequest.getHeader(headerName));
        }
    }
    //AuthType
    if (httpRequest.getAuthType() != null && !httpRequest.getAuthType().isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(AUTH_TYPE);
        sb.append(httpRequest.getAuthType());
    }
    //Cookies
    if (httpRequest.getCookies() != null && httpRequest.getCookies().length > 0) {
        sb.append(System.lineSeparator());
        sb.append(COOKIES);
        for (Cookie cookie : httpRequest.getCookies()) {
            sb.append(System.lineSeparator());
            sb.append(cookie.getName());
            sb.append(" : ");
            sb.append(cookie.getValue());
        }
    }
    //RemoteAddr
    if (httpRequest.getRemoteAddr() != null && !httpRequest.getRemoteAddr().isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(REMOTE_ADDR);
        sb.append(httpRequest.getRemoteAddr());
    }
    //RemoteHost
    if (httpRequest.getRemoteHost() != null && !httpRequest.getRemoteHost().isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(REMOTE_HOST);
        sb.append(httpRequest.getRemoteHost());
    }
    //User principal
    if (httpRequest.getUserPrincipal() != null) {
        if (httpRequest.getUserPrincipal().getName() != null
                && !httpRequest.getUserPrincipal().getName().isEmpty()) {
            sb.append(System.lineSeparator());
            sb.append(PRINCIPAL);
            sb.append(httpRequest.getUserPrincipal().getName());
        }
    }
    //Body
    ResettableStreamHttpServletRequest wrappedRequest = new ResettableStreamHttpServletRequest(
            (HttpServletRequest) request);
    String body = IOUtils.toString(wrappedRequest.getReader());
    if (body != null && !body.isEmpty()) {
        sb.append(System.lineSeparator());
        sb.append(BODY);
        sb.append(System.lineSeparator());
        sb.append(body);
    }
    wrappedRequest.resetInputStream();

    LOGGER.info(sb.toString());
    chain.doFilter(wrappedRequest, response);
}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private static void handleUploadPart(HttpServletRequest request, HttpServletResponse response, InputStream is,
        BlobStore blobStore, String containerName, String blobName, String uploadId)
        throws IOException, S3Exception {
    // TODO: duplicated from handlePutBlob
    String contentLengthString = null;
    String decodedContentLengthString = null;
    String contentMD5String = null;
    for (String headerName : Collections.list(request.getHeaderNames())) {
        String headerValue = Strings.nullToEmpty(request.getHeader(headerName));
        if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) {
            contentLengthString = headerValue;
        } else if (headerName.equalsIgnoreCase("x-amz-decoded-content-length")) {
            decodedContentLengthString = headerValue;
        } else if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_MD5)) {
            contentMD5String = headerValue;
        }/*from   ww  w .  j  a va2  s  .  c o m*/
    }
    if (decodedContentLengthString != null) {
        contentLengthString = decodedContentLengthString;
    }

    HashCode contentMD5 = null;
    if (contentMD5String != null) {
        try {
            contentMD5 = HashCode.fromBytes(BaseEncoding.base64().decode(contentMD5String));
        } catch (IllegalArgumentException iae) {
            throw new S3Exception(S3ErrorCode.INVALID_DIGEST, iae);
        }
        if (contentMD5.bits() != Hashing.md5().bits()) {
            throw new S3Exception(S3ErrorCode.INVALID_DIGEST);
        }
    }

    if (contentLengthString == null) {
        throw new S3Exception(S3ErrorCode.MISSING_CONTENT_LENGTH);
    }
    long contentLength;
    try {
        contentLength = Long.parseLong(contentLengthString);
    } catch (NumberFormatException nfe) {
        throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT, nfe);
    }
    if (contentLength < 0) {
        throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT);
    }

    String partNumberString = request.getParameter("partNumber");
    if (partNumberString == null) {
        throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT);
    }
    int partNumber;
    try {
        partNumber = Integer.parseInt(partNumberString);
    } catch (NumberFormatException nfe) {
        throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT,
                "Part number must be an integer between 1 and 10000" + ", inclusive", nfe,
                ImmutableMap.of("ArgumentName", "partNumber", "ArgumentValue", partNumberString));
    }
    if (partNumber < 1 || partNumber > 10_000) {
        throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT,
                "Part number must be an integer between 1 and 10000" + ", inclusive", (Throwable) null,
                ImmutableMap.of("ArgumentName", "partNumber", "ArgumentValue", partNumberString));
    }

    // TODO: how to reconstruct original mpu?
    MultipartUpload mpu = MultipartUpload.create(containerName, blobName, uploadId,
            createFakeBlobMetadata(blobStore), new PutOptions());

    if (getBlobStoreType(blobStore).equals("azureblob")) {
        // Azure has a maximum part size of 4 MB while S3 has a minimum
        // part size of 5 MB and a maximum of 5 GB.  Split a single S3
        // part multiple Azure parts.
        long azureMaximumMultipartPartSize = blobStore.getMaximumMultipartPartSize();
        HashingInputStream his = new HashingInputStream(Hashing.md5(), is);
        for (int offset = 0, subPartNumber = 0; offset < contentLength; offset += azureMaximumMultipartPartSize, ++subPartNumber) {
            Payload payload = Payloads
                    .newInputStreamPayload(ByteStreams.limit(his, azureMaximumMultipartPartSize));
            payload.getContentMetadata()
                    .setContentLength(Math.min(azureMaximumMultipartPartSize, contentLength - offset));
            blobStore.uploadMultipartPart(mpu, 10_000 * partNumber + subPartNumber, payload);
        }
        response.addHeader(HttpHeaders.ETAG,
                maybeQuoteETag(BaseEncoding.base16().lowerCase().encode(his.hash().asBytes())));
    } else {
        MultipartPart part;
        Payload payload = Payloads.newInputStreamPayload(is);
        payload.getContentMetadata().setContentLength(contentLength);
        if (contentMD5 != null) {
            payload.getContentMetadata().setContentMD5(contentMD5);
        }

        part = blobStore.uploadMultipartPart(mpu, partNumber, payload);

        if (part.partETag() != null) {
            response.addHeader(HttpHeaders.ETAG, maybeQuoteETag(part.partETag()));
        }
    }
}

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

public void performTask(javax.servlet.http.HttpServletRequest request,
        javax.servlet.http.HttpServletResponse response) {

    /**/* www .j ava 2  s .  c om*/
    * 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. 
    * 
    * 
    * 
    * 
    * 
    * 
    */

    logger.debug(" Directory to store all the uploaded files");

    String ourTempDirectory = "/opt/erp/import/obras/";
    try {
        out = response.getWriter();
    } catch (Exception e) {
        e.printStackTrace();
    }

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

    logger.debug("Initialization for chunk management.");
    boolean bLastChunk = false;
    int numChunk = 0;

    logger.debug(
            "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();
    out.println("[parseRequest.jsp]  ------------------------------ ");
    out.println("[parseRequest.jsp]  Headers of the received request:");
    logger.debug("[parseRequest.jsp]  Headers of the received request:");
    while (headers.hasMoreElements()) {
        String header = headers.nextElement();
        out.println("[parseRequest.jsp]  " + header + ": " + request.getHeader(header));
        logger.debug("[parseRequest.jsp]  " + header + ": " + request.getHeader(header));
    }
    out.println("[parseRequest.jsp]  ------------------------------ ");

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

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

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

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

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

        logger.debug(" Create a factory for disk-based file items");
        DiskFileItemFactory factory = new DiskFileItemFactory();

        logger.debug(" Set factory constraints");
        factory.setSizeThreshold(ourMaxMemorySize);
        logger.debug("ourTempDirectory" + ourTempDirectory);
        factory.setRepository(new File(ourTempDirectory));

        logger.debug(" Create a new file upload handler");
        ServletFileUpload upload = new ServletFileUpload(factory);

        logger.debug(" Set overall request size constraint");
        upload.setSizeMax(ourMaxRequestSize);

        logger.debug(" Parse the request");
        if (sendRequest) {
            logger.debug("For debug only. Should be removed for production systems. ");
            out.println(
                    "[parseRequest.jsp] ===========================================================================");
            out.println("[parseRequest.jsp] Sending the received request content: ");
            logger.debug("[parseRequest.jsp] Sending the received request content: ");
            InputStream is = request.getInputStream();
            int c;
            while ((c = is.read()) >= 0) {
                out.write(c);
            }
            logger.debug("while");
            is.close();
            out.println(
                    "[parseRequest.jsp] ===========================================================================");
        } else if (!request.getContentType().startsWith("multipart/form-data")) {
            out.println("[parseRequest.jsp] No parsing of uploaded file: content type is "
                    + request.getContentType());
        } else {

            List /* FileItem */ items = upload.parseRequest(request);

            logger.debug(" Process the uploaded items" + items.size());

            Iterator iter = items.iterator();
            FileItem fileItem;
            File fout;
            out.println("[parseRequest.jsp]  Let's read the sent data   (" + items.size() + " items)");
            while (iter.hasNext()) {
                fileItem = (FileItem) iter.next();

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

                    logger.debug(
                            "If we receive the md5sum parameter, we've read finished to read the current file. It's not");
                    logger.debug(
                            "a very good (end of file) signal. Will be better in the future ... probably !");
                    logger.debug("Let's put a separator, to make output easier to read.");
                    if (fileItem.getFieldName().equals("md5sum[]")) {
                        out.println("[parseRequest.jsp]  ------------------------------ ");
                    }
                } else {
                    logger.debug("Ok, we've got a file. Let's process it.");
                    logger.debug("Again, for all informations of what is exactly a FileItem, please");
                    logger.debug("have a look to http://jakarta.apache.org/commons/fileupload/");

                    out.println("[parseRequest.jsp] FieldName: " + fileItem.getFieldName());
                    out.println("[parseRequest.jsp] File Name: " + fileItem.getName());
                    out.println("[parseRequest.jsp] ContentType: " + fileItem.getContentType());
                    out.println("[parseRequest.jsp] Size (Bytes): " + fileItem.getSize());
                    logger.debug(
                            "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());
                    out.println("[parseRequest.jsp] File Out: " + fout.toString());
                    logger.debug(" write the file");
                    fileItem.write(fout);

                    //
                    logger.debug("Chunk management: if it was the last chunk, let's recover the complete file");
                    logger.debug("by concatenating all chunk parts.");
                    logger.debug("");
                    if (bLastChunk) {
                        out.println("[parseRequest.jsp]  Last chunk received: let's rebuild the complete file ("
                                + fileItem.getName() + ")");
                        logger.debug("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;
                            out.println("[parseRequest.jsp] " + "  Concatenating " + filename);
                            fis = new FileInputStream(ourTempDirectory + filename);
                            while ((nbBytes = fis.read(byteBuff)) >= 0) {
                                //out.println("[parseRequest.jsp] " + "     Nb bytes read: " + nbBytes);
                                fos.write(byteBuff, 0, nbBytes);
                            }
                            fis.close();
                        }
                        fos.close();
                    }

                    logger.debug(" End of chunk management");
                    //

                    fileItem.delete();
                }
            }
            logger.debug("while");
        }

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

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

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

        logger.debug("Do you want to test a successful upload, or the way the applet reacts to an error ?");
        if (generateError) {
            out.println(
                    "ERROR: this is a test error (forced in /wwwroot/pages/parseRequest.jsp).\\nHere is a second line!");
        } else {
            out.println("SUCCESS");
            logger.debug("");
        }

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

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

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private static void handlePutBlob(HttpServletRequest request, HttpServletResponse response, InputStream is,
        BlobStore blobStore, String containerName, String blobName) throws IOException, S3Exception {
    // Flag headers present since HttpServletResponse.getHeader returns
    // null for empty headers values.
    String contentLengthString = null;
    String decodedContentLengthString = null;
    String contentMD5String = null;
    for (String headerName : Collections.list(request.getHeaderNames())) {
        String headerValue = Strings.nullToEmpty(request.getHeader(headerName));
        if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) {
            contentLengthString = headerValue;
        } else if (headerName.equalsIgnoreCase("x-amz-decoded-content-length")) {
            decodedContentLengthString = headerValue;
        } else if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_MD5)) {
            contentMD5String = headerValue;
        }//  ww w.  ja  v  a2 s. c om
    }
    if (decodedContentLengthString != null) {
        contentLengthString = decodedContentLengthString;
    }

    HashCode contentMD5 = null;
    if (contentMD5String != null) {
        try {
            contentMD5 = HashCode.fromBytes(BaseEncoding.base64().decode(contentMD5String));
        } catch (IllegalArgumentException iae) {
            throw new S3Exception(S3ErrorCode.INVALID_DIGEST, iae);
        }
        if (contentMD5.bits() != Hashing.md5().bits()) {
            throw new S3Exception(S3ErrorCode.INVALID_DIGEST);
        }
    }

    if (contentLengthString == null) {
        throw new S3Exception(S3ErrorCode.MISSING_CONTENT_LENGTH);
    }
    long contentLength;
    try {
        contentLength = Long.parseLong(contentLengthString);
    } catch (NumberFormatException nfe) {
        throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT, nfe);
    }
    if (contentLength < 0) {
        throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT);
    }

    BlobAccess access;
    String cannedAcl = request.getHeader("x-amz-acl");
    if (cannedAcl == null || cannedAcl.equalsIgnoreCase("private")) {
        access = BlobAccess.PRIVATE;
    } else if (cannedAcl.equalsIgnoreCase("public-read")) {
        access = BlobAccess.PUBLIC_READ;
    } else if (CANNED_ACLS.contains(cannedAcl)) {
        throw new S3Exception(S3ErrorCode.NOT_IMPLEMENTED);
    } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    PutOptions options = new PutOptions().setBlobAccess(access);

    String blobStoreType = getBlobStoreType(blobStore);
    if (blobStoreType.equals("azureblob") && contentLength > 64 * 1024 * 1024) {
        options.multipart(true);
    }

    String eTag;
    try {
        BlobBuilder.PayloadBlobBuilder builder = blobStore.blobBuilder(blobName).payload(is)
                .contentLength(contentLength);

        addContentMetdataFromHttpRequest(builder, request);
        if (contentMD5 != null) {
            builder = builder.contentMD5(contentMD5);
        }

        eTag = blobStore.putBlob(containerName, builder.build(), options);
    } catch (HttpResponseException hre) {
        HttpResponse hr = hre.getResponse();
        if (hr == null) {
            return;
        }
        int status = hr.getStatusCode();
        switch (status) {
        case HttpServletResponse.SC_BAD_REQUEST:
        case 422: // Swift returns 422 Unprocessable Entity
            throw new S3Exception(S3ErrorCode.BAD_DIGEST);
        default:
            // TODO: emit hre.getContent() ?
            response.sendError(status);
            break;
        }
        return;
    }

    response.addHeader(HttpHeaders.ETAG, maybeQuoteETag(eTag));
}