Example usage for javax.servlet.http HttpServletRequest getContentLength

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

Introduction

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

Prototype

public int getContentLength();

Source Link

Document

Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known ir is greater than Integer.MAX_VALUE.

Usage

From source file:org.signserver.web.GenericProcessServlet.java

/**
 * Handles http post./*from w ww  .j a  va2s .c o m*/
 *
 * @param req servlet request
 * @param res servlet response
 *
 * @throws IOException input/output error
 * @throws ServletException error
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    LOG.debug(">doPost()");

    int workerId = 1;
    byte[] data = null;
    String fileName = null;
    String pdfPassword = null;
    boolean workerRequest = false;

    if (LOG.isDebugEnabled()) {
        LOG.debug("Received a request with length: " + req.getContentLength());
    }

    final String workerNameOverride = (String) req.getAttribute(WORKERNAME_PROPERTY_OVERRIDE);

    if (workerNameOverride != null) {
        workerId = getWorkerSession().getWorkerId(workerNameOverride);
        workerRequest = true;
    }

    final long maxUploadSize = getMaxUploadSize();

    ProcessType processType = ProcessType.signDocument;
    final MetaDataHolder metadataHolder = new MetaDataHolder();

    if (ServletFileUpload.isMultipartContent(req)) {
        final DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(Integer.MAX_VALUE); // Don't write to disk

        final ServletFileUpload upload = new ServletFileUpload(factory);

        // Limit the maximum size of input
        upload.setSizeMax(maxUploadSize);

        try {
            final List items = upload.parseRequest(req);
            final Iterator iter = items.iterator();
            FileItem fileItem = null;
            String encoding = null;
            while (iter.hasNext()) {
                final Object o = iter.next();
                if (o instanceof FileItem) {
                    final FileItem item = (FileItem) o;

                    if (item.isFormField()) {
                        if (!workerRequest) {
                            if (WORKERNAME_PROPERTY_NAME.equals(item.getFieldName())) {
                                if (LOG.isDebugEnabled()) {
                                    LOG.debug("Found a signerName in the request: " + item.getString());
                                }
                                workerId = getWorkerSession().getWorkerId(item.getString());
                            } else if (WORKERID_PROPERTY_NAME.equals(item.getFieldName())) {
                                if (LOG.isDebugEnabled()) {
                                    LOG.debug("Found a signerId in the request: " + item.getString());
                                }
                                try {
                                    workerId = Integer.parseInt(item.getString());
                                } catch (NumberFormatException ignored) {
                                }
                            }
                        }

                        final String itemFieldName = item.getFieldName();

                        if (PDFPASSWORD_PROPERTY_NAME.equals(itemFieldName)) {
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("Found a pdfPassword in the request.");
                            }
                            pdfPassword = item.getString("ISO-8859-1");
                        } else if (PROCESS_TYPE_PROPERTY_NAME.equals(itemFieldName)) {
                            final String processTypeAttribute = item.getString("ISO-8859-1");

                            if (LOG.isDebugEnabled()) {
                                LOG.debug("Found process type in the request: " + processTypeAttribute);
                            }

                            if (processTypeAttribute != null) {
                                try {
                                    processType = ProcessType.valueOf(processTypeAttribute);
                                } catch (IllegalArgumentException e) {
                                    sendBadRequest(res, "Illegal process type: " + processTypeAttribute);
                                    return;
                                }
                            } else {
                                processType = ProcessType.signDocument;
                            }
                        } else if (ENCODING_PROPERTY_NAME.equals(itemFieldName)) {
                            encoding = item.getString("ISO-8859-1");
                        } else if (isFieldMatchingMetaData(itemFieldName)) {
                            try {
                                metadataHolder.handleMetaDataProperty(itemFieldName,
                                        item.getString("ISO-8859-1"));
                            } catch (IOException e) {
                                sendBadRequest(res, "Malformed properties given using REQUEST_METADATA.");
                                return;
                            }
                        }
                    } else {
                        // We only care for one upload at a time right now
                        if (fileItem == null) {
                            fileItem = item;
                        }
                    }
                }
            }

            if (fileItem == null) {
                sendBadRequest(res, "Missing file content in upload");
                return;
            } else {
                fileName = fileItem.getName();
                data = fileItem.get(); // Note: Reads entiry file to memory

                if (encoding != null && !encoding.isEmpty()) {
                    if (ENCODING_BASE64.equalsIgnoreCase(encoding)) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Decoding base64 data");
                        }
                        data = Base64.decode(data);
                    } else {
                        sendBadRequest(res, "Unknown encoding for the 'data' field: " + encoding);
                        return;
                    }
                }
            }
        } catch (FileUploadBase.SizeLimitExceededException ex) {
            LOG.error(HTTP_MAX_UPLOAD_SIZE + " exceeded: " + ex.getLocalizedMessage());
            res.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                    "Maximum content length is " + maxUploadSize + " bytes");
            return;
        } catch (FileUploadException ex) {
            throw new ServletException("Upload failed", ex);
        }
    } else {
        if (!workerRequest) {
            String name = req.getParameter(WORKERNAME_PROPERTY_NAME);
            if (name != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found a signerName in the request: " + name);
                }
                workerId = getWorkerSession().getWorkerId(name);
            }
            String id = req.getParameter(WORKERID_PROPERTY_NAME);
            if (id != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found a signerId in the request: " + id);
                }
                workerId = Integer.parseInt(id);
            }
        }

        final Enumeration<String> params = req.getParameterNames();

        while (params.hasMoreElements()) {
            final String property = params.nextElement();
            if (PDFPASSWORD_PROPERTY_NAME.equals(property)) {
                pdfPassword = (String) req.getParameter(PDFPASSWORD_PROPERTY_NAME);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found a pdfPassword in the request.");
                }
            } else if (isFieldMatchingMetaData(property)) {
                try {
                    metadataHolder.handleMetaDataProperty(property, req.getParameter(property));
                } catch (IOException e) {
                    sendBadRequest(res, "Malformed properties given using REQUEST_METADATA.");
                    return;
                }
            }
        }

        final String processTypeAttribute = (String) req.getParameter(PROCESS_TYPE_PROPERTY_NAME);

        if (processTypeAttribute != null) {
            try {
                processType = ProcessType.valueOf(processTypeAttribute);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found process type in the request: " + processType.name());
                }
            } catch (IllegalArgumentException e) {
                sendBadRequest(res, "Illegal process type: " + processTypeAttribute);
                return;
            }
        } else {
            processType = ProcessType.signDocument;
        }

        if (METHOD_GET.equalsIgnoreCase(req.getMethod())
                || (req.getContentType() != null && req.getContentType().contains(FORM_URL_ENCODED))) {
            LOG.debug("Request is FORM_URL_ENCODED");

            if (req.getParameter(DATA_PROPERTY_NAME) == null) {
                sendBadRequest(res, "Missing field 'data' in request");
                return;
            }
            data = req.getParameter(DATA_PROPERTY_NAME).getBytes();

            String encoding = req.getParameter(ENCODING_PROPERTY_NAME);
            if (encoding != null && !encoding.isEmpty()) {
                if (ENCODING_BASE64.equalsIgnoreCase(encoding)) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Decoding base64 data");
                    }
                    data = Base64.decode(data);
                } else {
                    sendBadRequest(res, "Unknown encoding for the 'data' field: " + encoding);
                    return;
                }
            }
        } else {
            // Pass-through the content to be handled by worker if
            // unknown content-type
            if (LOG.isDebugEnabled()) {
                LOG.debug("Request Content-type: " + req.getContentType());
            }

            // Get an input stream and read the bytes from the stream
            InputStream in = req.getInputStream();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            int len;
            byte[] buf = new byte[1024];
            while ((len = in.read(buf)) > 0) {
                os.write(buf, 0, len);
            }
            in.close();
            os.close();
            data = os.toByteArray();
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Request of type: " + processType.name());
    }

    // Limit the maximum size of input
    if (data.length > maxUploadSize) {
        LOG.error("Content length exceeds " + maxUploadSize + ", not processed: " + req.getContentLength());
        res.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                "Maximum content length is " + maxUploadSize + " bytes");
    } else {
        processRequest(req, res, workerId, data, fileName, pdfPassword, processType, metadataHolder);
    }

    LOG.debug("<doPost()");
}

