Example usage for javax.servlet ServletInputStream read

List of usage examples for javax.servlet ServletInputStream read

Introduction

In this page you can find the example usage for javax.servlet ServletInputStream read.

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads some number of bytes from the input stream and stores them into the buffer array b.

Usage

From source file:com.releasequeue.jenkins.action.ReleaseQueueWebHookAction.java

public void doIndex(StaplerRequest req, StaplerResponse resp) throws Exception {
    List<Ancestor> ancestors = req.getAncestors();
    AbstractProject project = (AbstractProject) ancestors.get(ancestors.size() - 2).getObject();

    byte[] data = new byte[req.getContentLength()];
    ServletInputStream inputStream = req.getInputStream();
    inputStream.read(data);
    JSONParser parser = new JSONParser();
    JSONObject jsonObj = JSONObject.fromObject(parser.parse(new String(data)));

    List<ParameterValue> values = new ArrayList<ParameterValue>();
    ParametersDefinitionProperty property = (ParametersDefinitionProperty) project
            .getProperty(ParametersDefinitionProperty.class);

    if (property != null) {
        for (ParameterDefinition parameterDefinition : property.getParameterDefinitions()) {
            String parameterName = parameterDefinition.getName();
            ParameterValue parameterValue = null;

            if (jsonObj.containsKey(parameterName)) {
                String strValue = jsonObj.get(parameterName).toString();
                if (parameterDefinition.getClass() == StringParameterDefinition.class) {
                    parameterValue = ((StringParameterDefinition) parameterDefinition).createValue(strValue);
                } else if (parameterDefinition.getClass() == TextParameterDefinition.class) {
                    parameterValue = ((TextParameterDefinition) parameterDefinition).createValue(strValue);
                } else if (parameterDefinition.getClass() == ChoiceParameterDefinition.class) {
                    if (((ChoiceParameterDefinition) parameterDefinition).getChoices().contains(strValue)) {
                        parameterValue = ((ChoiceParameterDefinition) parameterDefinition)
                                .createValue(strValue);
                    }//w w w .j a v  a  2s .  c  o m
                }
            }
            if (parameterValue == null) {
                parameterValue = parameterDefinition.getDefaultParameterValue();
            }

            values.add(parameterValue);
        }
    }

    Jenkins.getInstance().getQueue().schedule(project, 0, new ParametersAction(values),
            new CauseAction(new ReleaseQueueBuildCause()));
}

From source file:test.integ.be.fedict.performance.servlet.OcspServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String caName = request.getParameter(CA_QUERY_PARAM);
    if (null == caName) {
        throw new ServletException("No CA name found.");
    }//w w w . ja  va2  s  . c  o  m

    CAConfiguration ca = TestPKI.get().findCa(caName);
    if (null == ca) {
        throw new ServletException("CA Config not found for " + caName);
    }

    try {

        if (null == request.getContentType() || !request.getContentType().equals("application/ocsp-request")) {
            LOG.error("Wrong content type: " + request.getContentType());
            return;
        }

        int len = request.getContentLength();
        byte[] ocspRequestData = new byte[len];
        ServletInputStream reader = request.getInputStream();
        int result = reader.read(ocspRequestData);
        if (-1 == result) {
            LOG.error("No data found ?!");
            return;
        }

        BigInteger maxRevokedSN = new BigInteger(Long.toString(ca.getCrlRecords()));

        OCSPReq ocspRequest = new OCSPReq(ocspRequestData);

        BasicOCSPRespGenerator ocspRespGen = new BasicOCSPRespGenerator(ca.getKeyPair().getPublic());
        for (Req req : ocspRequest.getRequestList()) {

            LOG.debug("OCSP request for CA=" + caName + " sn=" + req.getCertID().getSerialNumber());

            if (-1 == req.getCertID().getSerialNumber().compareTo(maxRevokedSN)) {
                LOG.debug("revoked");
                ocspRespGen.addResponse(req.getCertID(),
                        new RevokedStatus(new RevokedInfo(new ASN1GeneralizedTime(new Date()), null)));
            } else {
                ocspRespGen.addResponse(req.getCertID(), CertificateStatus.GOOD);
            }
        }

        BasicOCSPResp ocspResp;
        ocspResp = ocspRespGen.generate("SHA1WITHRSA", ca.getKeyPair().getPrivate(), null, new Date(), "BC");

        OCSPRespGenerator og = new OCSPRespGenerator();

        response.setContentType("application/ocsp-response");
        response.getOutputStream().write((og.generate(OCSPRespGenerator.SUCCESSFUL, ocspResp)).getEncoded());

    } catch (Exception e) {
        LOG.error("Exception: " + e.getMessage(), e);
        throw new ServletException(e);
    }
}

