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.amalto.core.storage.task.staging.StagingTaskService.java

@POST
@Path("{container}/")
@Consumes(MediaType.APPLICATION_XML)//  ww  w.j  a v  a 2  s.co  m
@ApiOperation(value = "start a new validation on provided container and model and returns the validation task id")
public String startValidation(@ApiParam(value = "Container name") @PathParam("container") String dataContainer,
        @ApiParam(value = "Model name") @QueryParam("model") String dataModel,
        @Context HttpServletRequest request) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Filter filter;
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        String content = IOUtils.toString(request.getInputStream());
        if (!content.isEmpty()) {
            Document doc = builder.parse(new InputSource(new StringReader(content)));
            filter = new ConfigurableFilter(doc);
        } else {
            filter = DefaultFilter.INSTANCE;
        }
    } catch (Exception e) {
        filter = DefaultFilter.INSTANCE;
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Ignored parse error for staging filter: ", e);
        }
    }
    return delegate.startValidation(dataContainer, dataModel, filter);
}

From source file:es.tid.cep.esperanza.Rules.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* w  ww  . jav a  2 s.  c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("application/json;charset=UTF-8");
    try {
        ServletInputStream sis = request.getInputStream();
        byte[] b = new byte[request.getContentLength()];
        sis.read(b, 0, b.length);
        String expression = new String(b);
        logger.debug("rule text: ", expression);
        EPStatement statement = epService.getEPAdministrator().createEPL(expression);
        logger.debug("statement json: " + Utils.Statement2JSONObject(statement));
        statement.addListener(new GenericListener());
        out.println(Utils.Statement2JSONObject(statement));
    } catch (EPException epe) {
        logger.error("creating statement", epe);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.printf("{\"error\":%s}\n", JSONObject.valueToString(epe.getMessage()));
    } finally {
        out.close();
    }
}

From source file:com.linecorp.bot.servlet.LineBotCallbackRequestParser.java

/**
 * Parse request.//  w  w w. j  a  v a  2s . c  o m
 *
 * @param req HTTP servlet request.
 * @return Parsed result. If there's an error, this method sends response.
 * @throws LineBotCallbackException There's an error around signature.
 */
public CallbackRequest handle(HttpServletRequest req) throws LineBotCallbackException, IOException {
    // validate signature
    String signature = req.getHeader("X-Line-Signature");
    if (signature == null || signature.length() == 0) {
        throw new LineBotCallbackException("Missing 'X-Line-Signature' header");
    }

    final byte[] json = ByteStreams.toByteArray(req.getInputStream());
    if (log.isDebugEnabled()) {
        log.debug("got: {}", new String(json, StandardCharsets.UTF_8));
    }

    if (!lineSignatureValidator.validateSignature(json, signature)) {
        throw new LineBotCallbackException("Invalid API signature");
    }

    final CallbackRequest callbackRequest = objectMapper.readValue(json, CallbackRequest.class);
    if (callbackRequest == null || callbackRequest.getEvents() == null) {
        throw new LineBotCallbackException("Invalid content");
    }
    return callbackRequest;
}

From source file:com.github.rabid_fish.proxy.servlet.SoapServlet.java

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

    PrintWriter writer = response.getWriter();
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("text/xml");

    try {//from w w w  . jav  a2 s  .  c o  m
        ServletInputStream stream = request.getInputStream();
        String requestBody = IOUtils.toString(stream);

        Integer mathResult = getMathResult(requestBody);
        writeMathResult(writer, mathResult);
    } catch (Exception e) {
        writeSoapError(writer, e.getMessage());
    }

    writer.flush();
    writer.close();
}

From source file:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java

private InputStream getRequestBody(HttpServletRequest request) {
    InputStream requestEntity = null;
    try {// www  .  jav  a2 s.c  om
        requestEntity = request.getInputStream();
    } catch (IOException ex) {
        // no requestBody is ok.
    }
    return requestEntity;
}

From source file:com.jaspersoft.jasperserver.rest.services.RESTRole.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    try {//from   ww  w .ja  v a 2  s .  c  om

        String searchCriteria = restUtils.extractResourceName(SERVICE_NAME, req.getPathInfo());

        WSRole role = restUtils.unmarshal(WSRole.class, req.getInputStream());

        role = restUtils.populateServiceObject(role);

        updateRole(role, restUtils.getWSRoleSearchCriteria(searchCriteria));

        restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, "");
    } catch (IOException e) {
        throw new ServiceException(e.getLocalizedMessage());
    } catch (JAXBException e) {
        throw new ServiceException(e.getLocalizedMessage());
    }
}

