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.library.essay.tinymce.spellchecker.TinyMCESpellCheckerServlet.java

/**
 * @param request request/*from  w  ww .  j  a v  a 2 s  .c  o  m*/
 * @return read the request content and return it as String object
 * @throws IOException
 */
private String getRequestBody(HttpServletRequest request) throws IOException {
    StringBuilder sb = new StringBuilder();
    String line = request.getReader().readLine();
    while (null != line) {
        sb.append(line);
        line = request.getReader().readLine();
    }

    return sb.toString();
}

From source file:jp.co.applibot.backup.BackupController.java

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String json = "";
    String className = "";
    String key = "";
    Long now = new Date().getTime();
    if (request != null) {
        BufferedReader bufferReaderBody = new BufferedReader(request.getReader());
        String body = bufferReaderBody.readLine();
        json = body;/*  w w  w . j  a v a2 s  .c o m*/
    }

    int indexLast = json.indexOf("\":");
    if (indexLast > 0) {
        className = json.substring(1, indexLast);
    }
    className = className.replaceAll("\"", "");

    JSONParser parser = new JSONParser();
    //      try {
    //          
    //         Object wrapObj = parser.parse(json);
    //   
    //         JSONObject jsonWrapObject = (JSONObject) wrapObj;
    //    
    //         String jsonObj = jsonWrapObject.get(className).toString();
    //         
    //         Object obj = parser.parse(jsonObj);
    //         
    //         JSONObject jsonObject = (JSONObject) obj;
    //         
    //         key = jsonObject.get("id").toString();
    //    
    //      } catch (ParseException e) {
    //         e.printStackTrace();
    //      }

    JSch jsch = new JSch();
    String host = "107.167.177.138";
    String user = "dmlogging";
    String passwd = "Applibot12345";
    try {
        Session session = jsch.getSession(user, host, 22);
        session.setPassword(passwd);
        session.connect(30000);
        Channel channel = session.openChannel("exec");
        // ((ChannelExec)channel).setCommand("\"" + json +"\"" +  ">> /home/komiya_sakura_applibot_co_jp/test.txt");
        ((ChannelExec) channel).setCommand("mkdir /home/komiya_sakura_applibot_co_jp/logfiles");
        LOGGER.warning("command set");
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(System.err);

        InputStream in = channel.getInputStream();

        channel.connect();
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0)
                    break;
                LOGGER.warning(new String(tmp, 0, i));
            }
            if (channel.isClosed()) {
                if (in.available() > 0)
                    continue;
                LOGGER.warning("exit-status: " + channel.getExitStatus());
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
            }
        }
        channel.disconnect();
        session.disconnect();
    } catch (JSchException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    GcsFilename fileName = new GcsFilename(BUCKETNAME, className + "_" + now.toString() + "_" + key);
    GcsFileOptions options = new GcsFileOptions.Builder().mimeType("text/html").acl("public-read").build();
    GcsOutputChannel outputChannel = gcsService.createOrReplace(fileName, options);

    outputChannel.write(ByteBuffer.wrap(json.getBytes("UTF8")));
    outputChannel.close();

    //reply
    PrintWriter out = response.getWriter();
    out.println(json);
}

From source file:hu.fnf.devel.wishbox.gateway.GatewayREST.java