From source file:it.vige.greenarea.sgrl.servlet.CommonsFileUploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/plain");
    out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
    out.println();/*w w w  .j ava  2s  . c  om*/
    int fileSize = request.getContentLength();
    byte[] buf = new byte[fileSize];
    try {
        ServletInputStream is = request.getInputStream();
        is.read(buf);
        File file = new File(destinationDir, "LogisticNetwork.mxe");
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(buf);
        fos.close();
        out.close();
    } catch (Exception ex) {
        log("Error encountered while uploading file", ex);
    }

}

From source file:be.solidx.hot.utils.IOUtils.java

public static Promise<byte[], Exception, Void> asyncRead(final HttpServletRequest req,
        final ExecutorService executorService, final ExecutorService promiseResolver) {

    final DeferredObject<byte[], Exception, Void> deferredObject = new DeferredObject<>();

    try {/*  w w w.j a  va 2 s . c o m*/
        final ServletInputStream servletInputStream = req.getInputStream();

        servletInputStream.setReadListener(new ReadListener() {

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            @Override
            public void onError(final Throwable t) {
                promiseResolver.execute(new Runnable() {
                    @Override
                    public void run() {
                        deferredObject.reject(new Exception(t));
                    }
                });
            }

            @Override
            public void onDataAvailable() throws IOException {
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        byte b[] = new byte[2048];
                        int len = 0;

                        try {
                            while (servletInputStream.isReady() && (len = servletInputStream.read(b)) != -1) {
                                baos.write(b, 0, len);
                            }
                        } catch (IOException e) {
                            LOGGER.error("", e);
                        }
                    }
                });
            }

            @Override
            public void onAllDataRead() throws IOException {
                promiseResolver.execute(new Runnable() {
                    @Override
                    public void run() {
                        deferredObject.resolve(baos.toByteArray());
                    }
                });
            }
        });
    } catch (final IOException e2) {
        promiseResolver.execute(new Runnable() {
            @Override
            public void run() {
                deferredObject.reject(new Exception(e2));
            }
        });

    } catch (final IllegalStateException exception) {
        promiseResolver.execute(new Runnable() {
            @Override
            public void run() {
                deferredObject.resolve("".getBytes());
            }
        });
    }

    //      executorService.execute(new Runnable() {
    //         @Override
    //         public void run() {
    //            final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    //            try {
    //               IOUtils.toOutputStreamBuffered(req.getInputStream(), outputStream);
    //               promiseResolver.execute(new Runnable() {
    //                  @Override
    //                  public void run() {
    //                     deferredObject.resolve(outputStream.toByteArray());
    //                  }
    //               });
    //            } catch (final IOException e) {
    //               promiseResolver.execute(new Runnable() {
    //                  @Override
    //                  public void run() {
    //                     deferredObject.reject(e);
    //                  }
    //               });
    //            }
    //         }
    //      });

    return deferredObject.promise();
}

From source file:org.egov.restapi.filter.ApiFilter.java

@Override
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
        final FilterChain filterChain) throws IOException, ServletException {
    final MultiReadHttpServletRequest multiReadRequest = new MultiReadHttpServletRequest(
            (HttpServletRequest) servletRequest);
    if (!validateRequest(multiReadRequest))
        throw new ApplicationRuntimeException("RESTAPI.001");
    String ulbCode = null;//from ww w .j  a  va 2  s  . c o  m
    final byte[] b = new byte[5000];
    ulbCode = servletRequest.getParameter("ulbCode");
    if (ulbCode == null) {
        JSONObject jsonObject = null;
        String jb = new String();
        try {
            final ServletInputStream inputStream = multiReadRequest.getInputStream();
            inputStream.read(b);
            jb = new String(b);
        } catch (final Exception e) {
            // Throw error
        }

        try {
            jsonObject = JSONObject.fromObject(jb.toString());
        } catch (final Exception e) {
            throw new RuntimeException("Invalid Json");
        }

        if (jsonObject != null)
            ulbCode = jsonObject.getString("ulbCode");
        else
            throw new RuntimeException("Invalid Json ULB Code is not Passed");

    }

    if (StringUtils.isNotBlank(ulbCode)) {
        if (!ulbCode.equals(ApplicationThreadLocals.getCityCode())) {
            LOG.info("Request Reached Different city. Need to change domain details");
            final String cityName = RestRedirectConstants.getCode_ulbNames().get(ulbCode).toLowerCase();
            ApplicationThreadLocals.setTenantID(cityName);
            final City city = cityService.getCityByCode(ulbCode);
            ApplicationThreadLocals.setDomainName(city.getDomainURL());
            ApplicationThreadLocals.setCityCode(ulbCode);
        } else
            LOG.info("ULB code resolved to be same, continueing normal request flow");
    } else {
        LOG.error("ULB Code missing in request");
        throw new ApplicationRuntimeException("ULB Code missing in request");
    }
    filterChain.doFilter(multiReadRequest, servletResponse);

}

