Example usage for javax.servlet.http HttpServletRequest getReader

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

Introduction

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

Prototype

public BufferedReader getReader() throws IOException;

Source Link

Document

Retrieves the body of the request as character data using a BufferedReader.

Usage

From source file:com.devnexus.ting.web.controller.AndroidLoginController.java

/**
 * This will verify tokens sent from an Authenticated Android device that
 * the user is who the user says it is.//from  w w  w.  j  a v  a 2s .  c o m
 * <p/>
 * Additionally it will create an account if one does not exist.
 */
@RequestMapping(value = "/s/loginAndroid", method = RequestMethod.POST)
@ResponseBody
public String login(HttpServletRequest request, HttpServletResponse response) {

    try {

        AndroidAuthentication auth = GSON.fromJson(request.getReader(), AndroidAuthentication.class);
        String accessToken = auth.idToken;

        GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(new NetHttpTransport(),
                new JacksonFactory()).setAudience(Arrays.asList(CLIENT_ID))
                        // If you retrieved the token on Android using the
                        // Play Services 8.3 API or newer, set
                        // the issuer to "https://accounts.google.com".
                        // Otherwise, set the issuer to
                        // "accounts.google.com". If you need to verify
                        // tokens from multiple sources, build
                        // a GoogleIdTokenVerifier for each issuer and try
                        // them both.
                        .setIssuer("https://accounts.google.com").build();

        GoogleIdToken idToken = verifier.verify(accessToken);
        Payload payload = idToken.getPayload();

        User user;
        try {
            user = (User) userService.loadUserByUsername("google:" + payload.getSubject());
        } catch (UsernameNotFoundException e) {
            user = new User();
            user.setEmail(payload.getEmail());
            user.setUsername("google:" + payload.getSubject());
            user.setUserAuthorities(new HashSet<UserAuthority>(1));
            user.getUserAuthorities().add(new UserAuthority(user, AuthorityType.APP_USER));
            user.setFirstName((String) payload.get("given_name"));
            user.setLastName((String) payload.get("family_name"));
            byte[] password = new byte[16];
            new SecureRandom().nextBytes(password);
            user.setPassword(Arrays.toString(password));

            try {
                userService.addUser(user);
            } catch (DuplicateUserException ex) {
                Logger.getLogger(AndroidLoginController.class.getName()).log(Level.SEVERE, null, ex);
                throw new RuntimeException(ex);
            }

            user = (User) userService.loadUserByUsername(user.getUsername());

        }

        MobileSignIn signIn = new MobileSignIn();
        signIn.setToken(new BigInteger(512, new SecureRandom()).toString(32));
        signIn.setUser(user);
        user.getMobileTokens().add(signIn);

        userService.updateUser(user);

        return "{\"token\":\"" + signIn.getToken() + "\"}";

    } catch (IOException | GeneralSecurityException e) {
        Logger.getAnonymousLogger().log(Level.SEVERE, e.getMessage(), e);

        throw new RuntimeException(e);
    }

}