@Secured({ "ROLE_ADMIN" })
@RequestMapping(value = "/persistence/user/{userId}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String createUser(@PathVariable("userId") String userId, HttpServletRequest request) {
    StringBuilder content = new StringBuilder();
    StringBuilder stringBuilder = new StringBuilder();
    X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
    for (X509Certificate cert : certs) {
        stringBuilder.append(cert.getSubjectX500Principal().getName());
    }//from  ww  w  . j  a v  a  2s.  com
    try {
        while (request.getReader().ready()) {
            content.append(request.getReader().readLine());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return userId + ": " + content + ": " + stringBuilder;
}

From source file:org.openhab.io.neeo.internal.AbstractServlet.java

/**
 * Handles the post by routing it to the appropriate {@link ServletService} or logging it if no route found
 *//*from   w  ww.  j  av a 2 s  .c om*/
@Override
protected void doPost(@Nullable HttpServletRequest req, @Nullable HttpServletResponse resp)
        throws ServletException, IOException {
    Objects.requireNonNull(req, "req cannot be null");
    Objects.requireNonNull(resp, "resp cannot be null");

    if (logger.isDebugEnabled()) {
        req.getReader().mark(150000);
        logger.debug("doPost: {} with {}", getFullURL(req), IOUtils.toString(req.getReader()));
        req.getReader().reset();
    }

    final String pathInfo = NeeoUtil.decodeURIComponent(req.getPathInfo());
    final String[] paths = StringUtils.split(pathInfo.startsWith("/") ? pathInfo.substring(1) : pathInfo, '/');
    final ServletService service = getService(paths);

    if (service == null) {
        logger.debug("Unknown/unhandled route: {}", pathInfo);
    } else {
        service.handlePost(req, paths, resp);
    }
}

From source file:org.eclipse.orion.server.git.servlets.GitDiffHandlerV1.java

private boolean identifyNewDiffResource(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    try {/*from w  ww  . ja  va 2 s.  c  o m*/
        StringWriter writer = new StringWriter();
        IOUtilities.pipe(request.getReader(), writer, false, false);
        JSONObject requestObject = new JSONObject(writer.toString());
        URI u = getURI(request);
        IPath p = new Path(u.getPath());
        IPath np = new Path("/"); //$NON-NLS-1$
        for (int i = 0; i < p.segmentCount(); i++) {
            String s = p.segment(i);
            if (i == 2) {
                s += ".."; //$NON-NLS-1$
                s += GitUtils.encode(requestObject.getString(GitConstants.KEY_COMMIT_NEW));
            }
            np = np.append(s);
        }
        if (p.hasTrailingSeparator())
            np = np.addTrailingSeparator();
        URI nu = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), u.getPort(), np.toString(), u.getQuery(),
                u.getFragment());
        JSONObject result = new JSONObject();
        result.put(ProtocolConstants.KEY_LOCATION, nu.toString());
        OrionServlet.writeJSONResponse(request, response, result);
        response.setHeader(ProtocolConstants.HEADER_LOCATION, resovleOrionURI(request, nu).toString());
        return true;
    } catch (Exception e) {
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "An error occured when identifying a new Diff resource.", e));
    }
}

From source file:com.mxgraph.online.dredit.FileServlet.java

/**
 * Update a file given a JSON representation, and return the JSON
 * representation of the created file.//from   w w w. j  a  v a 2 s.co m
 */
@Override
public void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {
        CredentialMediator cm = getCredentialMediator(req, resp);
        ClientFile clientFile = new ClientFile(req.getReader());
        //user can initiate a Save from logged out tab, we log out the other users to allow saving any unsaved work
        if (clientFile.userId != null
                && !clientFile.userId.equals(req.getSession().getAttribute(CredentialMediator.USER_ID_KEY))) {
            endSession(req, resp, cm);
        }

        Drive service = getDriveService(req, resp, cm);
        File file = clientFile.toFile();
        file = service.files().update(clientFile.resource_id, file,
                ByteArrayContent.fromString(clientFile.mimeType, clientFile.content)).execute();

        resp.setContentType(JSON_MIMETYPE);
        resp.getWriter().print(new Gson().toJson(file.getId()).toString());
    } catch (Exception e) {
        resp.setStatus(500);
        if (e instanceof GoogleJsonResponseException) {
            GoogleJsonResponseException e2 = (GoogleJsonResponseException) e;
            resp.setStatus(e2.getStatusCode());
        }
        try {
            resp.getWriter().write(getAuthorizationUrl(req, true));
        } catch (Exception ex) {
            throw new RuntimeException("Failed to redirect for authorization.");
        }
    }
}

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

