Example usage for java.io PrintWriter write

List of usage examples for java.io PrintWriter write

Introduction

In this page you can find the example usage for java.io PrintWriter write.

Prototype

public void write(String s) 

Source Link

Document

Writes a string.

Usage

From source file:com.haulmont.cuba.restapi.FileUploadController.java

@RequestMapping(value = "/api/upload", method = RequestMethod.POST)
public void upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
    UserSession userSession = getSession(request, response);
    if (userSession == null)
        return;//from  ww w .ja  v  a 2  s .co m

    AppContext.setSecurityContext(new SecurityContext(userSession));
    try {
        InputStream is = request.getInputStream();
        if (is == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        FileDescriptor fd = getFileDescriptor(request, response);
        if (fd == null)
            return;

        try {
            uploadToMiddleware(userSession, is, fd);
            saveFileDescriptor(fd);

            response.setStatus(HttpServletResponse.SC_OK);
            PrintWriter writer = new PrintWriter(
                    new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8));
            writer.write(fd.getId().toString());
            writer.close();

        } catch (FileStorageException e) {
            log.error("Unable to upload file", e);
            response.sendError(e.getType().getHttpStatus());
        } finally {
            IOUtils.closeQuietly(is);
        }
    } finally {
        AppContext.setSecurityContext(null);
    }
}

From source file:au.org.paperminer.main.LocationFilter.java

/**
 * Deletes a reference to a location by marking it "struckout" (no actual delete from DB)
 * @param req/*from   www  .  j  a  va 2s  .  co m*/
 * @param resp
 */
private void strikeout(HttpServletRequest req, HttpServletResponse resp) {
    String locnList = req.getParameter("lid");
    String troveId = req.getParameter("tid");
    String userId = req.getParameter("uid");
    try {
        m_logger.debug("strikeout userId=" + userId);

        int cnt = m_helper.strikeout(userId, locnList, troveId);
        String[] tmp = locnList.split(",");
        if (tmp.length != cnt) {
            req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e303");
        }
        m_logger.debug("locationFilter locn strikeout: " + troveId + '/' + locnList + " Deleted: " + cnt);
        resp.setContentType("text/json");
        PrintWriter pm = resp.getWriter();
        pm.write("{\"rm\":\"" + cnt + "\"}");
        pm.close();
    } catch (PaperMinerException ex) {
        m_logger.error("Strikeout failed", ex);
        req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e304");
    } catch (IOException ex) {
        req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e114");
    }
}

From source file:au.org.paperminer.main.LocationFilter.java

/**
 * Adds a reference to an existing location
 * @param req/* w  w w  .  j  a va  2s .com*/
 * @param resp
 */
private void add(HttpServletRequest req, HttpServletResponse resp) {
    String userId = req.getParameter("uid");
    String troveId = req.getParameter("tid");
    String locnId = req.getParameter("lid");
    String freq = req.getParameter("freq");
    try {
        boolean res = m_helper.addReference(userId, troveId, locnId, freq, "A");
        m_logger.debug("locationFilter add location " + troveId + '/' + locnId + '/' + freq + " Insert "
                + (res ? "ok" : "failed"));
        if (!res) {
            req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e307");
        }

        resp.setContentType("text/json");
        PrintWriter pw = resp.getWriter();
        pw.write("{ \"res\":" + (res ? "\"ok\"" : "\"failed\"") + " }");
        pw.close();
    } catch (PaperMinerException ex) {
        m_logger.error("add GS record failed", ex);
        req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e307");
    } catch (IOException ex) {
        req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e114");
    }
}

From source file:net.solarnetwork.node.setup.test.DefaultSetupServiceTest.java