From source file:com.cloud.bridge.service.controller.s3.S3BucketAction.java

public void executePutBucket(HttpServletRequest request, HttpServletResponse response) throws IOException {
    int contentLength = request.getContentLength();
    Object objectInContent = null;

    if (contentLength > 0) {
        InputStream is = null;/*from   w  w  w .j  av  a 2 s .  c om*/
        try {
            is = request.getInputStream();
            String xml = StringHelper.stringFromStream(is);
            Class.forName("com.cloud.bridge.service.core.s3.S3CreateBucketConfiguration");
            XSerializer serializer = new XSerializer(new XSerializerXmlAdapter());
            objectInContent = serializer.serializeFrom(xml);
            if (objectInContent != null && !(objectInContent instanceof S3CreateBucketConfiguration)) {
                throw new InvalidRequestContentException("Invalid request content in create-bucket: " + xml);
            }
            is.close();

        } catch (IOException e) {
            logger.error("Unable to read request data due to " + e.getMessage(), e);
            throw new NetworkIOException(e);

        } catch (ClassNotFoundException e) {
            logger.error("In a normal world this should never never happen:" + e.getMessage(), e);
            throw new RuntimeException("A required class was not found in the classpath:" + e.getMessage());
        } finally {
            if (is != null)
                is.close();
        }
    }

    S3CreateBucketRequest engineRequest = new S3CreateBucketRequest();
    engineRequest.setBucketName((String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY));
    engineRequest.setConfig((S3CreateBucketConfiguration) objectInContent);
    try {
        S3CreateBucketResponse engineResponse = ServiceProvider.getInstance().getS3Engine()
                .handleRequest(engineRequest);
        response.addHeader("Location", "/" + engineResponse.getBucketName());
        response.setContentLength(0);
        response.setStatus(200);
        response.flushBuffer();
    } catch (ObjectAlreadyExistsException oaee) {
        response.setStatus(409);
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <Error><Code>OperationAborted</Code><Message>A conflicting conditional operation is currently in progress against this resource. Please try again..</Message>";
        response.setContentType("text/xml; charset=UTF-8");
        S3RestServlet.endResponse(response, xml.toString());
    }
}

