Example usage for javax.servlet.http HttpServletRequest getInputStream

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

Introduction

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

Prototype

public ServletInputStream getInputStream() throws IOException;

Source Link

Document

Retrieves the body of the request as binary data using a ServletInputStream .

Usage

From source file:com.googlesource.gerrit.plugins.lfs.fs.LfsFsContentServlet.java

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
    AnyLongObjectId id = getObjectToTransfer(req, rsp);
    if (id == null) {
        return;//from w  ww  .  j a v  a2s  .c  o m
    }

    if (!authorizer.verifyAuthInfo(req.getHeader(HDR_AUTHORIZATION), UPLOAD, id)) {
        sendError(rsp, HttpStatus.SC_UNAUTHORIZED,
                MessageFormat.format(LfsServerText.get().failedToCalcSignature, "Invalid authorization token"));
        return;
    }

    AsyncContext context = req.startAsync();
    context.setTimeout(timeout);
    req.getInputStream().setReadListener(new ObjectUploadListener(repository, context, req, rsp, id));
}

From source file:com.twinsoft.convertigo.engine.admin.services.database_objects.Set.java

protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
    Element root = document.getDocumentElement();
    Document post = null;/*from   w  w w . j  a  v a  2  s .com*/
    Element response = document.createElement("response");

    try {
        Map<String, DatabaseObject> map = com.twinsoft.convertigo.engine.admin.services.projects.Get
                .getDatabaseObjectByQName(request);

        xpath = new TwsCachedXPathAPI();
        post = XMLUtils.parseDOM(request.getInputStream());
        postElt = document.importNode(post.getFirstChild(), true);

        String objectQName = xpath.selectSingleNode(postElt, "./@qname").getNodeValue();
        DatabaseObject object = map.get(objectQName);

        //         String comment = getPropertyValue(object, "comment").toString();
        //         object.setComment(comment);

        if (object instanceof Project) {
            Project project = (Project) object;

            String objectNewName = getPropertyValue(object, "name").toString();

            Engine.theApp.databaseObjectsManager.renameProject(project, objectNewName);

            map.remove(objectQName);
            map.put(project.getQName(), project);
        }

        BeanInfo bi = CachedIntrospector.getBeanInfo(object.getClass());

        PropertyDescriptor[] propertyDescriptors = bi.getPropertyDescriptors();

        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            String propertyName = propertyDescriptor.getName();

            Method setter = propertyDescriptor.getWriteMethod();

            Class<?> propertyTypeClass = propertyDescriptor.getReadMethod().getReturnType();
            if (propertyTypeClass.isPrimitive()) {
                propertyTypeClass = ClassUtils.primitiveToWrapper(propertyTypeClass);
            }

            try {
                String propertyValue = getPropertyValue(object, propertyName).toString();

                Object oPropertyValue = createObject(propertyTypeClass, propertyValue);

                if (object.isCipheredProperty(propertyName)) {

                    Method getter = propertyDescriptor.getReadMethod();
                    String initialValue = (String) getter.invoke(object, (Object[]) null);

                    if (oPropertyValue.equals(initialValue)
                            || DatabaseObject.encryptPropertyValue(initialValue).equals(oPropertyValue)) {
                        oPropertyValue = initialValue;
                    } else {
                        object.hasChanged = true;
                    }
                }

                if (oPropertyValue != null) {
                    Object args[] = { oPropertyValue };
                    setter.invoke(object, args);
                }

            } catch (IllegalArgumentException e) {
            }
        }

        Engine.theApp.databaseObjectsManager.exportProject(object.getProject());
        response.setAttribute("state", "success");
        response.setAttribute("message", "Project have been successfully updated!");
    } catch (Exception e) {
        Engine.logAdmin.error("Error during saving the properties!\n" + e.getMessage());
        response.setAttribute("state", "error");
        response.setAttribute("message", "Error during saving the properties!");
        Element stackTrace = document.createElement("stackTrace");
        stackTrace.setTextContent(e.getMessage());
        root.appendChild(stackTrace);
    } finally {
        xpath.resetCache();
    }

    root.appendChild(response);
}

From source file:com.kolich.curacao.mappers.request.types.body.MemoryBufferingRequestBodyMapper.java