@Test
public void renewNetworkCertificate() throws Exception {
    SetupIdentityInfo info = new SetupIdentityInfo(1L, TEST_CONF_VALUE, TEST_SOLARIN_HOST, getHttpServerPort(),
            false, TEST_PW_VALUE);/*  w w w. j  av  a2s. c  om*/
    expect(setupIdentityDao.getSetupIdentityInfo()).andReturn(info).atLeastOnce();
    replayAll();
    keystoreService.saveCACertificate(CA_CERT);
    keystoreService.generateNodeSelfSignedCertificate(TEST_DN);
    String csr = keystoreService.generateNodePKCS10CertificateRequestString();

    X509Certificate originalCert;

    PemReader pemReader = new PemReader(new StringReader(csr));
    try {
        PemObject pem = pemReader.readPemObject();
        PKCS10CertificationRequest req = new PKCS10CertificationRequest(pem.getContent());
        originalCert = PKITestUtils.sign(req, CA_CERT, CA_KEY_PAIR.getPrivate());
        String signedPem = PKITestUtils.getPKCS7Encoding(new X509Certificate[] { originalCert });
        keystoreService.saveNodeSignedCertificate(signedPem);

        log.debug("Saved signed node certificate {}:\n{}", originalCert.getSerialNumber(), signedPem);

        assertThat("Generated CSR", csr, notNullValue());
    } finally {
        pemReader.close();
    }

    // now let's renew!
    AbstractTestHandler handler = new AbstractTestHandler() {

        @Override
        protected boolean handleInternal(String target, HttpServletRequest request,
                HttpServletResponse response, int dispatch) throws Exception {
            assertEquals("POST", request.getMethod());
            assertEquals("/solarin/api/v1/sec/cert/renew", target);
            String password = request.getParameter("password");
            assertEquals("foobar", password);

            String keystoreData = request.getParameter("keystore");
            assertNotNull(keystoreData);
            byte[] data = Base64.decodeBase64(keystoreData);
            KeyStore keyStore = KeyStore.getInstance("pkcs12");
            keyStore.load(new ByteArrayInputStream(data), password.toCharArray());
            Certificate cert = keyStore.getCertificate("node");
            assertNotNull(cert);
            assertTrue(cert instanceof X509Certificate);
            X509Certificate nodeCert = (X509Certificate) cert;
            assertEquals(new X500Principal(TEST_DN), nodeCert.getSubjectX500Principal());
            assertEquals(CA_CERT.getSubjectX500Principal(), nodeCert.getIssuerX500Principal());

            response.setContentType("application/json");
            PrintWriter out = response.getWriter();
            out.write("{\"success\":true}");
            out.flush();
            response.flushBuffer();
            return true;
        }

    };
    httpServer.addHandler(handler);

    service.renewNetworkCertificate("foobar");
}

From source file:com.adobe.acs.commons.wcm.impl.AemEnvironmentIndicatorFilter.java

@Override
@SuppressWarnings("squid:S3776")
public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
        final FilterChain filterChain) throws IOException, ServletException {

    if (!(servletRequest instanceof HttpServletRequest) || !(servletResponse instanceof HttpServletResponse)) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;/* ww w.j av  a2 s  .co m*/
    }

    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final HttpServletResponse response = (HttpServletResponse) servletResponse;

    if (!this.accepts(request)) {
        filterChain.doFilter(request, response);
        return;
    }

    final BufferingResponse capturedResponse = new BufferingResponse(response);

    filterChain.doFilter(request, capturedResponse);

    boolean doInclude = true;
    if (ArrayUtils.isNotEmpty(excludedWCMModes)) {
        // Test for configured WCM modes, where the indicators are not displayed
        WCMMode wcmmode = extractFromRequest(request);

        if (wcmmode != null) {
            for (String m : excludedWCMModes) {
                if (StringUtils.equalsIgnoreCase(wcmmode.name(), m)) {
                    doInclude = false;
                    break;
                }
            }
        } else {
            // No wcmmode could be extracted from the request
        }
    }

    // Get contents
    final String contents = capturedResponse.getContents();

    if (doInclude && contents != null && StringUtils.contains(response.getContentType(), "html")) {

        final int bodyIndex = contents.indexOf("</body>");

        if (bodyIndex != -1) {
            final PrintWriter printWriter = response.getWriter();

            printWriter.write(contents.substring(0, bodyIndex));

            if (StringUtils.isNotBlank(css)) {
                printWriter.write("<style>" + css + " </style>");
                printWriter.write("<div id=\"" + DIV_ID + "\">" + innerHTML + "</div>");
            }

            if (StringUtils.isNotBlank(titlePrefix)) {
                printWriter.printf(TITLE_UPDATE_SCRIPT, titlePrefix);
            }

            printWriter.write(contents.substring(bodyIndex));
            return;
        }
    }

    if (contents != null) {
        response.getWriter().write(contents);
    }
}