From source file:org.alfresco.module.vti.handler.alfresco.AlfrescoMethodHandler.java

/**
 * @see org.alfresco.module.vti.handler.MethodHandler#putResource(HttpServletRequest, HttpServletResponse)
 *//*from   ww w . j  a v a 2  s .c o m*/
public void putResource(HttpServletRequest request, HttpServletResponse response) {
    // Office 2008/2011 for Mac specific header
    final String lockTimeOut = request.getHeader(DAV_EXT_LOCK_TIMEOUT);

    if (request.getContentLength() == 0 && lockTimeOut == null) {
        return;
    }

    String decodedUrl = URLDecoder.decode(request.getRequestURI());
    if (decodedUrl.length() > getPathHelper().getAlfrescoContext().length()) {
        decodedUrl = decodedUrl.substring(getPathHelper().getAlfrescoContext().length() + 1);
    }

    FileInfo resourceFileInfo = getPathHelper().resolvePathFileInfo(decodedUrl);
    NodeRef resourceNodeRef = null;

    if (resourceFileInfo != null) {
        resourceNodeRef = resourceFileInfo.getNodeRef();
    }

    if (logger.isDebugEnabled()) {
        logger.debug("The request lock timeout from response is " + lockTimeOut);
        logger.debug("The resource nodeRef is " + resourceNodeRef);
    }

    // Does the file already exist (false), or has it been created by this request? 
    boolean newlyCreated = false;

    // Office 2008/2011 for Mac
    if (resourceNodeRef == null && lockTimeOut != null) {
        try {
            final Pair<String, String> parentChild = VtiPathHelper.splitPathParentChild(decodedUrl);
            final FileInfo parent = getPathHelper().resolvePathFileInfo(parentChild.getFirst());

            RetryingTransactionCallback<NodeRef> cb = new RetryingTransactionCallback<NodeRef>() {
                @Override
                public NodeRef execute() throws Throwable {
                    NodeRef result = getFileFolderService()
                            .create(parent.getNodeRef(), parentChild.getSecond(), ContentModel.TYPE_CONTENT)
                            .getNodeRef();

                    int timeout = Integer.parseInt(lockTimeOut.substring(WebDAV.SECOND.length()));
                    getLockService().lock(result, getUserName(), timeout);

                    return result;
                }
            };

            resourceNodeRef = getTransactionService().getRetryingTransactionHelper().doInTransaction(cb);

            if (resourceNodeRef != null) {
                newlyCreated = true;
            }

            if (logger.isDebugEnabled()) {
                logger.debug("Created new node " + resourceNodeRef);
            }

            response.setStatus(HttpServletResponse.SC_CREATED);
            response.setHeader(WebDAV.HEADER_LOCK_TOKEN, WebDAV.makeLockToken(resourceNodeRef, getUserName()));
            response.setHeader(DAV_EXT_LOCK_TIMEOUT, lockTimeOut);
        } catch (AccessDeniedException e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
    }

    // Check we managed to find the node one way or another
    if (resourceNodeRef == null) {
        if (logger.isInfoEnabled()) {
            logger.info("No node found for resource " + decodedUrl);
        }

        // TODO Is this the correct status code to return if they've
        //  tried to query for something that doesn't exist?
        // Or should we return something else, or even create it?
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Get the working copy of it
    final NodeRef workingCopyNodeRef = getCheckOutCheckInService().getWorkingCopy(resourceNodeRef);

    // ALF-15984
    if (!expectedETagForNode(request, resourceNodeRef)) {
        response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // updates changes on the server

    final BufferedHttpServletRequest bufferedRequest = new BufferedHttpServletRequest(request, streamFactory);
    final NodeRef finalResourceNodeRef = resourceNodeRef;
    final String finalDecodedUrl = decodedUrl;
    final boolean finalNewlyCreated = newlyCreated;
    final String siteId = davHelper.determineSiteId(getPathHelper().getRootNodeRef(), finalDecodedUrl);
    RetryingTransactionCallback<Void> work = new RetryingTransactionCallback<Void>() {
        @SuppressWarnings("deprecation")
        @Override
        public Void execute() throws Throwable {
            ContentWriter writer;
            boolean newlyCreated = finalNewlyCreated;
            FileFolderService fileFolderService = getFileFolderService();
            if (workingCopyNodeRef != null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Writing to the workung copy " + workingCopyNodeRef);
                }
                if (fileFolderService.isHidden(workingCopyNodeRef)) {
                    fileFolderService.setHidden(workingCopyNodeRef, false);
                }

                // working copy writer
                writer = getContentService().getWriter(workingCopyNodeRef, ContentModel.PROP_CONTENT, true);
            } else {
                // ALF-17662, hidden node is the same as non-existed node for SPP
                if (fileFolderService.isHidden(finalResourceNodeRef)) {
                    // make it visible for client
                    fileFolderService.setHidden(finalResourceNodeRef, false);
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Writing to the node " + finalResourceNodeRef);
                }
                // original document writer
                writer = getContentService().getWriter(finalResourceNodeRef, ContentModel.PROP_CONTENT, true);

            }

            String documentName = getNodeService().getProperty(finalResourceNodeRef, ContentModel.PROP_NAME)
                    .toString();
            String mimetype = getMimetypeService().guessMimetype(documentName);
            writer.setMimetype(mimetype);
            writer.putContent(bufferedRequest.getInputStream());

            // If needed, mark the node as having now had its content supplied
            if (getNodeService().hasAspect(finalResourceNodeRef, ContentModel.ASPECT_WEBDAV_NO_CONTENT)) {
                // CLOUD-2209: newly created documents not shown in activity feed.
                newlyCreated = true;
                getNodeService().removeAspect(finalResourceNodeRef, ContentModel.ASPECT_WEBDAV_NO_CONTENT);
            }

            // If we actually have content, it's time to add the versionable aspect and save the current version
            ContentData contentData = writer.getContentData();
            if (workingCopyNodeRef == null
                    && !getNodeService().hasAspect(finalResourceNodeRef, ContentModel.ASPECT_VERSIONABLE)
                    && ContentData.hasContent(contentData) && contentData.getSize() > 0) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Creating a new major version for " + finalResourceNodeRef);
                }
                getVersionService().createVersion(finalResourceNodeRef, Collections
                        .<String, Serializable>singletonMap(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR));
            }

            if (siteId != null) {
                String tenantDomain = davHelper.determineTenantDomain();
                long fileSize = contentData.getSize();
                reportUploadEvent(finalDecodedUrl, siteId, tenantDomain, newlyCreated, mimetype, fileSize);
            }

            return null;
        }
    };

    try {
        getTransactionService().getRetryingTransactionHelper().doInTransaction(work);
    } catch (Exception e) {
        if (logger.isDebugEnabled()) {
            logger.debug("An exception occurred during writing the content.", e);
        }
        response.setStatus(HttpServletResponse.SC_CONFLICT);
        return;
    } finally {
        if (bufferedRequest != null) {
            bufferedRequest.close();
        }
    }

    // original document properties
    Map<QName, Serializable> props = getNodeService().getProperties(resourceNodeRef);

    if (workingCopyNodeRef != null) {
        String workingCopyOwner = getNodeService()
                .getProperty(workingCopyNodeRef, ContentModel.PROP_WORKING_COPY_OWNER).toString();
        if (workingCopyOwner.equals(getAuthenticationService().getCurrentUserName())) {
            // working copy properties
            props = getNodeService().getProperties(workingCopyNodeRef);
        }
    }
    String guid = resourceNodeRef.getId().toUpperCase();
    Date lastModified = (Date) props.get(ContentModel.PROP_MODIFIED);
    response.setHeader("Repl-uid", VtiUtils.constructRid(guid));
    response.setHeader("ResourceTag", VtiUtils.constructResourceTag(guid, lastModified));
    response.setHeader("Last-Modified", VtiUtils.formatBrowserDate(lastModified));
    response.setHeader("ETag", VtiUtils.constructETag(guid, lastModified));

    ContentReader reader = getContentService().getReader(resourceNodeRef, ContentModel.PROP_CONTENT);
    String mimetype = reader == null ? null : reader.getMimetype();

    if (mimetype != null) {
        response.setContentType(mimetype);
    }
}