@RequestMapping(path = "/s/user-schedule", method = { RequestMethod.POST, RequestMethod.PUT })
public List<UserScheduleItem> updateUserScheduleCurrentEvent(HttpServletRequest request) {

    try {//  w w w .  j a  v a 2  s  .  c  om
        String accessToken = request.getHeader("authToken");

        User user;
        user = (User) userService.loadUserByAndroidToken(accessToken);

        JsonArray presentaitonIds = new JsonParser().parse(request.getReader()).getAsJsonArray();
        List<UserScheduleItem> scheduleItems = new ArrayList<>(presentaitonIds.size());

        for (int index = 0; index < presentaitonIds.size(); index++) {
            UserScheduleItem item = new UserScheduleItem();

            item.setUser(user);
            item.setScheduleItem(
                    businessService.getPresentation(presentaitonIds.get(index).getAsLong()).getScheduleItem());
            scheduleItems.add(item);
        }

        calendarServices.replaceScheduleItemsForUser(user, scheduleItems);
        return businessService.getUserScheduleItemsForCurrentEventForUser(user);
    } catch (IOException ex) {
        Logger.getLogger(AndroidLoginController.class.getName()).log(Level.SEVERE, null, ex);
        throw new RuntimeException(ex);
    }
}

From source file:com.zextras.zimbradrive.CreateTempAttachmentFileHttpHandler.java

private void doInternalPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    Account account = mBackendUtils.assertAccountFromAuthToken(httpServletRequest);
    ZimbraLog.addAccountNameToContext(account.getName());
    String path;//from   ww  w.j  a v  a2s . c  o m
    BufferedReader reader = httpServletRequest.getReader();
    while ((path = reader.readLine()) != null) {
        HttpResponse fileRequestResponse = mCloudHttpRequestUtils.queryCloudServerService(account, path);

        int responseCode = fileRequestResponse.getStatusLine().getStatusCode();
        if (responseCode < HTTP_LOWEST_ERROR_STATUS) {
            HttpPost post = new HttpPost(mBackendUtils.getServerServiceUrl("/service/upload?fmt=extended,raw"));
            post.setHeader(CONTENT_DISPOSITION_HTTP_HEADER, "attachment; filename=\" "
                    + convertToUnicode(path.substring(path.lastIndexOf("/") + 1)) + " \"");
            post.setHeader("Cache-Control", "no-cache");
            post.setHeader("Cookie", httpServletRequest.getHeader("Cookie"));
            post.setHeader("X-Zimbra-Csrf-Token", httpServletRequest.getHeader("X-Zimbra-Csrf-Token"));
            post.setEntity(fileRequestResponse.getEntity());

            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s)
                        throws CertificateException {
                    return true;
                }
            });
            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(builder.build());
            CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();

            HttpResponse response = client.execute(post);

            response.getEntity().writeTo(httpServletResponse.getOutputStream());
        } else {
            httpServletResponse.setStatus(responseCode);
            PrintWriter respWriter = httpServletResponse.getWriter();
            respWriter.println("Error");
            respWriter.close();
            break;
        }
    }
}

From source file:com.mxgraph.online.dredit.FileServlet.java