From source file:com.haulmont.cuba.restapi.LoginServiceController.java

protected void doLogin(String username, String password, String localeStr, HttpServletRequest request,
        HttpServletResponse response) throws IOException, JSONException {
    Locale locale = localeFromString(localeStr);

    AuthenticationService authenticationService = AppBeans.get(AuthenticationService.NAME);
    try {/*  w  w w .  j  a  v  a  2  s  . c o  m*/
        AbstractClientCredentials credentials = new LoginPasswordCredentials(username,
                passwordEncryption.getPlainHash(password), locale);
        UserSession userSession = authenticationService.login(credentials).getSession();

        if (!userSession.isSpecificPermitted(Authentication.PERMISSION_NAME)) {
            log.info(String.format("User %s is not allowed to use REST-API", username));
            AppContext.setSecurityContext(new SecurityContext(userSession));
            try {
                authenticationService.logout();
            } finally {
                AppContext.setSecurityContext(null);
            }
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        try {
            AppContext.setSecurityContext(new SecurityContext(userSession));
            setSessionInfo(request, userSession);
        } finally {
            AppContext.setSecurityContext(null);
        }

        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter writer = new PrintWriter(
                new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8));
        writer.write(userSession.getId().toString());
        writer.close();

        log.debug(String.format("User %s logged in with REST-API, session id: %s", username,
                userSession.getId()));
    } catch (LoginException e) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

From source file:com.bitranger.parknshop.seller.controller.SellerChangePasCtrl.java

@RequestMapping(method = RequestMethod.GET, value = "/seller/changePassword")
public void changePassword(HttpServletRequest request, HttpServletResponse response) throws IOException {

    System.out.println("SellerChangePasCtrl.changePassword()");

    String oldPassword = request.getParameter("oldPassword");
    String newPassword = request.getParameter("newPassword");
    //String confirmPassword = request.getParameter("confirmPassword");

    PsSeller currentSeller = (PsSeller) request.getSession().getAttribute("currentSeller");

    PsSeller databaseSeller = sellerDAO.findByEmail(currentSeller.getEmail());

    PrintWriter out = response.getWriter();

    String msg = "";

    if (!oldPassword.equals(databaseSeller.getPassword())) {
        msg = "notequal";
    } else {/*from  w ww .  j a v a  2  s. c o m*/
        databaseSeller.setPassword(newPassword);
        sellerDAO.update(databaseSeller);
        msg = "success";
    }

    out.write(msg);
    out.flush();
    out.close();

}

From source file:biz.taoconsulting.dominodav.methods.PROPFIND.java

/**
 * (non-Javadoc)//from w w w . j av a2s  .c o m
 * 
 * @see biz.taoconsulting.dominodav.methods.AbstractDAVMethod#action()
 */
@SuppressWarnings("deprecation")
protected void action() throws Exception { // TODO: cleanup action method by
    // refactoring -- too messy
    boolean withoutChildren = true; // Resource only, no children
    IDAVRepository rep = this.getRepository();
    IDAVResource resource;
    HttpServletResponse resp = this.getResp();

    // Resource-Path is stripped by the repository name!
    String curPath = null;
    String curURI = null;

    try {
        curPath = (String) this.getHeaderValues().get("resource-path");
        if (curPath == null || curPath.equals("")) {
            curPath = "/";
        }
        // If Depth is missing it might throw an error, so we assume 0 then
        String depth = this.getHeaderValues().get("Depth");
        if (depth != null && depth.equals("0")) {
            withoutChildren = true;
        } else {
            withoutChildren = false;
        }
        // uri is the unique identifier on the host includes servlet and
        // repository but not server
        curURI = (String) this.getHeaderValues().get("uri");

    } catch (Exception e) {
        LOGGER.error(e);
        withoutChildren = true; // No recursive call to propfind in a error
        // condition
    }

    LOGGER.info("PROPFIND for path:[" + curPath + "] and URI:" + curURI);

    IDAVXMLResponse xr = DavXMLResponsefactory.getXMLResponse(null, false);
    if (this.redirectedFromGet) {
        // Determine the style
        String xsltStyle = null;
        if (rep instanceof DAVRepositoryMETA) {
            xsltStyle = WebDavManager.getManager(null).getRootPropfindStyle();
        } else {
            xsltStyle = WebDavManager.getManager(null).getPropfindStyle();
        }
        xr = DavXMLResponsefactory.getXMLResponse(xsltStyle, true);

    } else {
        xr = DavXMLResponsefactory.getXMLResponse(null, true);
    }
    // LOGGER.info("xr OK");
    // xr = DavXMLResponsefactory.getXMLResponse(null, false);

    try {

        // Here we need to retrieve the path without the repository name!
        resource = rep.getResource(curURI, withoutChildren);

        if (resource == null) {
            // LOGGER.info("Resource is null");
            this.setErrorMessage("<h1>404 - Resource not found</h1>", HttpServletResponse.SC_NOT_FOUND);

            String result = this.getErrorMessage();
            resp.setContentLength(result.length());
            PrintWriter out = resp.getWriter();
            out.write(result);
            out.close();

        } else {

            if (!resource.isCollection()) {
                // LOGGER.info("Resource is not a collection");
                this.getResp().setHeader("ETag", resource.getETag());
            }
            // Modified by EC
            // LOGGER.info("Further.....");

            java.util.Date dt = new java.util.Date();
            this.getResp().setHeader("Last-Modified", dt.toGMTString());
            this.getResp().setHeader("Cache-Control", "no-cache");
            dt.setYear(70);
            this.getResp().setHeader("Expires", dt.toGMTString());
            this.getResp().setHeader("Server", "Microsoft-IIS/6.0");
            this.getResp().setHeader("Public-Extension", "http://schemas.microsoft.com/repl-2");
            this.getResp().setHeader("MicrosoftSharePointTeamServices", "12.0.0.6210");
            this.getResp().setHeader("Set-Cookie", "WSS_KeepSessionAuthenticated=80; path=" + curURI);

            // End Mody by EC
            xr.openTag("multistatus");
            resource.addToDavXMLResponse(xr);
            xr.auxTag("username", rep.getCredentials().getUserName());
            xr.addComment("Called method : PROPFIND");
            xr.closeDocument();
            // LOGGER.info("Close doc");
            // Ugly hack: Domino closes connections on status 207
            // and Win7 has a problem with it

            /*
             * if (this.redirectedFromGet ||
             * this.cameFromWindows7webDAVredir(this.getReq())) {
             * this.setHTTPStatus(HttpServletResponse.SC_OK);
             * resp.setStatus(HttpServletResponse.SC_OK); } else {
             * this.setHTTPStatus(DAVProperties.STATUS_MULTIPART);
             * resp.setStatus(DAVProperties.STATUS_MULTIPART,
             * DAVProperties.STATUS_MULTIPART_STRING); }
             */

            this.setHTTPStatus(DAVProperties.STATUS_MULTIPART);
            resp.setStatus(DAVProperties.STATUS_MULTIPART, DAVProperties.STATUS_MULTIPART_STRING);
            resp.setHeader("Connection", "keep-alive");

            resp.setContentType(DAVProperties.TYPE_XML);
            // resp.setContentType("text/xml");
            // resp.setHeader("content-encoding", "utf-8");
            // resp.setContentLength(xr.getXMLBytes().length);
            // ServletOutputStream out = this.getOutputStream();
            // out.write(xr.getXMLBytes());
            // out.close();
            String result = xr.toString();
            resp.setContentLength(result.length());
            PrintWriter out = resp.getWriter();
            out.write(result);
            out.close();
        }

    } catch (DAVNotFoundException exc) {
        // LOGGER.error(exc);
        this.setErrorMessage("<h1>404 - Resource not found</h1>", HttpServletResponse.SC_NOT_FOUND);
        String result = this.getErrorMessage();
        resp.setContentLength(result.length());
        PrintWriter out = resp.getWriter();
        out.write(result);
        out.close();
    } catch (IOException e) {
        // LOGGER.error(e);
        this.setErrorMessage("<h1>500 - We screwed up</h1><h2>" + e.getMessage() + "</h2>",
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

}

From source file:au.org.paperminer.main.LocationFilter.java

/**
 * Inserts a new reference to a new location (also inserted, though we double check it is not already known)
 * @param req//from   w ww  . j  a  v  a  2  s  . c o m
 * @param resp
 */
private void insert(HttpServletRequest req, HttpServletResponse resp) {
    String userId = req.getParameter("uid");
    String troveId = req.getParameter("tid");
    String freq = req.getParameter("freq");
    String name = req.getParameter("nm");
    String sln = req.getParameter("sln");
    String ssn = req.getParameter("ssn");
    String cln = req.getParameter("cln");
    String csn = req.getParameter("csn");
    String lat = req.getParameter("lat");
    String lng = req.getParameter("lng");
    String nwlat = req.getParameter("nwlat");
    String nwlng = req.getParameter("nwlng");
    String selat = req.getParameter("selat");
    String selng = req.getParameter("selng");
    m_logger.debug(
            name + ',' + ssn + ',' + sln + ',' + csn + ',' + cln + ',' + lat + ',' + lng + ',' + troveId);
    HashMap<String, String> map = new HashMap<String, String>();
    map.put("name", name);
    map.put("state_sn", ssn);
    map.put("state_ln", sln);
    map.put("cntry_sn", csn);
    map.put("cntry_ln", cln);
    map.put("lat", lat);
    map.put("lng", lng);
    map.put("nw_lat", nwlat);
    map.put("nw_lng", nwlng);
    map.put("se_lat", selat);
    map.put("se_lng", selng);
    try {
        int locnId = m_helper.addLocation(userId, troveId, freq, map);
        m_logger.debug("locationFilter locn lookup: ");

        resp.setContentType("text/json");
        PrintWriter pm = resp.getWriter();
        pm.write("{ \"lid\":\"" + locnId + "\" }");
        pm.close();
    } catch (PaperMinerException ex) {
        m_logger.error("insert location/GS records failed", ex);
        req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e306");
    } catch (IOException ex) {
        req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e114");
    }
}

From source file:me.chester.myretweetedtweets.RetrieveTweetsServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String path = request.getPathInfo();
    String callback = request.getParameter("callback");
    PrintWriter out = response.getWriter();
    if (path != null && path.length() > 1) {
        try {//from   ww w .  j  a  va 2 s.  com
            long id = Long.parseLong(path.substring(1));
            String json = getJsonWithCache(id, callback);
            response.setContentType("application/json");
            out.write(json);
            return;
        } catch (NumberFormatException e) {
            // Invalid id, will be treated as 404-not-found below
        } catch (EntityNotFoundException e) {
            // Invalid id, will be treated as 404-not-found below
        } catch (TwitterException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write("Error retrieving tweets. Maybe you should re-authorize?");
        } catch (CacheException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write("Error with Memcache. We are all doomed.");
        }
    }
    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    out.write("Invalid URL. Try authorizing again to get a valid one");
}