@Override
public final T resolve(@Nullable final Annotation annotation, @Nonnull final CuracaoContext ctx)
        throws Exception {
    // This mapper, and all of its children, only handles parameters
    // annotated with request body. If it's anything else, immediately
    // return null.
    if (!(annotation instanceof RequestBody)) {
        return null;
    }/*from   w w w  . j  a  v  a  2  s.  c o  m*/
    final RequestBody rb = (RequestBody) annotation;
    // If this request context already has a copy of the request body
    // in memory, then we should not attempt to "re-buffer" it.  We can
    // use what's already been fetched over the wire from the client.
    byte[] body = ctx.getBody();
    if (body == null) {
        // No pre-buffered body was attached to the request context.  We
        // should attempt to buffer one.
        final HttpServletRequest request = ctx.request_;
        final long maxLength = (rb.maxSizeInBytes() > 0L) ?
        // If the RequestBody annotation specified a maximum body
        // size in bytes, then we should honor that here.
                rb.maxSizeInBytes() :
                // Otherwise, default to what's been globally configured in
                // the app configuration.
                DEFAULT_MAX_REQUEST_BODY_SIZE_BYTES;
        // Sigh, blocking I/O (for now).
        try (final InputStream is = request.getInputStream()) {
            long contentLength = request.getContentLength();
            if (contentLength != -1L) {
                // Content-Length was specified, check to make sure it's not
                // larger than the maximum request body size supported.
                if (maxLength > 0 && contentLength > maxLength) {
                    throw new RequestTooLargeException(
                            "Incoming request " + "body was too large to buffer into memory: " + contentLength
                                    + "-bytes > " + maxLength + "-bytes maximum.");
                }
            } else {
                // Content-Length was not specified on the request.
                contentLength = (maxLength <= 0) ?
                // Default to copy as much as data as we can if the
                // config does not place a limit on the maximum size
                // of the request body to buffer in memory.
                        Long.MAX_VALUE :
                        // No Content-Length was specified.  Default the max
                        // number of bytes to the max request body size.
                        maxLength;
            }
            // Note we're using a limited input stream that intentionally
            // limits the number of bytes read by reading N-bytes, then
            // stops.  This prevents us from filling up too many buffers
            // which could lead to bringing down the JVM with too many
            // requests and not enough memory.
            body = toByteArray(limit(is, contentLength));
            // Cache the freshly buffered body byte[] array to the request
            // context for other mappers to pick up if needed.
            ctx.setBody(body);
        }
    }
    return resolveWithBody(rb, ctx, body);
}

From source file:org.createnet.raptor.auth.service.jwt.JsonUsernamePasswordFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException {

    if (!request.getMethod().equals("POST")) {
        throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
    }/* ww w .ja v a2 s . c  o m*/

    if (!request.getContentType().equals(MediaType.APPLICATION_JSON)) {
        throw new AuthenticationServiceException("Only Content-Type " + MediaType.APPLICATION_JSON
                + " is supported. Provided is " + request.getContentType());
    }

    LoginForm loginForm;
    try {
        InputStream body = request.getInputStream();
        loginForm = jacksonObjectMapper.readValue(body, LoginForm.class);
    } catch (IOException ex) {
        throw new AuthenticationServiceException("Error reading body", ex);
    }

    if (loginForm.username == null) {
        loginForm.username = "";
    }

    if (loginForm.password == null) {
        loginForm.password = "";
    }

    loginForm.username = loginForm.username.trim();

    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
            loginForm.username, loginForm.password);
    setDetails(request, authRequest);

    return this.getAuthenticationManager().authenticate(authRequest);
}

From source file:eionet.gdem.utils.FileUpload.java

/**
 * Uploads file from client to the server. Parses HttpRequestInputstream and writes bytes to the specified folder in the same
 * computer, where servlet runs//  w w w .  ja v  a  2  s .  c o  m
 *
 * @param req request
 * @throws GDEMException If an error occurs.
 */