From source file:io.codeclou.jenkins.githubwebhookbuildtriggerplugin.GithubWebhookBuildTriggerAction.java

@RequirePOST
public HttpResponse doReceive(HttpServletRequest request, StaplerRequest staplerRequest)
        throws IOException, ServletException {
    StringWriter writer = new StringWriter();
    IOUtils.copy(request.getInputStream(), writer, "UTF-8");
    String requestBody = writer.toString();
    Gson gson = new Gson();
    GithubWebhookPayload githubWebhookPayload = gson.fromJson(requestBody, GithubWebhookPayload.class);
    StringBuilder info = new StringBuilder();
    if (githubWebhookPayload == null) {
        return HttpResponses.error(500, this
                .getTextEnvelopedInBanner("   ERROR: payload json is empty at least requestBody is empty!"));
    }//w w  w.  j a  v  a  2 s . com
    try {
        //
        // WEBHOOK SECRET
        //
        String githubSignature = request.getHeader("x-hub-signature");
        String webhookSecretAsConfiguredByUser = GithubWebhookBuildTriggerPluginBuilder.DescriptorImpl
                .getDescriptor().getWebhookSecret();
        String webhookSecretMessage = "validating webhook payload against wevhook secret.";
        info.append(">> webhook secret validation").append("\n");
        if (webhookSecretAsConfiguredByUser == null || webhookSecretAsConfiguredByUser.isEmpty()) {
            webhookSecretMessage = "   skipping validation since no webhook secret is configured in \n"
                    + "   'Jenkins' -> 'Configure' tab under 'Github Webhook Build Trigger' section.";
        } else {
            Boolean isValid = GitHubWebhookUtility.verifySignature(requestBody, githubSignature,
                    webhookSecretAsConfiguredByUser);
            if (!isValid) {
                info.append(webhookSecretMessage).append("\n");
                return HttpResponses.error(500, this.getTextEnvelopedInBanner(info.toString()
                        + "   ERROR: github webhook secret signature check failed. Check your webhook secret."));
            }
            webhookSecretMessage = "   ok. Webhook secret validates against " + githubSignature + "\n";
        }
        info.append(webhookSecretMessage).append("\n\n");

        //
        // CHECK IF INITIAL REQUEST (see test-webhook-init-payload.json)
        // See: https://developer.github.com/webhooks/#ping-event
        //
        if (githubWebhookPayload.getHook_id() != null) {
            info.append(">> ping request received: your webhook with ID ");
            info.append(githubWebhookPayload.getHook_id());
            info.append(" is working :)\n");
            return HttpResponses.plainText(this.getTextEnvelopedInBanner(info.toString()));
        }

        //
        // PAYLOAD TO ENVVARS
        //
        EnvironmentContributionAction environmentContributionAction = new EnvironmentContributionAction(
                githubWebhookPayload);

        //
        // TRIGGER JOBS
        //
        String jobNamePrefix = this.normalizeRepoFullName(githubWebhookPayload.getRepository().getFull_name());
        StringBuilder jobsTriggered = new StringBuilder();
        ArrayList<String> jobsAlreadyTriggered = new ArrayList<>();
        StringBuilder causeNote = new StringBuilder();
        causeNote.append("github-webhook-build-trigger-plugin:\n");
        causeNote.append(githubWebhookPayload.getAfter()).append("\n");
        causeNote.append(githubWebhookPayload.getRef()).append("\n");
        causeNote.append(githubWebhookPayload.getRepository().getClone_url());
        Cause cause = new Cause.RemoteCause("github.com", causeNote.toString());
        Collection<Job> jobs = Jenkins.getInstance().getAllItems(Job.class);
        if (jobs.isEmpty()) {
            jobsTriggered.append("   WARNING NO JOBS FOUND!\n");
            jobsTriggered.append("      You either have no jobs or if you are using matrix-based security,\n");
            jobsTriggered.append("      please give the following rights to 'Anonymous':\n");
            jobsTriggered.append("      'Job' -> build, discover, read.\n");
        }
        for (Job job : jobs) {
            if (job.getName().startsWith(jobNamePrefix) && !jobsAlreadyTriggered.contains(job.getName())) {
                jobsAlreadyTriggered.add(job.getName());
                if (job instanceof WorkflowJob) {
                    WorkflowJob wjob = (WorkflowJob) job;
                    if (wjob.isBuildable()) {
                        jobsTriggered.append("   WORKFLOWJOB> ").append(job.getName()).append(" TRIGGERED\n");
                        wjob.scheduleBuild2(0, environmentContributionAction.transform(),
                                new CauseAction(cause));
                    } else {
                        jobsTriggered.append("   WORKFLOWJOB> ").append(job.getName())
                                .append(" NOT BUILDABLE. SKIPPING.\n");
                    }
                } else {
                    AbstractProject projectScheduable = (AbstractProject) job;
                    if (job.isBuildable()) {
                        jobsTriggered.append("   CLASSICJOB>  ").append(job.getName()).append(" TRIGGERED\n");
                        projectScheduable.scheduleBuild(0, cause, environmentContributionAction);
                    } else {
                        jobsTriggered.append("   CLASSICJOB>  ").append(job.getName())
                                .append(" NOT BUILDABLE. SKIPPING.\n");
                    }
                }
            }
        }
        //
        // WRITE ADDITONAL INFO
        //
        info.append(">> webhook content to env vars").append("\n");
        info.append(environmentContributionAction.getEnvVarInfo());
        info.append("\n");
        info.append(">> jobs triggered with name matching '").append(jobNamePrefix).append("*'").append("\n");
        info.append(jobsTriggered.toString());
        return HttpResponses.plainText(this.getTextEnvelopedInBanner(info.toString()));
    } catch (JsonSyntaxException ex) {
        return HttpResponses.error(500,
                this.getTextEnvelopedInBanner(info.toString() + "   ERROR: github webhook json invalid"));
    }
}