From source file:com.reachcall.pretty.http.ProxyServlet.java

@SuppressWarnings("unchecked")
private void doPost(HttpPost method, HttpServletRequest req) throws IOException {
    copyHeaders(req, method);//from w w w  . j  av a2  s .c o m
    if (CONTENT_TYPE_FORM.equalsIgnoreCase(req.getContentType())) {
        Map<String, String[]> params = (Map<String, String[]>) req.getParameterMap();
        List<NameValuePair> pairs = new LinkedList<NameValuePair>();

        for (String name : params.keySet()) {
            String[] values = params.get(name);

            for (String value : values) {
                NameValuePair pair = new BasicNameValuePair(name, value);
                pairs.add(pair);
            }
        }

        method.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
    } else {
        method.setEntity(new InputStreamEntity(req.getInputStream(), req.getContentLength()));
    }
}

From source file:com.mb.ext.web.controller.UserController.java

@RequestMapping(value = "/wechatPayResponse", method = RequestMethod.POST)
@ResponseBody//  w w w  .  j  a  va 2 s  .  c o  m
public String wechatPayResponse(HttpServletRequest request, HttpServletResponse response) {
    int length = request.getContentLength();
    byte[] bytes = new byte[length];
    InputStream inputStream;
    try {
        inputStream = request.getInputStream();
        inputStream.read(bytes);
        String responseStr = new String(bytes, "UTF-8");

        XStream xstream = new XStream(new XppDriver() {
            public HierarchicalStreamWriter createWriter(Writer out) {
                return new PrettyPrintWriter(out) {
                    // CDATA
                    boolean cdata = true;

                    @SuppressWarnings("rawtypes")
                    public void startNode(String name, Class clazz) {
                        super.startNode(name, clazz);
                    }

                    protected void writeText(QuickWriter writer, String text) {
                        if (cdata) {
                            writer.write("<![CDATA[");
                            writer.write(text);
                            writer.write("]]>");
                        } else {
                            writer.write(text);
                        }
                    }
                };
            }
        });

        xstream.alias("xml", PayResultResponse.class);
        PayResultResponse payResultResponse = (PayResultResponse) xstream.fromXML(responseStr);

        if (!"SUCCESS".equals(payResultResponse.getResult_code())
                || !"SUCCESS".equals(payResultResponse.getResult_code())) {
            response.sendError(500);
        } else {
            String orderNumber = payResultResponse.getOut_trade_no();
            try {
                userService.updateOrderStatus(orderNumber, Constants.ORDER_STATUS_INPROGRESS);
                return WechatConstants.SUCCESS_RESPONSE;
            } catch (BusinessException e) {
                logger.error(e.getMessage());
                response.sendError(500);
            }
        }

    } catch (Exception e) {
        logger.error(e.getMessage());
        try {
            response.sendError(500);
        } catch (IOException e1) {
            logger.error(e1.getMessage());
        }
    }
    return "";
}