public File uploadFile(HttpServletRequest req) throws GDEMException {

    // helper arrays
    byte[] bt1 = new byte[4096];
    byte[] bt2 = new byte[4096];

    int[] int1 = new int[1];
    int[] int2 = new int[1];
    ServletInputStream si = null;

    try {
        si = req.getInputStream();
        String contentType = req.getContentType();
        String charEncoding = req.getCharacterEncoding();
        // +RV020508
        int contentLength = req.getContentLength();
        lenRcvd = 0;
        if (contentLength == -1) {
            throw new GDEMException("Invalid HTTP POST. Content length is unknown.");
        }
        //
        int boundaryPos;
        if ((boundaryPos = contentType.indexOf("boundary=")) != -1) {
            contentType = contentType.substring(boundaryPos + 9);
            contentType = "--" + contentType;
        } // end if

        // Find filename
        String fileName;
        while ((fileName = readLine(bt1, int1, si, charEncoding)) != null) {
            int i = fileName.indexOf("filename=");
            if (i >= 0) {
                fileName = fileName.substring(i + 10);
                i = fileName.indexOf("\"");
                if (i > 0) {
                    FileOutputStream fileOut = null;
                    boolean fWrite = false;
                    File tmpFile = new File(_folderName, getSessionId());
                    try {

                        fileName = fileName.substring(0, i);

                        fileName = getFileName(fileName);

                        // _fileName is returned by getFileName() method
                        _fileName = fileName;

                        String line2 = readLine(bt1, int1, si, charEncoding);
                        if (line2.indexOf("Content-Type") >= 0) {
                            readLine(bt1, int1, si, charEncoding);
                        }

                        fileOut = new FileOutputStream(tmpFile);

                        String helpStr = null;
                        long l = 0L;

                        // changes to true, if something is written to the output file
                        // remains false, if user has entered a wrong filename or the file's size is 0kB

                        // parse the file in the MIME message
                        while ((line2 = readLine(bt1, int1, si, charEncoding)) != null) {
                            if (line2.indexOf(contentType) == 0 && bt1[0] == 45) {
                                break;
                            }
                            if (helpStr != null && l <= 75L) {
                                fWrite = true;
                                fileOut.write(bt2, 0, int2[0]);
                                fileOut.flush();
                            } // endif
                            helpStr = readLine(bt2, int2, si, charEncoding);
                            if (helpStr == null || helpStr.indexOf(contentType) == 0 && bt2[0] == 45) {
                                break;
                            }

                            fWrite = true;
                            fileOut.write(bt1, 0, int1[0]);
                            fileOut.flush();
                        } // end while

                        byte bt0;

                        if (lineSep.length() == 1) {
                            bt0 = 2;
                        } else {
                            bt0 = 1;
                        }

                        if (helpStr != null && bt2[0] != 45 && int2[0] > lineSep.length() * bt0) {
                            fileOut.write(bt2, 0, int2[0] - lineSep.length() * bt0);
                            fWrite = true;
                        }
                        if (line2 != null && bt1[0] != 45 && int1[0] > lineSep.length() * bt0) {
                            fileOut.write(bt1, 0, int1[0] - lineSep.length() * bt0);
                            fWrite = true;
                        }
                    } finally {
                        IOUtils.closeQuietly(fileOut);
                    }
                    if (fWrite) {
                        try {
                            synchronized (fileLock) {
                                File file = new File(_folderName, fileName);
                                int n = 0;
                                while (file.exists()) {
                                    n++;
                                    fileName = genFileName(fileName, n);
                                    file = new File(_folderName, fileName);
                                }
                                setFileName(fileName);
                                try {
                                    file.delete();
                                } catch (Exception _ex) {
                                    throw new GDEMException("Error deleting temporary file: " + _ex.toString());
                                }
                                tmpFile.renameTo(file);
                                return file;
                            } // sync
                        } catch (Exception _ex) {
                            throw new GDEMException("Error renaming temporary file: " + _ex.toString());
                        }

                    } else { // end-if file = 0kb or does not exist
                        tmpFile.delete();
                        throw new GDEMException("File: " + fileName + " does not exist or contains no data.");
                    }

                }
                // break;
            } // end if (filename found)
        } // end while
          // +RV020508
        if (contentLength != lenRcvd) {
            throw new GDEMException(
                    "Canceled upload: expected " + contentLength + " bytes, received " + lenRcvd + " bytes.");
        }
    } catch (IOException e) {
        throw new GDEMException("Error uploading file: " + e.toString());
    } finally {
        IOUtils.closeQuietly(si);
    }

    return null;
}

From source file:com.kurento.kmf.content.internal.ControlProtocolManager.java

/**
 * Receiver method for JSON throw a request.
 * /*  w  ww .j  a va 2 s .co m*/
 * @param asyncCtx
 *            Asynchronous context
 * @return Received JSON encapsulated as a Java class
 */