From source file:org.zalando.logbook.servlet.example.ExampleController.java

@RequestMapping(value = "/read-bytes", produces = MediaType.TEXT_PLAIN_VALUE)
public void readBytes(final HttpServletRequest request, final HttpServletResponse response) throws IOException {

    final ServletInputStream input = request.getInputStream();
    final ServletOutputStream output = response.getOutputStream();

    final byte[] buffer = new byte[1];

    while (true) {
        final int read = input.read(buffer);
        if (read == -1) {
            break;
        }//w w w . j  a v a  2s .c o  m
        output.write(buffer);
    }
}

From source file:jmu.edu.cn.util.JsonMapper.java

public <T> T fromJson(HttpServletRequest request, Class<T> pojoClass) throws IOException {
    ServletInputStream inputStream = request.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buf = new byte[1024];
    int index = inputStream.read(buf);
    while (index > 0) {
        baos.write(buf, 0, index);// ww w . j  a  va  2 s.  com
        index = inputStream.read(buf);
    }
    return mapper.readValue(baos.toByteArray(), pojoClass);
}

From source file:org.apache.shindig.gadgets.servlet.HtmlAccelServletTest.java

private void expectPostRequest(String extraPath, String url, final String data) throws IOException {
    expect(request.getMethod()).andReturn("POST").anyTimes();
    expect(request.getServletPath()).andReturn(SERVLET).anyTimes();
    expect(request.getScheme()).andReturn("http").anyTimes();
    expect(request.getServerName()).andReturn("apache.org").anyTimes();
    expect(request.getServerPort()).andReturn(-1).anyTimes();
    expect(request.getRequestURI()).andReturn(SERVLET + extraPath).anyTimes();
    expect(request.getRequestURL()).andReturn(new StringBuffer("apache.org" + SERVLET + extraPath)).anyTimes();
    String queryParams = (url == null ? "" : "url=" + url + "&container=accel" + "&gadget=test");
    expect(request.getQueryString()).andReturn(queryParams).anyTimes();

    ServletInputStream inputStream = mock(ServletInputStream.class);
    expect(request.getInputStream()).andReturn(inputStream);
    expect(inputStream.read((byte[]) EasyMock.anyObject())).andAnswer(new IAnswer<Integer>() {
        public Integer answer() throws Throwable {
            byte[] byteArray = (byte[]) EasyMock.getCurrentArguments()[0];
            System.arraycopy(data.getBytes(), 0, byteArray, 0, data.length());
            return data.length();
        }/*ww  w.  j  ava2 s. co m*/
    });
    expect(inputStream.read((byte[]) EasyMock.anyObject())).andReturn(-1);
    Vector<String> headerNames = new Vector<String>();
    expect(request.getHeaderNames()).andReturn(headerNames.elements());
}

From source file:com.orinus.script.safe.jetty.SRequest.java

public byte[] getRequestData() {
    byte[] tag = new byte[0];
    try {//from  w  w  w.  j  a  v  a 2s . c  om
        ServletInputStream sis = req.getInputStream();
        tag = new byte[sis.available()];
        sis.read(tag);
    } catch (Exception e) {
    }
    return tag;
}

From source file:org.springframework.reactive.web.servlet.RequestBodyPublisher.java

@Override
public void onDataAvailable() throws IOException {
    ServletInputStream input = this.synchronizer.getInputStream();

    while (true) {
        logger.debug("Demand: " + this.demand);

        if (!demand.hasDemand()) {
            break;
        }/*from   www.ja v a2  s  .  com*/

        boolean ready = input.isReady();
        logger.debug("Input " + ready + "/" + input.isFinished());

        if (!ready) {
            break;
        }

        int read = input.read(buffer);
        logger.debug("Input read:" + read);

        if (read == -1) {
            break;
        } else if (read > 0) {
            this.demand.decrement();
            byte[] copy = Arrays.copyOf(this.buffer, read);

            //            logger.debug("Next: " + new String(copy, UTF_8));

            this.subscriber.onNext(copy);

        }
    }
}