From source file:org.red5.server.net.rtmpt.RTMPTServlet.java

/**
 * Add data for an established session./*from   w w  w.  j  a v a  2s. c  o  m*/
 * 
 * @param req
 *            Servlet request
 * @param resp
 *            Servlet response
 * @throws IOException
 *             I/O exception
 */
protected void handleSend(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    log.debug("handleSend");
    final RTMPTConnection conn = getConnection();
    if (conn != null) {
        IoSession session = conn.getIoSession();
        // get the handshake from the session
        InboundHandshake handshake = null;
        // put the received data in a ByteBuffer
        int length = req.getContentLength();
        log.trace("Request content length: {}", length);
        final IoBuffer message = IoBuffer.allocate(length);
        ServletUtils.copy(req, message.asOutputStream());
        message.flip();
        RTMP rtmp = conn.getState();
        int connectionState = rtmp.getState();
        switch (connectionState) {
        case RTMP.STATE_CONNECT:
            // we're expecting C0+C1 here
            //log.trace("C0C1 byte order: {}", message.order());
            log.debug("decodeHandshakeC0C1 - buffer: {}", message);
            // we want 1537 bytes for C0C1
            if (message.remaining() >= (Constants.HANDSHAKE_SIZE + 1)) {
                // get the connection type byte, may want to set this on the conn in the future
                byte connectionType = message.get();
                log.trace("Incoming C0 connection type: {}", connectionType);
                // add the in-bound handshake, defaults to non-encrypted mode
                handshake = new InboundHandshake(connectionType);
                session.setAttribute(RTMPConnection.RTMP_HANDSHAKE, handshake);
                // create array for decode
                byte[] dst = new byte[Constants.HANDSHAKE_SIZE];
                // copy out 1536 bytes
                message.get(dst);
                //log.debug("C1 - buffer: {}", Hex.encodeHexString(dst));
                // set state to indicate we're waiting for C2
                rtmp.setState(RTMP.STATE_HANDSHAKE);
                IoBuffer s1 = handshake.decodeClientRequest1(IoBuffer.wrap(dst));
                if (s1 != null) {
                    //log.trace("S1 byte order: {}", s1.order());
                    conn.writeRaw(s1);
                } else {
                    log.warn("Client was rejected due to invalid handshake");
                    conn.close();
                }
            }
            break;
        case RTMP.STATE_HANDSHAKE:
            // we're expecting C2 here
            //log.trace("C2 byte order: {}", message.order());
            log.debug("decodeHandshakeC2 - buffer: {}", message);
            // no connection type byte is supposed to be in C2 data
            if (message.remaining() >= Constants.HANDSHAKE_SIZE) {
                // get the handshake
                handshake = (InboundHandshake) session.getAttribute(RTMPConnection.RTMP_HANDSHAKE);
                // create array for decode
                byte[] dst = new byte[Constants.HANDSHAKE_SIZE];
                // copy
                message.get(dst);
                log.trace("Copied {}", Hex.encodeHexString(dst));
                //if (log.isTraceEnabled()) {
                //    log.trace("C2 - buffer: {}", Hex.encodeHexString(dst));
                //}
                if (handshake.decodeClientRequest2(IoBuffer.wrap(dst))) {
                    log.debug("Connected, removing handshake data and adding rtmp protocol filter");
                    // set state to indicate we're connected
                    rtmp.setState(RTMP.STATE_CONNECTED);
                    // remove handshake from session now that we are connected
                    session.removeAttribute(RTMPConnection.RTMP_HANDSHAKE);
                } else {
                    log.warn("Client was rejected due to invalid handshake");
                    conn.close();
                }
            }
            // let the logic flow into connected to catch the remaining bytes that probably contain
            // the connect call
        case RTMP.STATE_CONNECTED:
            // decode the objects and pass to received; messages should all be Packet type
            for (Object obj : conn.decode(message)) {
                conn.handleMessageReceived(obj);
            }
            break;
        case RTMP.STATE_ERROR:
        case RTMP.STATE_DISCONNECTING:
        case RTMP.STATE_DISCONNECTED:
            // do nothing, really
            log.debug("Nothing to do, connection state: {}", RTMP.states[connectionState]);
            break;
        default:
            throw new IllegalStateException("Invalid RTMP state: " + connectionState);
        }
        conn.dataReceived();
        conn.updateReadBytes(length);
        message.clear();
        message.free();
        // return pending messages
        returnPendingMessages(conn, resp);
    } else {
        handleBadRequest(String.format("Send: unknown client session: %s", requestInfo.get().getSessionId()),
                resp);
    }
}