public JsonRpcRequest receiveJsonRequest(AsyncContext asyncCtx) {
    HttpServletRequest request = (HttpServletRequest) asyncCtx.getRequest();

    // Received character encoding should be UTF-8. In order to check this,
    // the method detectJsonEncoding will be used. Before that, the
    // InputStream read from request.getInputStream() should be cloned
    // (using a ByteArrayOutputStream) to be used on detectJsonEncoding and
    // then for reading the JSON message

    try {
        InputStream inputStream = request.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[BUFF];
        int len;
        while ((len = inputStream.read(buffer)) > -1) {
            baos.write(buffer, 0, len);
        }
        baos.flush();

        String encoding = detectJsonEncoding(new ByteArrayInputStream(baos.toByteArray()));
        log.debug("Detected JSON encoding: " + encoding);
        if (encoding == null) {
            throw new KurentoMediaFrameworkException(
                    "Invalid or unsupported charset encondig in received JSON request", 10018);
        }

        InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(baos.toByteArray()), encoding);

        JsonRpcRequest jsonRequest = gson.fromJson(isr, JsonRpcRequest.class);
        Assert.notNull(jsonRequest.getMethod());
        log.info("Received JsonRpc request ...\n " + jsonRequest.toString());
        return jsonRequest;
    } catch (IOException e) {
        // TODO: trace this exception and double check appropriate JsonRpc
        // answer is sent
        throw new KurentoMediaFrameworkException(
                "IOException reading JsonRPC request. Cause: " + e.getMessage(), e, 20016);
    }
}

From source file:net.community.chest.gitcloud.facade.frontend.git.GitController.java

private CloseableHttpResponse transferPostedData(HttpEntityEnclosingRequestBase postRequest,
        final HttpServletRequest req) throws IOException {
    InputStream postData = req.getInputStream();
    try {/*from ww  w.j  a  v  a  2  s  .c  om*/
        if (logger.isTraceEnabled()) {
            LineLevelAppender appender = new LineLevelAppender() {
                @Override
                @SuppressWarnings("synthetic-access")
                public void writeLineData(CharSequence lineData) throws IOException {
                    logger.trace("transferPostedData(" + req.getMethod() + ")[" + req.getRequestURI() + "]["
                            + req.getQueryString() + "] C: " + lineData);
                }

                @Override
                public boolean isWriteEnabled() {
                    return true;
                }
            };
            postData = new TeeInputStream(postData, new HexDumpOutputStream(appender), true);
        }
        postRequest.setEntity(new InputStreamEntity(postData));
        return client.execute(postRequest);
    } finally {
        postData.close();
    }
}

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

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Match match = (Match) req.getAttribute("match");
    HttpPut method = new HttpPut(match.toURL());
    copyHeaders(req, method);/*w ww . j  a  v a 2s. co  m*/

    method.setEntity(new InputStreamEntity(req.getInputStream(), req.getContentLength()));

    this.execute(match, method, req, resp);
}