From source file:org.academia.servlet.SMatricula.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from  www . j ava2 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 {
    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            jb.append(line);
        }
        //System.out.println(jb.toString());
        String datt = String.valueOf(jb.toString());

        JSONObject jsonObj = new JSONObject(datt);

        BAlumno oBAlumno = new BAlumno();
        String value = (String) jsonObj.get("nombre");
        oBAlumno.setNombre(value);

        value = (String) jsonObj.get("apellidoPaterno");
        oBAlumno.setApellidoPaterno(value);

        value = (String) jsonObj.get("apellidoMaterno");
        oBAlumno.setApellidoMaterno(value);

        value = (String) jsonObj.get("dni");
        oBAlumno.setDni(value);

        value = (String) jsonObj.get("direccion");
        oBAlumno.setDireccion(value);

        oBAlumno.setEstado(true);
        oBAlumno.setIdSalon(5);
        oBAlumno.setIdExamen(5);

        int idAlumno = new DAOAlumno().registrarAlumno(oBAlumno);

        BMatricula oBMatricula = new BMatricula();

        value = (String) jsonObj.get("escuela");
        oBMatricula.setEscuela(value);
        value = (String) jsonObj.get("idciclo");
        oBMatricula.setIdCiclo(Integer.parseInt(value));

        oBMatricula.setIdAlumno(idAlumno);
        oBMatricula.setIdSecretario(1);
        oBMatricula.setMonto(360.0);

        boolean flag = new DAOMatricula().registrarAlumno(oBMatricula);

        if (idAlumno != 0 && flag == true) {
            String json1 = new Gson().toJson("Alumno matriculado!");
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(json1);
        } else {
            String json1 = new Gson().toJson("Error al matricular Alumno");
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(json1);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:servlets.DeleteStudentServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  w w  w .j a  v a 2  s .c om
 * @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 {
    try (PrintWriter out = response.getWriter()) {
        StudentDAO stDao = new StudentDAO();
        JSONParser parser = new JSONParser();
        try {
            JSONObject jsonObj = (JSONObject) parser.parse(new BufferedReader(request.getReader()));
            stDao.deleteStudent((long) jsonObj.get("id"));
        } catch (Exception e) {
            out.println(e.getMessage());
        }
    }
}

From source file:com.google.ratel.util.RatelUtils.java

public static Reader createLimitedReader(HttpServletRequest request, final int maxRequestSize) {

    try {//from  w  ww  . j  a v a 2 s  .  c o  m
        Reader reader = request.getReader();

        // Limit input to stop flood requests
        final long requestSize = request.getContentLength();

        if (maxRequestSize >= 0) {
            if (requestSize != -1 && requestSize > maxRequestSize) {

                String msg = format(
                        "the request was rejected because its size (%s) exceeds the configured maximum (%s)",
                        requestSize, maxRequestSize);
                throw new IllegalArgumentException(msg);
            }

            reader = new LimitedReader(reader, maxRequestSize) {
                @Override
                protected void raiseError(long pSizeMax, long pCount) throws IOException {
                    String msg = format(
                            "the request was rejected because its size (%s) exceeds the configured maximum (%s)",
                            requestSize, maxRequestSize);
                    throw new IllegalArgumentException(msg);
                }
            };
        }

        return reader;

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:servlets.EditStudentServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from w  w w  . ja  va  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 {
    try (PrintWriter out = response.getWriter()) {
        StudentDAO stDao = new StudentDAO();
        JSONParser parser = new JSONParser();
        try {
            JSONObject jsonObj = (JSONObject) parser.parse(new BufferedReader(request.getReader()));
            Student st = (Student) stDao.getStudentById((long) jsonObj.get("id"));
            st.setName((String) jsonObj.get("name"));
            stDao.updateStudent(st);
        } catch (Exception e) {
            out.println(e.getMessage());
        }
    }
}

From source file:org.glyptodon.guacamole.net.example.DummyGuacamoleTunnelServlet.java

@Override
protected GuacamoleTunnel doConnect(HttpServletRequest request) throws GuacamoleException {

    HttpSession httpSession = request.getSession(true);
    JSONObject jsonObject = null;//www. j  a va2 s . c  o  m
    // testing
    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null)
            jb.append(line);
        System.out.println("*** Body: " + jb.toString());
    } catch (Exception e) {
        //System.out.println(e.printStackTrace()); 
        System.out.println("*** Error");
    }

    try {
        jsonObject = new JSONObject(jb.toString());
        System.out.println("****");
        System.out.println(jsonObject.getString("initial-program"));
        /*System.out.println(jsonObject.getString("remote-app"));
        System.out.println(jsonObject.getString("remote-app-dir"));
        System.out.println(jsonObject.getString("remote-app-args"));*/
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // try {
    //     JSONObject jsonObject = JSONObject.fromObject(jb.toString());
    // } catch (ParseException e) {
    //     // crash and burn
    //     throw new IOException("Error parsing JSON request string");
    // }

    // guacd connection information
    String hostname = "localhost";
    int port = 4822;

    // VNC connection information
    GuacamoleConfiguration config = new GuacamoleConfiguration();
    config.setProtocol("vnc");
    config.setParameter("hostname", "localhost");
    config.setParameter("port", "5901");
    config.setParameter("username", "root");
    config.setParameter("password", "welcome");
    // try {
    //     config.setParameter("initial-program", jsonObject.getString("initial-program"));
    //     config.setParameter("remote-app", jsonObject.getString("remote-app"));
    //     config.setParameter("remote-app-dir", jsonObject.getString("remote-app-dir"));
    //     config.setParameter("remote-app-args", jsonObject.getString("remote-app-args"));
    // } catch (JSONException e) {
    //     // TODO Auto-generated catch block
    //     e.printStackTrace();
    // }

    // Connect to guacd, proxying a connection to the VNC server above
    GuacamoleSocket socket = new ConfiguredGuacamoleSocket(new InetGuacamoleSocket(hostname, port), config);

    // Create tunnel from now-configured socket
    GuacamoleTunnel tunnel = new GuacamoleTunnel(socket);

    // Attach tunnel
    GuacamoleSession session = new GuacamoleSession(httpSession);
    session.attachTunnel(tunnel);

    return tunnel;

}

From source file:org.whispersystems.claserver.PullRequestValidationServlet.java

/**
 * This is the endpoint for the github webhook
 */// w  ww .  ja  v a  2 s. c om
protected void doPost(HttpServletRequest request, HttpServletResponse resp)
        throws ServletException, IOException {
    String xHubSig = request.getHeader("X-Hub-Signature");
    StringWriter writer = new StringWriter();
    mapper.writeValue(writer, request.getParameterMap());
    String body = CharStreams.toString(request.getReader());
    GithubPullEvent event = mapper.readValue(mapper.getJsonFactory().createJsonParser(body),
            GithubPullEvent.class);

    try {
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec secret = new SecretKeySpec(config.githubSecret.getBytes("UTF-8"), "HmacSHA1");
        mac.init(secret);
        byte[] digest = mac.doFinal(body.getBytes());
        String hmac = String.format("sha1=%s", Hex.encodeHexString(digest));

        if (MessageDigest.isEqual(hmac.getBytes(), xHubSig.getBytes())) {
            updateStatus(config, event.pull_request);
        } else {
            logger.warning("Invalid request signature");
        }
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        e.printStackTrace();
    }
}

From source file:org.academia.servlet.SCrearSecretario.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from w  ww .j av  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 {
    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            jb.append(line);
        }
        //System.out.println(jb.toString());
        String datt = String.valueOf(jb.toString());

        JSONObject jsonObj = new JSONObject(datt);

        BUsuario oBUsuario = new BUsuario();
        String usuario = (String) jsonObj.get("usuario");
        oBUsuario.setUsuario(usuario);

        String password = (String) jsonObj.get("contrasenia");
        oBUsuario.setContrasenia(password);
        oBUsuario.setEstado(true);

        int idUsuario = new DAOUsuario().crearUsario(oBUsuario);

        BSecretario oBSecretario = new BSecretario();
        oBSecretario.setIdUsuario(idUsuario);

        String value = (String) jsonObj.get("nombre");
        oBSecretario.setNombre(value);

        value = (String) jsonObj.get("apellidoPaterno");
        oBSecretario.setApellidoPaterno(value);

        value = (String) jsonObj.get("apellidoMaterno");
        oBSecretario.setApellidoMaterno(value);

        value = (String) jsonObj.get("dni");
        oBSecretario.setDni(value);

        value = (String) jsonObj.get("direccion");
        oBSecretario.setDireccion(value);

        //Valores por defecto

        int idSecretario = new DAOSecretario().crearSecretario(oBSecretario);

        BTelefono oBTelefono = new BTelefono();

        value = (String) jsonObj.get("telefono");
        oBTelefono.setNumero(value);
        //valores predetemindas
        oBTelefono.setIdTelefono(1);
        oBTelefono.setIdTitular(idSecretario);
        oBTelefono.setTipoTelefono("Claro");
        oBTelefono.setEstado(true);

        boolean flag = new DAOTelefono().insertarTelefono(oBTelefono);

        if ((idSecretario != 0) && flag == true) {
            String json1 = new Gson().toJson("Secretario Registrado!");
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(json1);
        } else {
            String json1 = new Gson().toJson("Error al registrar Secretario");
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(json1);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.sc.probro.servlets.RequestListServlet.java

public Request parseRequestFromJSONString(Broker broker, UserCredentials user, HttpServletRequest httpReq)
        throws BrokerException {
    Request req = new Request();
    StringBuilder sb = new StringBuilder();
    try {/*www  .j  a  v  a2  s  . c  o  m*/
        Reader r = httpReq.getReader();
        int rchar = -1;
        while ((rchar = r.read()) != -1) {
            sb.append((char) rchar);
        }

        JSONObject obj = new JSONObject(sb.toString());

        JSONType requestType = schemaEnv.lookupType("NewRequest");
        if (!requestType.contains(obj)) {
            BadRequestException exception = new BadRequestException(requestType.explain(obj));
            //Log.warn(exception);
            throw exception;
        }

        req.setFromJSON(obj, broker, user);

        req.metadata = new ArrayList<Metadata>();

        JSONArray metadataArray = obj.getJSONArray("metadata");
        for (int i = 0; i < metadataArray.length(); i++) {
            JSONObject metaObj = metadataArray.getJSONObject(i);

            Metadata meta = new Metadata();
            meta.setFromJSON(metaObj, broker, user);

            req.metadata.add(meta);
        }

    } catch (IOException e) {
        throw new BrokerException(e);
    } catch (JSONException e) {
        throw new BrokerException(e);
    }
    return req;
}

From source file:ch.unifr.pai.twice.widgets.mpProxyScreenShot.server.ReadOnlyPresentation.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String url = req.getParameter("url"); //e.g.: http://www.sbb.ch

    Object uuidObj = req.getSession().getAttribute(Constants.uuidCookie);
    String uuid = uuidObj != null ? uuidObj.toString() : null;
    BufferedReader reader = req.getReader();
    ByteArrayOutputStream byteArrOS = new ByteArrayOutputStream();
    int b;/*from w ww .  j a  va 2 s . co  m*/
    while ((b = reader.read()) != -1) {
        byteArrOS.write(b);
    }
    byteArrOS.flush();
    byteArrOS.close();
    reader.close();
    String html = new String(byteArrOS.toByteArray(), "UTF-8");
    if (!html.isEmpty() && url != null && !url.isEmpty())
        uuidToScreenshot.put(uuid, new Screenshot(html, url, req.getParameter("height"),
                req.getParameter("width"), req.getParameter("top"), req.getParameter("left")));
}