From source file:com.library.essay.tinymce.spellchecker.GoogleSpellChekerServlet.java

public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    PrintWriter out = response.getWriter();
    try {/*  ww w.j a v  a  2  s . co m*/
        JSONObject requestJSONdata = requestDataToJSON(request.getInputStream());
        String method = requestJSONdata.getString("method");
        String language = requestJSONdata.getJSONArray("params").getString(0);
        this.connect(language);
        this.setHeaders();
        String textToCheck;

        if (method.equalsIgnoreCase("checkWords")) {
            JSONArray words = requestJSONdata.getJSONArray("params").getJSONArray(1);
            textToCheck = words.join(" ").replaceAll("\"", "");
        } else if (method.equalsIgnoreCase("getSuggestions")) {
            textToCheck = requestJSONdata.getJSONArray("params").getString(1);
        } else {
            out.println(
                    "{\"id\":null,\"results\":null,\"error\":\"Invalid request, method not yet implemented\"}");
            out.flush();
            return;
        }

        this.sendData(getXML(textToCheck));
        JSONObject responseJSON = this.receiveData(method, textToCheck);
        if (responseJSON == null) {
            out.println("{\"id\":null,\"results\":null,\"error\":\"No suggestions were received\"}");
            out.flush();
            return;
        }

        responseJSON.write(out);
        out.flush();
    } catch (JSONException e1) {

        //Send error to client, exit
        out.println("{\"id\":null,\"results\":null,\"error\":\"Invalid request, cannot parse json data\"}");
        out.flush();
        return;
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }

}

From source file:com.honnix.yaacs.adapter.http.ACRequestHandler.java

private InputStream getRequestInputStream(HttpServletRequest request) {
    InputStream inputStream = null;

    try {/*  w  ww . j  ava 2  s  .  c  o  m*/
        inputStream = request.getInputStream();
    } catch (IOException e) {
        LOG.warn("Error retrieving input stream from request.", e);
    }

    return inputStream;
}

From source file:com.openmeap.services.ServiceManagementServlet.java

/**
 * /* ww w.  jav a2  s. c o m*/
 * @param request
 * @param response
 * @return
 * @throws IOException
 */
private Result healthCheck(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String json = Utils.readInputStream(request.getInputStream(), FormConstants.CHAR_ENC_DEFAULT);
    Result result = null;
    try {
        ClusterNodeRequest nodeRequest = (ClusterNodeRequest) new JSONObjectBuilder()
                .fromJSON(new JSONObject(json), new ClusterNodeRequest());
        Map<String, String> properties = (Map<String, String>) context
                .getBean("openmeapServicesWebPropertiesMap");
        synchronized (properties) {
            properties.put("clusterNodeUrlPrefix", nodeRequest.getClusterNode().getServiceWebUrlPrefix());
            properties.put("fileSystemStoragePathPrefix",
                    nodeRequest.getClusterNode().getFileSystemStoragePathPrefix());
        }
        result = new Result(Result.Status.SUCCESS);
    } catch (JSONException e) {
        result = new Result();
        result.setStatus(Result.Status.FAILURE);
        String msg = "Failed to parse health status check JSON - " + json;
        logger.error(msg);
        result.setMessage(msg);
    }

    return result;
}