/**
 * Create a new file given a JSON representation, and return the JSON
 * representation of the created file.//  w w  w  . j  a  v a2  s.  c o m
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {
        CredentialMediator cm = getCredentialMediator(req, resp);
        ClientFile clientFile = new ClientFile(req.getReader());
        //user can initiate a Save from logged out tab, we log out the other users to allow saving any unsaved work
        if (clientFile.userId != null
                && !clientFile.userId.equals(req.getSession().getAttribute(CredentialMediator.USER_ID_KEY))) {
            endSession(req, resp, cm);
        }

        Drive service = getDriveService(req, resp, cm);
        // TODO: Fetch parentId from JSON request and update the ParentsCollection of the file
        File file = clientFile.toFile();

        if (!clientFile.content.equals("")) {
            try {
                file = service.files()
                        .insert(file, ByteArrayContent.fromString(clientFile.mimeType, clientFile.content))
                        .execute();
            } catch (HttpResponseException e) {
                // TODO: Parse JSON response
                if (e.getMessage().indexOf("\"reason\": \"appNotInstalled\"") > 0) {
                    resp.setStatus(403);

                    try {
                        resp.getWriter().write(APP_INSTALL_URL);
                    } catch (Exception ex) {
                        throw new RuntimeException("Failed to redirect for installation URL.");
                    }
                }
            }
        } else {
            file = service.files().insert(file).execute();
        }

        resp.setContentType(JSON_MIMETYPE);
        resp.getWriter().print(new Gson().toJson(file.getId()).toString());
    } catch (Exception e) {
        resp.setStatus(500);
        if (e instanceof GoogleJsonResponseException) {
            GoogleJsonResponseException e2 = (GoogleJsonResponseException) e;
            resp.setStatus(e2.getStatusCode());
        }
        try {
            resp.getWriter().write(getAuthorizationUrl(req, true));
        } catch (Exception ex) {
            throw new RuntimeException("Failed to redirect for authorization.");
        }
    }
}

From source file:org.jahia.modules.example.settings.SettingsAction.java

/**
 * This method handles saving./*from  w  w w .ja v  a 2 s .  c o m*/
 *
 * @param request
 * @param renderContext
 * @param resource
 * @param session
 * @param parameters
 * @param urlResolver
 * @return
 * @throws Exception
 */
@Override
public ActionResult doExecute(final HttpServletRequest request, final RenderContext renderContext,
        final Resource resource, final JCRSessionWrapper session, final Map<String, List<String>> parameters,
        final URLResolver urlResolver) throws Exception {
    try {
        // Get the request chars and set to response text.
        final String responseText = CharStreams.toString(request.getReader());
        final JSONObject settings;
        final Settings serverSettings;
        final String siteKey = renderContext.getSite().getSiteKey();

        // if payload has content, it means an update.
        if (StringUtils.isNotEmpty(responseText)) {
            // Create JSONObject from responseText.
            settings = new JSONObject(responseText);

            // Get the settings from the JCR.
            final Settings oldSettings = settingsService.getSettings(siteKey);

            // Check against the settings from the JCR with the new setting property that has been posted.
            final Boolean enabled = getSettingOrDefault(settings, SettingsConstants.ENABLED,
                    (oldSettings != null && oldSettings.getEnabled()));
            final String settings1 = getSettingOrDefault(settings, SettingsConstants.SETTING_1,
                    (oldSettings != null ? oldSettings.getSetting1() : ""));

            // If service is enabled, then set the settings in the JCR.
            if (enabled) {
                serverSettings = settingsService.setSettings(siteKey, settings1);
            } else {
                serverSettings = null;
            }
        } else {
            serverSettings = settingsService.getSettings(siteKey);
        }

        // Create a JSON object to be returned as a response.
        final JSONObject resp = new JSONObject();
        if (serverSettings != null) {
            resp.put(SettingsConstants.ENABLED, serverSettings.getEnabled());
            resp.put(SettingsConstants.SETTING_1, serverSettings.getSetting1());
        }

        // If no configuration set, then set a variable noConf to true.  This value can be used to display a
        // message to the end user.
        resp.put("noConf", serverSettings == null);
        return new ActionResult(HttpServletResponse.SC_OK, null, resp);
    } catch (Exception e) {
        final JSONObject error = new JSONObject();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("error while saving settings", e);
        }
        // Set the error type and message as a response.
        error.put("error", e.getMessage());
        error.put("type", e.getClass().getSimpleName());
        return new ActionResult(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, error);
    }
}