Example usage for java.io PrintWriter close

List of usage examples for java.io PrintWriter close

Introduction

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

Prototype

public void close() 

Source Link

Document

Closes the stream and releases any system resources associated with it.

Usage

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 w  w  w .j  a  va  2  s.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:model.settings.ReadSettings.java

/**
 * Set up paint as program in OSX./* ww w . j a  va  2s.  c  om*/
 */
private static void installLinux() {

    /*
     * setting up "open with" links for paint.
     * Therefore request SUDO rights.
     */
    try {

        final String userHome = System.getProperty("user.home");
        final String localDest = userHome + "/paint.desktop";
        final String finalDest = "/usr/share/applications/paint.desktop";
        Util.exportResource("/res/files/paint.desktop", localDest);

        String passwd = "";

        /*
         * Check whether the execution was successfully (and the password
         * was correct) or the file already exists
         */
        while (!new File(finalDest).exists()) {

            /*
             * Request SUDO privileges.
             */
            passwd = Util.requestSudoRights("mv " + localDest + " " + finalDest);

            if (passwd.equals("")) {
                JOptionPane.showMessageDialog(null, "installation failed due to lack of privileges.");
                return;
            }

            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        /*
         * Copy jar file
         */

        /////////////////////////Path for jar file.///////////////////
        // /usr/lib/paint/paint.jar requests sudo rights.
        // because of this, each time an update is done these rights 
        // have to be requested. Thus chose another path:
        // ~/.PaintUni/paint.jar
        // (PROGRAM_LOCATION/paint.jar)

        /*
         * STEP 2:   Create (executable) file which is called if the 
         *          application is run.
         */

        final String dest_jar_file = PROGRAM_LOCATION + "paint.jar";
        final String dest_exec = "/usr/bin/paint";
        String orig_jar_file = URLDecoder.decode(ClassLoader.getSystemClassLoader().getResource(".").getPath(),
                "UTF-8");

        // if Eclipse on-the-fly-compiling
        final String eclipseSubstring = "target/classes/";
        if (orig_jar_file.endsWith(eclipseSubstring)) {
            orig_jar_file = orig_jar_file.substring(0, orig_jar_file.length() - eclipseSubstring.length());

        }
        orig_jar_file += "paint.jar";

        /*
         * Step 3:   Copy .jar file to the destination.
         */
        try {
            Files.copy(Paths.get(orig_jar_file), Paths.get(dest_jar_file),
                    java.nio.file.StandardCopyOption.REPLACE_EXISTING);

        } catch (IOException e) {

            final String command1 = "cp " + "\"" + orig_jar_file + "\"" + " " + "\"" + dest_jar_file + "\"";
            String ret1 = Util.executeCommandLinux(command1);
            System.out.println(command1 + "" + ret1);
        }

        final String content = "#!/bin/bash \n" + "java -jar " + dest_jar_file + " $1";

        // rather dirty solution. Creating a temporary file which is copied
        // to another location which requests sudoer rights.
        // If the temporary file already exists, randomly change the name.
        String temporaryLocation = userHome + "/paint_tmp_0123";
        while (new File(temporaryLocation).exists()) {
            temporaryLocation += "" + new Random().nextInt(10);
        }

        PrintWriter writer = new PrintWriter(temporaryLocation, "UTF-8");
        writer.println(content);
        writer.close();

        final String command = "mv " + temporaryLocation + " " + dest_exec;
        Util.execSudoCommand(command, passwd);
        // if the password was not correct / no sudo rights
        if (!new File(dest_exec).exists()) {
            while (!new File(dest_exec).exists()) {

                /*
                 * Request SUDO privileges.
                 */
                passwd = Util.requestSudoRights(command);

                if (passwd.equals("")) {
                    JOptionPane.showMessageDialog(null, "installation failed due to lack of privileges.");
                    return;
                }

                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        Util.execSudoCommand("chmod a+x " + dest_exec, passwd);

    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:ch.epfl.lsir.xin.algorithm.baseline.GlobalAverage.java

@Override
public void saveModel(String file) {
    // TODO Auto-generated method stub
    try {//  w w  w  . jav  a 2  s  .  c  o m
        PrintWriter printer = new PrintWriter(file);
        printer.println(this.mean);
        printer.flush();
        printer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.xmarts.ringingPayroll.rpf_process.Ring.java

private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strKey, String windowId,
        String strTab, String strProcessId, String strPath, String strPosted, String strFilePath,
        String strDocNo) throws IOException, ServletException {
    if (log4j.isDebugEnabled())
        log4j.debug("Output: Button process Ring Electronic Invoice");
    //System.out.println("metodo prong");
    String[] discard = { "" };
    XmlDocument xmlDocument = xmlEngine.readXmlTemplate("com/xmarts/ringingPayroll/rpf_process/Ring", discard)
            .createXmlDocument();// w w w. j a  va2s  . c  o m
    xmlDocument.setParameter("key", strKey);
    xmlDocument.setParameter("window", windowId);
    xmlDocument.setParameter("tab", strTab);
    xmlDocument.setParameter("processed", strProcessId);
    xmlDocument.setParameter("path", strPath);
    xmlDocument.setParameter("posted", strPosted);
    xmlDocument.setParameter("docNo", strDocNo);

    {
        OBError myMessage = vars.getMessage("Ring");
        vars.removeMessage("Ring");
        if (myMessage != null) {
            xmlDocument.setParameter("messageType", myMessage.getType());
            xmlDocument.setParameter("messageTitle", myMessage.getTitle());
            xmlDocument.setParameter("messageMessage", myMessage.getMessage());
        }
    }

    xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
    xmlDocument.setParameter("directory", "var baseDirectory = \"" + strReplaceWith + "/\";\n");
    xmlDocument.setParameter("theme", vars.getTheme());
    xmlDocument.setParameter("rpfPayrollId", strKey);

    if (!strFilePath.equals("")) {
        xmlDocument.setParameter("inpFilePath", strFilePath);
        xmlDocument.setParameter("inpOnLoad", "onLoadClose();");
    }
    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println(xmlDocument.print());
    out.close();
}

From source file:de.shadowhunt.sonar.plugins.ignorecode.batch.IgnoreCoverageDecoratorTest.java

@Test
public void testDecorateAllLines() throws Exception {
    final java.io.File configFile = temporaryFolder.newFile("coverage.txt");
    final PrintWriter writer = new PrintWriter(configFile);
    writer.println("src/java/net/example/Foo.java;*");
    writer.close();

    final Configuration configuration = Mockito.mock(Configuration.class);
    Mockito.when(configuration.getString(IgnoreCoverageDecorator.CONFIG_FILE))
            .thenReturn(configFile.getAbsolutePath());

    final IgnoreCoverageDecorator decorator = new IgnoreCoverageDecorator(configuration);

    final org.sonar.api.resources.File file = org.sonar.api.resources.File
            .create("src/java/net/example/Foo.java");
    final DecoratorContext context = Mockito.mock(DecoratorContext.class);
    decorator.decorate(file, context);//from  www  . j av  a  2 s .  c om
}

From source file:mack.servlets.TransfServlet.java

private void geraXSL() throws IOException {
    HttpClient cliente = HttpClients.createDefault();
    HttpGet httpget = new HttpGet("http://localhost:8081/AppFrontController/dados/gpx.xsl");
    HttpResponse resposta = cliente.execute(httpget);
    System.out.println("----------------------------------------");
    System.out.println(resposta.getStatusLine());
    HttpEntity entity = resposta.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
        StringBuilder out = new StringBuilder();
        String line;/*www. j  a  v  a  2 s.  c o m*/
        while ((line = reader.readLine()) != null) {
            out.append(line);
        }
        PrintWriter w = new PrintWriter("/temp/gpx.xsl");
        w.print(out.toString());
        w.flush();
        w.close();
        reader.close();
        instream.close();
    }

}

From source file:com.norconex.collector.core.AbstractCollectorLauncher.java

public void launch(String[] args) {
    CommandLine cmd = parseCommandLineArguments(args);
    String action = cmd.getOptionValue(ARG_ACTION);
    File configFile = new File(cmd.getOptionValue(ARG_CONFIG));
    File varFile = null;/*from   w w  w. j ava 2  s  .  c  om*/
    if (cmd.hasOption(ARG_VARIABLES)) {
        varFile = new File(cmd.getOptionValue(ARG_VARIABLES));
    }

    try {
        if (!configFile.isFile()) {
            System.err.println("Invalid configuration file path: " + configFile.getAbsolutePath());
            System.exit(-1);
        }
        if (varFile != null && !varFile.isFile()) {
            System.err.println("Invalid variable file path: " + configFile.getAbsolutePath());
            System.exit(-1);
        }

        ICollectorConfig config = new CollectorConfigLoader(getCollectorConfigClass())
                .loadCollectorConfig(configFile, varFile);
        ICollector collector = createCollector(config);
        if (ARG_ACTION_START.equalsIgnoreCase(action)) {
            collector.start(false);
        } else if (ARG_ACTION_RESUME.equalsIgnoreCase(action)) {
            collector.start(true);
        } else if (ARG_ACTION_STOP.equalsIgnoreCase(action)) {
            collector.stop();
        }
    } catch (Exception e) {
        PrintStream err = System.err;
        File errorFile = new File("./error-" + System.currentTimeMillis() + ".log");
        err.println("\n\nAn ERROR occured:\n\n" + e.getLocalizedMessage());
        err.println("\n\nDetails of the error has been stored at: " + errorFile.getAbsolutePath() + "\n\n");
        try {
            PrintWriter w = new PrintWriter(errorFile, CharEncoding.UTF_8);
            e.printStackTrace(w);
            w.flush();
            w.close();
        } catch (FileNotFoundException | UnsupportedEncodingException e1) {
            err.println("\n\nCannot write error file. " + e1.getLocalizedMessage());
        }
        System.exit(-1);
    }
}

From source file:org.openmrs.module.retrosecurity.advice.PatientServiceAdvice.java

private void writeFile(String st) throws IOException {
    PrintWriter writer = new PrintWriter(logFilePath, "UTF-8");
    writer.println(st);//from   w w w  . jav a2 s.c  o m
    writer.close();
}

From source file:jp.aegif.liferay.experiment.mryoshio.rr.RoomPortlet.java

@Override
public void serveResource(ResourceRequest req, ResourceResponse res) throws IOException, PortletException {

    if (logger.isDebugEnabled())
        debug(req);/*from www.j  ava 2  s  .co m*/

    try {
        String rid = req.getResourceID();
        PortletBag pbag = PortletBagPool.get(PortalUtil.getPortletId(req));
        String ajaxResponse = null;

        if ("add-view".equals(rid) || "update-view".equals(rid)) {
            ajaxResponse = PortalUtil.renderPage(pbag.getServletContext(),
                    PortalUtil.getHttpServletRequest(req), PortalUtil.getHttpServletResponse(res), editJSP,
                    false);
        } else if ("list-view".equals(rid)) {
            ajaxResponse = getListDataAsJson(Integer.parseInt(req.getParameter("itemPerPage")),
                    Integer.parseInt(req.getParameter("targetPage")));
        } else if ("update-room".equals(rid)) {
            updateRoom(req);
        } else if ("delete-room".equals(rid)) {
            deleteRoom(req);
        } else {
            ajaxResponse = ERR_NO_TYPE_SPECIFIED;
        }
        PrintWriter writer = res.getWriter();
        writer.write(ajaxResponse);
        writer.flush();
        writer.close();
    } catch (ServletException e) {
        throw new PortletException(e);
    }
}