From source file:org.apache.openaz.xacml.rest.XACMLPdpServlet.java

/**
 * PUT - The PAP engine sends configuration information using HTTP PUT request. One parameter is expected:
 * config=[policy|pip|all] policy - Expect a properties file that contains updated lists of the root and
 * referenced policies that the PDP should be using for PEP requests. Specifically should AT LEAST contain
 * the following properties: xacml.rootPolicies xacml.referencedPolicies In addition, any relevant
 * information needed by the PDP to load or retrieve the policies to store in its cache. EXAMPLE:
 * xacml.rootPolicies=PolicyA.1, PolicyB.1
 * PolicyA.1.url=http://localhost:9090/PAP?id=b2d7b86d-d8f1-4adf-ba9d-b68b2a90bee1&version=1
 * PolicyB.1.url=http://localhost:9090/PAP/id=be962404-27f6-41d8-9521-5acb7f0238be&version=1
 * xacml.referencedPolicies=RefPolicyC.1, RefPolicyD.1
 * RefPolicyC.1.url=http://localhost:9090/PAP?id=foobar&version=1
 * RefPolicyD.1.url=http://localhost:9090/PAP/id=example&version=1 pip - Expect a properties file that
 * contain PIP engine configuration properties. Specifically should AT LEAST the following property:
 * xacml.pip.engines In addition, any relevant information needed by the PDP to load and configure the
 * PIPs. EXAMPLE: xacml.pip.engines=foo,bar foo.classname=com.foo foo.sample=abc foo.example=xyz ......
 * bar.classname=com.bar ...... all - Expect ALL new configuration properties for the PDP
 *
 * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
 *//*  w w w  .  j  a v  a  2s .c o m*/
@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //
    // Dump our request out
    //
    if (logger.isDebugEnabled()) {
        XACMLRest.dumpRequest(request);
    }
    //
    // What is being PUT?
    //
    String cache = request.getParameter("cache");
    //
    // Should be a list of policy and pip configurations in Java properties format
    //
    if (cache != null && request.getContentType().equals("text/x-java-properties")) {
        if (request.getContentLength() > Integer
                .parseInt(XACMLProperties.getProperty("MAX_CONTENT_LENGTH", "32767"))) {
            String message = "Content-Length larger than server will accept.";
            logger.info(message);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
            return;
        }
        this.doPutConfig(cache, request, response);
    } else {
        String message = "Invalid cache: '" + cache + "' or content-type: '" + request.getContentType() + "'";
        logger.error(message);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
        return;
    }
}

From source file:com.orange.api.atmosdav.AtmosDavServlet.java

/**
 * MKCOL Method.//w ww.ja  va2  s .c o m
 */