From source file:com.thinkberg.moxo.dav.LockHandler.java

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileObject object = getResourceManager().getFileObject(request.getPathInfo());

    try {/* ww w  .  ja  va 2s .  c  o m*/
        Lock lock = LockManager.getInstance().checkCondition(object, getIf(request));
        if (lock != null) {
            sendLockAcquiredResponse(response, lock);
            return;
        }
    } catch (LockException e) {
        // handle locks below
    }

    try {
        SAXReader saxReader = new SAXReader();
        Document lockInfo = saxReader.read(request.getInputStream());
        //log(lockInfo);

        Element rootEl = lockInfo.getRootElement();
        String lockScope = null, lockType = null;
        Object owner = null;
        Iterator elIt = rootEl.elementIterator();
        while (elIt.hasNext()) {
            Element el = (Element) elIt.next();
            if (TAG_LOCKSCOPE.equals(el.getName())) {
                lockScope = el.selectSingleNode("*").getName();
            } else if (TAG_LOCKTYPE.equals(el.getName())) {
                lockType = el.selectSingleNode("*").getName();
            } else if (TAG_OWNER.equals(el.getName())) {
                // TODO correctly handle owner
                Node subEl = el.selectSingleNode("*");
                if (subEl != null && TAG_HREF.equals(subEl.getName())) {
                    owner = new URL(el.selectSingleNode("*").getText());
                } else {
                    owner = el.getText();
                }
            }
        }

        log("LOCK(" + lockType + ", " + lockScope + ", " + owner + ")");

        Lock requestedLock = new Lock(object, lockType, lockScope, owner, getDepth(request),
                getTimeout(request));
        try {
            LockManager.getInstance().acquireLock(requestedLock);
            sendLockAcquiredResponse(response, requestedLock);
        } catch (LockConflictException e) {
            response.sendError(SC_LOCKED);
        } catch (IllegalArgumentException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        }
    } catch (DocumentException e) {
        e.printStackTrace();
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:edu.txstate.dmlab.clusteringwiki.rest.TestController.java

/**
 * Save the details of the last executed step
 * @param executionId the execution id for the current test
 * @param model/*www  .j av a 2s. c  o m*/
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
@RequestMapping("/test/put/{executionId}")
public void saveStep(@PathVariable("executionId") String execId, HttpServletRequest request,
        HttpServletResponse response, Model model) throws Exception {

    String executionId = _cleanExtensions(execId);

    if (!isValidTest(request, executionId)) {
        sendOutput(response, "{\"error\":\"Invalid test execution id.\"}");
        return;
    }

    try {

        String data = null;
        InputStream is = request.getInputStream();

        if (is != null) {
            try {
                StringBuilder sb = new StringBuilder();
                String line;
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                data = sb.toString();
            } finally {
                is.close();
            }

        }

        if (data == null) {
            sendOutput(response, "{\"error\":\"No data received.\"}");
            return;
        }

        final JSONObject info = new JSONObject(data);

        final Integer stepId = info.getInt("stepId");
        final String cluster = info.getJSONObject("cluster").toString();
        final String times = info.getJSONObject("times").toString();
        final JSONObject tagExecutionInfo = info.getJSONObject("tagExecutionInfo");

        int itemCount = 0;
        final Iterator keys = tagExecutionInfo.keys();
        while (keys.hasNext()) {
            final String cnt = (String) keys.next();
            final Integer tagCount = Integer.valueOf(cnt);
            TestStepExecution exec = this.testStepExecutionDao.selectTestStepExecution(executionId, stepId,
                    tagCount);

            if (exec != null) {
                sendOutput(response,
                        "{\"error\":\"This step has already been saved. Please contact an administrator.\"}");
                return;
            }

            final JSONObject itemInfo = tagExecutionInfo.getJSONObject(cnt);

            exec = new TestStepExecution();
            exec.setExecutionId(executionId);
            exec.setTagCount(tagCount);
            exec.setBaseEffort(itemInfo.getDouble("baseEffort"));
            exec.setBaseRelevantEffort(itemInfo.getDouble("baseRelevantEffort"));
            exec.setUserEffort(itemInfo.getDouble("userEffort"));
            exec.setCluster(cluster);
            exec.setTimes(times);
            exec.setStepId(stepId);
            exec.setTags(itemInfo.getJSONObject("tags").toString());

            if (this.isLoggedIn()) {
                exec.setUid(applicationUser.getUserId());
            }

            this.testStepExecutionDao.saveTestStepExecution(exec);
            itemCount++;
        }

        //if no tagged items
        if (itemCount == 0) {
            TestStepExecution exec = this.testStepExecutionDao.selectTestStepExecution(executionId, stepId, 0);

            if (exec != null) {
                sendOutput(response,
                        "{\"error\":\"This step has already been saved. Please contact an administrator.\"}");
                return;
            }

            exec = new TestStepExecution();
            exec.setExecutionId(executionId);
            exec.setTagCount(0);
            exec.setBaseEffort(0.0D);
            exec.setBaseRelevantEffort(0.0D);
            exec.setUserEffort(0.0D);
            exec.setCluster(cluster);
            exec.setTimes(times);
            exec.setStepId(stepId);
            exec.setTags("{}");

            if (this.isLoggedIn()) {
                exec.setUid(applicationUser.getUserId());
            }

            this.testStepExecutionDao.saveTestStepExecution(exec);
        }

        sendOutput(response, "{\"success\":true}");

    } catch (Exception e) {
        sendOutput(response, "{\"error\":" + JSONObject.quote(e.getMessage()) + "}");
        return;
    }

}