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:controller.FacebookServlet.java

public boolean doFilePost64(HttpServletRequest request) throws FacebookDAOException {
    System.out.println("Do file post 45");
    if (request.getContentType() == null) {
        System.out.println("Content type null");
        return false;
    }//from   w ww .j ava 2  s  . co  m

    String s = null;
    try {
        ServletInputStream input = request.getInputStream();
        s = IOUtils.toString(input);
        Pattern regex = Pattern
                .compile("name=(.*)&email=(.*)&password=(.*)&birthday=(.*)&profile=(.*)&cover=(.*)");
        Matcher m = regex.matcher(s);
        if (m.find() && m.groupCount() > 0) {
            String name = m.group(1);
            String email = m.group(2);
            String password = m.group(3);
            String birthday = m.group(4);
            String profile = m.group(5);
            String cover = m.group(6);
            System.out.println(name + " - " + email + " - " + password + " - " + birthday);//+" - "+profile);//+" - "+cover);
            System.out.println(profile.length());
            //
            //
            System.out.println("CALENDAR");
            Calendar birth = Calendar.getInstance();
            System.out.println("DATE");
            String date[] = (birthday.split("-"));
            System.out.println("BIRTH" + birthday);
            birth.set(Integer.valueOf(date[0]), Integer.valueOf(date[1]), Integer.valueOf(date[2]));
            //System.out.println(birth);
            System.out.println("USER");
            User u = new User(name, email, birth);
            //System.out.println(u);
            String pathFile = "C:/Users/BBEIRIGO/Documents/NetBeansProjects/WebServiceFacebook/src/main/webapp/";
            FacebookDAO dao = new FacebookDAO(pathFile);
            User cadastrado = dao.saveUser(u, password);
            new File(pathFile + "/photos/" + cadastrado.getId() + "/Cover").mkdirs();
            new File(pathFile + "/photos/" + cadastrado.getId() + "/Profile").mkdirs();
            System.out.println(cadastrado);
            System.out.println("cover:" + cadastrado.getCoverPhoto().getPath());
            ///
            String coverPath = cadastrado.getCoverPhoto().getPath();
            String profilePath = cadastrado.getProfilePhoto().getPath();
            System.out.println(coverPath);
            //                if (saveFileEconded(URLDecoder.decode(cover, "UTF-8"), coverPath)) {
            //                    System.out.println("ENCODE COVER!!!");
            //                } else {
            //                    System.out.println("NO ENCODE COVER!!!");
            //                }
            //                if (saveFileEconded(URLDecoder.decode(profile, "UTF-8"), profilePath)) {
            //                    System.out.println("ENCODE PROFILE!!!");
            //                } else {
            //                    System.out.println("NO ENCODE PROFILE!!!");
            //                }
        } else {
            System.out.println("No achou!");
        }
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(FacebookServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(FacebookServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    return true;
}

From source file:com.ibm.watson.ta.retail.TAProxyServlet.java

/**
 * Create and POST a request to the Watson service
 *
 * @param req//from   w ww.  ja  v a 2s . co m
 *            the Http Servlet request
 * @param resp
 *            the Http Servlet response
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    req.setCharacterEncoding("UTF-8");
    try {
        String reqURI = req.getRequestURI();
        String endpoint = reqURI.substring(reqURI.lastIndexOf('/') + 1);
        String url = baseURL + "/v1/" + endpoint;
        // concatenate query params
        String queryStr = req.getQueryString();
        if (queryStr != null) {
            url += "?" + queryStr;
        }
        URI uri = new URI(url).normalize();
        logger.info("posting to " + url);

        Request newReq = Request.Post(uri);
        newReq.addHeader("Accept", "application/json");

        String metadata = req.getHeader("x-watson-metadata");
        if (metadata != null) {
            metadata += "client-ip:" + req.getRemoteAddr();
            newReq.addHeader("x-watson-metadata", metadata);
        }

        InputStreamEntity entity = new InputStreamEntity(req.getInputStream());
        newReq.bodyString(EntityUtils.toString(entity, "UTF-8"), ContentType.APPLICATION_JSON);

        Executor executor = this.buildExecutor(uri);
        Response response = executor.execute(newReq);
        HttpResponse httpResponse = response.returnResponse();
        resp.setStatus(httpResponse.getStatusLine().getStatusCode());

        ServletOutputStream servletOutputStream = resp.getOutputStream();
        httpResponse.getEntity().writeTo(servletOutputStream);
        servletOutputStream.flush();
        servletOutputStream.close();

        logger.info("post done");
    } catch (Exception e) {
        // Log something and return an error message
        logger.log(Level.SEVERE, "got error: " + e.getMessage(), e);
        resp.setStatus(HttpStatus.SC_BAD_GATEWAY);
    }
}

From source file:org.energy_home.jemma.internal.shapi.HapProxy.java

private Object readXmlObject(HttpServletRequest servletRequest) throws IOException {
    InputStream servletInputStream = servletRequest.getInputStream();
    try {//from  w ww  .  j av a  2  s.  co m
        return xmlConverter.readObject(servletInputStream);
    } finally {
        try {
            if (servletInputStream != null)
                servletInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.esri.gpt.control.search.ServletSavedSearch.java

/**
 * Put saved searches./* w  w w  .  ja v a 2 s. c  o  m*/
 * 
 * @param request the request
 * @param response the response
 * @param context the context
 * @throws SearchException the search exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws JSONException Throws json exception
 */
private void putSavedSearches(HttpServletRequest request, HttpServletResponse response, RequestContext context)
        throws SearchException, IOException, JSONException {

    ISearchSaveRepository saveRpstry = SearchSaveRpstryFactory.getSearchSaveRepository();
    if (saveRpstry instanceof GptRepository) {
        ((GptRepository) saveRpstry).setRequestContext(context);
    }

    SavedSearchCriterias savedSearchCriterias = saveRpstry.getSavedList(context.getUser());
    if (savedSearchCriterias.size() >= SearchConfig.getConfiguredInstance().getMaxSavedSearches()) {
        MessageBroker messageBroker = new FacesContextBroker(request, response).extractMessageBroker();
        String message = messageBroker.getMessage("catalog.search.error.maxSavedSearchesReached").getSummary();
        writeSavedSearches(request, response, context, message);
        return;
    }

    String body = IOUtils.toString(request.getInputStream(), "UTF-8");
    Map<String, String> paramMap = urlToParamMap(body);

    String name = "";
    String criteria = "";
    name = paramMap.get("name");
    if ("".equals(Val.chkStr(name))) {
        MessageBroker messageBroker = new FacesContextBroker(request, response).extractMessageBroker();
        String message = messageBroker.getMessage("catalog.search.savedSearches.noSaveName").getSummary();
        writeSavedSearches(request, response, context, message);
        return;
    }
    criteria = Val.chkStr(paramMap.get("criteria"));
    if (criteria.contains("?")) {
        criteria = criteria.substring(criteria.indexOf("?"));
        criteria = criteria.replace("?", "");
    }

    saveRpstry.save(name, criteria, context.getUser());
    writeSavedSearches(request, response, context);

}

From source file:net.bull.javamelody.TestMonitoringFilter.java

/** Test.
 * @throws ServletException e/* w  w w.  j  a  v a  2 s .c o m*/
 * @throws IOException e */
@Test
public void testDoFilter() throws ServletException, IOException {
    // displayed-counters
    setProperty(Parameter.DISPLAYED_COUNTERS, "sql");
    try {
        setUp();
        doFilter(createNiceMock(HttpServletRequest.class));
        setProperty(Parameter.DISPLAYED_COUNTERS, "");
        setUp();
        doFilter(createNiceMock(HttpServletRequest.class));
        setProperty(Parameter.DISPLAYED_COUNTERS, "unknown");
        try {
            setUp();
            doFilter(createNiceMock(HttpServletRequest.class));
        } catch (final IllegalArgumentException e) {
            assertNotNull("ok", e);
        }
    } finally {
        setProperty(Parameter.DISPLAYED_COUNTERS, null);
    }

    // url exclue
    setProperty(Parameter.URL_EXCLUDE_PATTERN, ".*");
    try {
        setUp();
        doFilter(createNiceMock(HttpServletRequest.class));
    } finally {
        setProperty(Parameter.URL_EXCLUDE_PATTERN, "");
    }

    // standard
    setUp();
    doFilter(createNiceMock(HttpServletRequest.class));

    // log
    setUp();
    setProperty(Parameter.LOG, TRUE);
    try {
        ((Logger) org.slf4j.LoggerFactory.getLogger(FILTER_NAME)).setLevel(Level.WARN);
        doFilter(createNiceMock(HttpServletRequest.class));

        ((Logger) org.slf4j.LoggerFactory.getLogger(FILTER_NAME)).setLevel(Level.DEBUG);
        doFilter(createNiceMock(HttpServletRequest.class));

        final HttpServletRequest request = createNiceMock(HttpServletRequest.class);
        expect(request.getHeader("X-Forwarded-For")).andReturn("me").anyTimes();
        expect(request.getQueryString()).andReturn("param1=1").anyTimes();
        doFilter(request);
    } finally {
        setProperty(Parameter.LOG, null);
    }

    // ajax
    final HttpServletRequest request = createNiceMock(HttpServletRequest.class);
    expect(request.getHeader("X-Requested-With")).andReturn("XMLHttpRequest");
    doFilter(request);

    // erreur systme http, avec log
    setProperty(Parameter.LOG, TRUE);
    try {
        final String test = "test";
        doFilter(createNiceMock(HttpServletRequest.class), new UnknownError(test));
        doFilter(createNiceMock(HttpServletRequest.class), new IllegalStateException(test));
        // pas possibles:
        //         doFilter(createNiceMock(HttpServletRequest.class), new IOException(test));
        //         doFilter(createNiceMock(HttpServletRequest.class), new ServletException(test));
        //         doFilter(createNiceMock(HttpServletRequest.class), new Exception(test));
    } finally {
        setProperty(Parameter.LOG, null);
    }

    setProperty(Parameter.RUM_ENABLED, TRUE);
    try {
        setUp();
        final HttpServletRequest requestForRum = createNiceMock(HttpServletRequest.class);
        expect(requestForRum.getHeader("accept")).andReturn("text/html");
        expect(requestForRum.getInputStream())
                .andReturn(createInputStreamForString("<html><body>test</body></html>")).anyTimes();
        doFilter(requestForRum);
    } finally {
        setProperty(Parameter.RUM_ENABLED, null);
    }
}

From source file:net.bull.javamelody.TestMonitoringFilter.java

/** Test.
 * @throws ServletException e/*  w w  w  .  j  a  v  a2s. co  m*/
 * @throws IOException e */
@Test
public void testDoFilterWithGWT() throws ServletException, IOException {
    final HttpServletRequest request = createNiceMock(HttpServletRequest.class);
    final String textGwtRpc = "text/x-gwt-rpc";
    expect(request.getContentType()).andReturn(textGwtRpc).anyTimes();
    expect(request.getInputStream()).andReturn(createInputStreamForString("1|2|3|4|5|6|7|8|9|10")).anyTimes();
    doFilter(request);

    final HttpServletRequest request2a = createNiceMock(HttpServletRequest.class);
    expect(request2a.getContentType()).andReturn("not/x-gwt-rpc").anyTimes();
    expect(request2a.getInputStream()).andReturn(createInputStreamForString("1|2|3|4|5|6|7|8|9|10")).anyTimes();
    doFilter(request2a);

    final HttpServletRequest request2b = createNiceMock(HttpServletRequest.class);
    expect(request2b.getContentType()).andReturn(textGwtRpc).anyTimes();
    expect(request2b.getInputStream()).andReturn(createInputStreamForString("1|2|3|4|5|6")).anyTimes();
    expect(request2b.getReader()).andReturn(new BufferedReader(new StringReader("1|2|3|4|5|6"))).anyTimes();
    replay(request2b);
    final PayloadNameRequestWrapper wrapper2b = new PayloadNameRequestWrapper(request2b);
    wrapper2b.getInputStream().read();
    wrapper2b.getReader().read();
    verify(request2b);

    final HttpServletRequest request2 = createNiceMock(HttpServletRequest.class);
    expect(request2.getContentType()).andReturn(textGwtRpc).anyTimes();
    expect(request2.getInputStream()).andReturn(createInputStreamForString("1|2|3|4|5|6||8|9|10")).anyTimes();
    expect(request2.getReader()).andReturn(new BufferedReader(new StringReader("1|2|3|4|5|6"))).anyTimes();
    replay(request2);
    final PayloadNameRequestWrapper wrapper2 = new PayloadNameRequestWrapper(request2);
    wrapper2.getInputStream().read();
    wrapper2.getReader().read();
    verify(request2);

    final HttpServletRequest request3 = createNiceMock(HttpServletRequest.class);
    expect(request3.getContentType()).andReturn(textGwtRpc).anyTimes();
    expect(request3.getCharacterEncoding()).andReturn("utf-8").anyTimes();
    expect(request3.getInputStream()).andReturn(createInputStreamForString("1|2|3|4|5|6||8|9|10")).anyTimes();
    expect(request3.getReader()).andReturn(new BufferedReader(new StringReader("1|2|3|4|5|6"))).anyTimes();
    replay(request3);
    final PayloadNameRequestWrapper wrapper3 = new PayloadNameRequestWrapper(request3);
    wrapper3.getInputStream().read();
    wrapper3.getInputStream().read();
    wrapper3.getReader().read();
    wrapper3.getReader().read();
    verify(request3);
}

From source file:com.enation.app.shop.core.action.api.MemberApiAction.java

/**
 * ?Flash?????//from   w  ww.j  ava 2s.  co m
 * 
 * @return
 */
public String saveAvatar() {
    String targetFile = makeFilename("avatar");

    int potPos = targetFile.lastIndexOf('/') + 1;
    String folderPath = targetFile.substring(0, potPos);
    FileUtil.createFolder(folderPath);

    try {
        File file = new File(targetFile);

        if (!file.exists()) {
            file.createNewFile();
        }

        HttpServletRequest request = ThreadContextHolder.getHttpRequest();
        FileOutputStream dos = new FileOutputStream(file);
        int x = request.getInputStream().read();
        while (x > -1) {
            dos.write(x);
            x = request.getInputStream().read();
        }
        dos.flush();
        dos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    if ("big".equals(type)) {
        Member member = UserConext.getCurrentMember();
        member.setFace("fs:/attachment/avatar/" + photoId + "_big." + FileUtil.getFileExt(photoServer));
        memberManager.edit(member);
    }

    json = "{\"data\":{\"urls\":[\"" + targetFile + "\"]},\"status\":1,\"statusText\":\"??\"}";

    return WWAction.JSON_MESSAGE;
}

From source file:com.thinkberg.webdav.PutHandler.java

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

    try {//from   w  ww . j ava2  s.  c  o m
        if (!LockManager.getInstance().evaluateCondition(object, getIf(request)).result) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
    } catch (LockException e) {
        response.sendError(SC_LOCKED);
        return;
    } catch (ParseException e) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }
    // it is forbidden to write data on a folder
    if (object.exists() && FileType.FOLDER.equals(object.getType())) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    FileObject parent = object.getParent();
    if (!parent.exists()) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    if (!FileType.FOLDER.equals(parent.getType())) {
        response.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    }

    InputStream is = request.getInputStream();
    OutputStream os = object.getContent().getOutputStream();
    long bytesCopied = Util.copyStream(is, os);
    String contentLengthHeader = request.getHeader("Content-length");
    LOG.debug(String.format("sent %d/%s bytes", bytesCopied,
            contentLengthHeader == null ? "unknown" : contentLengthHeader));
    os.flush();
    object.close();

    response.setStatus(HttpServletResponse.SC_CREATED);
}

From source file:net.mindengine.oculus.frontend.web.controllers.api.ApiController.java

private Object[] createMethodArguments(MatchedMethod matchedMethod, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    Class<?>[] parameters = matchedMethod.getMethod().getParameterTypes();
    Annotation[][] parameterAnnotations = matchedMethod.getMethod().getParameterAnnotations();
    Object[] args = new Object[parameters.length];

    for (int i = 0; i < parameters.length; i++) {
        if (parameters[i].equals(HttpServletRequest.class)) {
            args[i] = request;//from  w  ww  . ja  v a2 s. com
        } else if (parameters[i].equals(HttpServletResponse.class)) {
            args[i] = response;

        } else {
            RequestVar var = findAnnotation(parameterAnnotations[i], RequestVar.class);
            if (var != null) {
                args[i] = ClassUtils.createParameter(parameters[i],
                        matchedMethod.getRequestMatcher().group(var.value()));
            } else if (findAnnotation(parameterAnnotations[i], RequestBody.class) != null) {
                String jsonString = IOUtils.toString(request.getInputStream());

                ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                args[i] = objectMapper.readValue(jsonString, parameters[i]);
            } else {
                throw new IllegalArgumentException("Don't know how to map request");
            }
        }
    }

    return args;
}

From source file:com.emc.cto.ridagent.rid.RIDRequestHandler.java

@RequestMapping(method = RequestMethod.POST)
public String handleRequest(HttpServletRequest request, HttpServletResponse response, Model model)
        throws XProcException, IOException, URISyntaxException, TransformerException,
        NoSuchRequestHandlingMethodException {
    try {//ww w  .  j a v a  2s . c  o m

        // check the white list to see if we want to talk to the counter-party
        logger.info("If we got this far, the Spring Security whitelist checking has already passed OK...");

        SecurityContext ssc = SecurityContextHolder.getContext();
        String ridPeerName = ssc.getAuthentication().getName().toString();

        if (ridPeerName != null) {
            logger.info("RID Peer Name is: " + ridPeerName);
            if (!whiteList.contains(ridPeerName)) {
                logger.info("RID Peer name not found in whitelist.");
                logger.info(
                        "Edit RIDSystem-servlet.xml if and as appropriate, in order to authorize this peer.");
                throw new NoSuchRequestHandlingMethodException(request); // results in a 404 Not Found.
            }
            logger.info("Local whitelist Checking completed.");
            logger.info("Incoming WatchList.   " + request.getInputStream().toString());
        }

        PipelineInputCache pi = new PipelineInputCache();

        // supply HTTP body as the source for the resource Create pipeline
        pi.setInputPort("source", request.getInputStream());

        PipelineOutput output = m_requestHandler.executeOn(pi);

        model.addAttribute("pipelineOutput", output);
        return "pipelineOutput";
    } finally {
        ; //TODO add finally handler
    }
}