protected void doMkcol(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    AtmosApi api = getAPIFromAuthent(req, resp);

    if (req.getContentLength() > 0) {
        resp.sendError(resp.SC_UNSUPPORTED_MEDIA_TYPE);
        return;
    }

    String path = getPathFromReq(req);
    if (!path.endsWith("/"))
        path += "/";

    MetadataList metadata = getObjectMetadata(api.api, getAtmosPath(path, api));

    if (metadata != null) {
        // it already exists
        //resp.addHeader("Allow", methodsAllowed.toString()); ****
        resp.sendError(SC_METHOD_NOT_ALLOWED);
    }
    Object object = null;

    try {
        // does not exist so we create it
        api.api.createObjectOnPath(getAtmosPath(path, api), null, null, null, null);
        resp.setStatus(resp.SC_CREATED);
    } catch (EsuException e) {
        resp.sendError(e.getHttpCode(), e.getMessage());
    }
}

From source file:com.google.appinventor.server.GalleryServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) {
    setDefaultHeader(resp);//www  .  j  a  v a 2s  .c  o m
    UploadResponse uploadResponse;

    String uri = req.getRequestURI();
    // First, call split with no limit parameter.
    String[] uriComponents = uri.split("/");

    if (true) {
        String requestType = uriComponents[REQUEST_TYPE_INDEX];
        LOG.info("######### GOT IN URI");
        LOG.info(requestType);

        long project_Id = -1;
        String user_Id = "-1";
        if (requestType.equalsIgnoreCase("apps")) {
            project_Id = Long.parseLong(uriComponents[GALLERY_OR_USER_ID_INDEX]);
        } else if (requestType.equalsIgnoreCase("user")) {
            //the code below doesn't check if user_Id is the id of current user
            //user_Id = uriComponents[GALLERY_OR_USER_ID_INDEX];
            user_Id = userInfoProvider.getUserId();
        }
        InputStream uploadedStream;
        try {
            if (req.getContentLength() < MAX_IMAGE_FILE_SIZE) {
                uploadedStream = getRequestStream(req, ServerLayout.UPLOAD_FILE_FORM_ELEMENT);

                // Converts the input stream to byte array
                byte[] buffer = new byte[8000];
                int bytesRead = 0;
                ByteArrayOutputStream bao = new ByteArrayOutputStream();
                while ((bytesRead = uploadedStream.read(buffer)) != -1) {
                    bao.write(buffer, 0, bytesRead);
                }
                // Set up the cloud file (options)
                String key = "";
                GallerySettings settings = galleryService.loadGallerySettings();
                if (requestType.equalsIgnoreCase("apps")) {
                    key = settings.getProjectImageKey(project_Id);
                } else if (requestType.equalsIgnoreCase("user")) {
                    key = settings.getUserImageKey(user_Id);
                }

                // setup cloud
                GcsService gcsService = GcsServiceFactory.createGcsService();
                GcsFilename filename = new GcsFilename(settings.getBucket(), key);
                GcsFileOptions options = new GcsFileOptions.Builder().mimeType("image/jpeg").acl("public-read")
                        .cacheControl("no-cache").build();
                GcsOutputChannel writeChannel = gcsService.createOrReplace(filename, options);
                writeChannel.write(ByteBuffer.wrap(bao.toByteArray()));

                // Now finalize
                writeChannel.close();

                uploadResponse = new UploadResponse(UploadResponse.Status.SUCCESS);
            } else {
                /*file exceeds size of MAX_IMAGE_FILE_SIZE*/
                uploadResponse = new UploadResponse(UploadResponse.Status.FILE_TOO_LARGE);
            }

            // Now, get the PrintWriter for the servlet response and print the UploadResponse.
            // On the client side, in the onSubmitComplete method in ode/client/utils/Uploader.java, the
            // UploadResponse value will be retrieved as a String via the
            // FormSubmitCompleteEvent.getResults() method.
            PrintWriter out = resp.getWriter();
            out.print(uploadResponse.formatAsHtml());

        } catch (Exception e) {
            throw CrashReport.createAndLogError(LOG, req, null, e);
        }
        // Set http response information
        resp.setStatus(HttpServletResponse.SC_OK);
    }

    // Now, get the PrintWriter for the servlet response and print the UploadResponse.
    // On the client side, in the onSubmitComplete method in ode/client/utils/Uploader.java, the
    // UploadResponse value will be retrieved as a String via the
    // FormSubmitCompleteEvent.getResults() method.
    //    PrintWriter out = resp.getWriter();
    //    out.print(uploadResponse.formatAsHtml());

    // Set http response information
    resp.setStatus(HttpServletResponse.SC_OK);
}

From source file:org.sakaiproject.portal.util.ErrorReporter.java

@SuppressWarnings("rawtypes")
private String requestDisplay(HttpServletRequest request) {
    ResourceBundle rb = rbDefault;
    StringBuilder sb = new StringBuilder();
    try {//from  ww w .  j a v a 2 s  .com
        sb.append(rb.getString("bugreport.request")).append("\n");
        sb.append(rb.getString("bugreport.request.authtype")).append(request.getAuthType()).append("\n");
        sb.append(rb.getString("bugreport.request.charencoding")).append(request.getCharacterEncoding())
                .append("\n");
        sb.append(rb.getString("bugreport.request.contentlength")).append(request.getContentLength())
                .append("\n");
        sb.append(rb.getString("bugreport.request.contenttype")).append(request.getContentType()).append("\n");
        sb.append(rb.getString("bugreport.request.contextpath")).append(request.getContextPath()).append("\n");
        sb.append(rb.getString("bugreport.request.localaddr")).append(request.getLocalAddr()).append("\n");
        sb.append(rb.getString("bugreport.request.localname")).append(request.getLocalName()).append("\n");
        sb.append(rb.getString("bugreport.request.localport")).append(request.getLocalPort()).append("\n");
        sb.append(rb.getString("bugreport.request.method")).append(request.getMethod()).append("\n");
        sb.append(rb.getString("bugreport.request.pathinfo")).append(request.getPathInfo()).append("\n");
        sb.append(rb.getString("bugreport.request.protocol")).append(request.getProtocol()).append("\n");
        sb.append(rb.getString("bugreport.request.querystring")).append(request.getQueryString()).append("\n");
        sb.append(rb.getString("bugreport.request.remoteaddr")).append(request.getRemoteAddr()).append("\n");
        sb.append(rb.getString("bugreport.request.remotehost")).append(request.getRemoteHost()).append("\n");
        sb.append(rb.getString("bugreport.request.remoteport")).append(request.getRemotePort()).append("\n");
        sb.append(rb.getString("bugreport.request.requesturl")).append(request.getRequestURL()).append("\n");
        sb.append(rb.getString("bugreport.request.scheme")).append(request.getScheme()).append("\n");
        sb.append(rb.getString("bugreport.request.servername")).append(request.getServerName()).append("\n");
        sb.append(rb.getString("bugreport.request.headers")).append("\n");
        for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
            String headerName = (String) e.nextElement();
            boolean censor = (censoredHeaders.get(headerName) != null);
            for (Enumeration he = request.getHeaders(headerName); he.hasMoreElements();) {
                String headerValue = (String) he.nextElement();
                sb.append(rb.getString("bugreport.request.header")).append(headerName).append(":")
                        .append(censor ? "---censored---" : headerValue).append("\n");
            }
        }
        sb.append(rb.getString("bugreport.request.parameters")).append("\n");
        for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {

            String parameterName = (String) e.nextElement();
            boolean censor = (censoredParameters.get(parameterName) != null);
            String[] paramvalues = request.getParameterValues(parameterName);
            for (int i = 0; i < paramvalues.length; i++) {
                sb.append(rb.getString("bugreport.request.parameter")).append(parameterName).append(":")
                        .append(i).append(":").append(censor ? "----censored----" : paramvalues[i])
                        .append("\n");
            }
        }
        sb.append(rb.getString("bugreport.request.attributes")).append("\n");
        for (Enumeration e = request.getAttributeNames(); e.hasMoreElements();) {
            String attributeName = (String) e.nextElement();
            Object attribute = request.getAttribute(attributeName);
            boolean censor = (censoredAttributes.get(attributeName) != null);
            sb.append(rb.getString("bugreport.request.attribute")).append(attributeName).append(":")
                    .append(censor ? "----censored----" : attribute).append("\n");
        }
        HttpSession session = request.getSession(false);
        if (session != null) {
            DateFormat serverLocaleDateFormat = DateFormat.getDateInstance(DateFormat.FULL,
                    Locale.getDefault());
            sb.append(rb.getString("bugreport.session")).append("\n");
            sb.append(rb.getString("bugreport.session.creation")).append(session.getCreationTime())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.lastaccess")).append(session.getLastAccessedTime())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.creationdatetime"))
                    .append(serverLocaleDateFormat.format(session.getCreationTime())).append("\n");
            sb.append(rb.getString("bugreport.session.lastaccessdatetime"))
                    .append(serverLocaleDateFormat.format(session.getLastAccessedTime())).append("\n");
            sb.append(rb.getString("bugreport.session.maxinactive")).append(session.getMaxInactiveInterval())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.attributes")).append("\n");
            for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) {
                String attributeName = (String) e.nextElement();
                Object attribute = session.getAttribute(attributeName);
                boolean censor = (censoredAttributes.get(attributeName) != null);
                sb.append(rb.getString("bugreport.session.attribute")).append(attributeName).append(":")
                        .append(censor ? "----censored----" : attribute).append("\n");
            }

        }
    } catch (Exception ex) {
        M_log.error("Failed to generate request display", ex);
        sb.append("Error " + ex.getMessage());
    }

    return sb.toString();
}