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:edu.vt.vbi.patric.cache.ENewsGenerator.java

public boolean createCacheFile(String filePath) {

    boolean isSuccess = false;

    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {

        HttpGet httpRequest = new HttpGet(sourceURL);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String strResponseBody = client.execute(httpRequest, responseHandler);

        if (strResponseBody.length() > 0) {
            PrintWriter enewsOut = new PrintWriter(new FileWriter(filePath));
            enewsOut.println(strResponseBody);
            enewsOut.close();
        }/*  ww  w .j  a  v a2s  .c o m*/
        isSuccess = true;
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }
    return isSuccess;
}

From source file:com.jfinal.weixin.sdk.jfinal.MsgInterceptor.java

public void writeText(HttpServletResponse response, String text) {
    response.setContentType("text/x-json;charset=utf-8");
    response.setHeader("Cache-Control", "no-store, max-age=0, no-cache, must-revalidate");
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    response.setHeader("Pragma", "no-cache");
    try {/*from   w  ww.  j  ava  2  s .c om*/
        PrintWriter out = response.getWriter();
        out.write(text);
        out.close();
    } catch (IOException e) {
        logger.error("error write json data", e);
    }
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step7bConvArgRankProducer.java

@SuppressWarnings("unchecked")
public static void prepareData(String[] args) throws Exception {
    String inputDir = args[0];//w ww  . jav a 2 s .  c om
    File outputDir = new File(args[1]);

    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }

    List<File> files = IOHelper.listXmlFiles(new File(inputDir));

    // take only the gold data for this task
    String prefix = "all_DescendingScoreArgumentPairListSorter";
    Iterator<File> iterator = files.iterator();
    while (iterator.hasNext()) {
        File file = iterator.next();

        if (!file.getName().startsWith(prefix)) {
            iterator.remove();
        }
    }

    int totalArgumentsCounter = 0;

    DescriptiveStatistics statsPerTopic = new DescriptiveStatistics();

    for (File file : files) {
        List<AnnotatedArgumentPair> argumentPairs = (List<AnnotatedArgumentPair>) XStreamTools.getXStream()
                .fromXML(file);

        String name = file.getName().replaceAll(prefix, "").replaceAll("\\.xml", "");

        PrintWriter pw = new PrintWriter(new File(outputDir, name + ".csv"), "utf-8");
        pw.println("#id\trank\targument");

        Graph graph = buildGraphFromPairs(argumentPairs);

        Map<String, Argument> arguments = collectArguments(argumentPairs);

        int argumentsPerTopicCounter = arguments.size();

        PageRank pageRank = new PageRank();
        pageRank.setVerbose(true);
        pageRank.init(graph);

        for (Node node : graph) {
            String id = node.getId();
            double rank = pageRank.getRank(node);

            System.out.println(id);

            Argument argument = arguments.get(id);

            String text = Step7aLearningDataProducer.multipleParagraphsToSingleLine(argument.getText());

            pw.printf(Locale.ENGLISH, "%s\t%.5f\t%s%n", argument.getId(), rank, text);
        }

        totalArgumentsCounter += argumentsPerTopicCounter;
        statsPerTopic.addValue(argumentsPerTopicCounter);

        pw.close();
    }

    System.out.println("Total gold arguments: " + totalArgumentsCounter);
    System.out.println(statsPerTopic);
}

From source file:dk.dbc.DevelMain.java

@Override
public void run(OaiSetMatcherConfiguration config, Environment env) throws Exception {
    super.run(config, env);
    env.admin().addTask(new Task("terminate") {
        @Override/* ww  w  .j av  a2s. c  o  m*/
        public void execute(ImmutableMultimap<String, String> im, PrintWriter writer) throws Exception {
            writer.append("EXITTING\n");
            writer.close();
            new Thread() {
                @Override
                @SuppressFBWarnings(value = "DM_EXIT", justification = "It's intentional that the system should exit on a 'terminate' call")
                public void run() {
                    log.info("EXITTING");
                    System.exit(0);
                }
            }.start();
        }
    });
}

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

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

    String itemId = request.getParameter("id");

    psItemDAO.delete(psItemDAO.findById(Integer.parseInt(itemId)));

    PrintWriter out = response.getWriter();
    out.write("success");
    out.flush();//from www. ja  v  a 2  s  .c  o m
    out.close();

}

From source file:de.tudarmstadt.ukp.dkpro.core.api.resources.CompressionUtilsTest.java

@Test
public void testPrintWriter() throws IOException {
    CompressionMethod compressionMethod = CompressionMethod.XZ;
    String text = StringUtils.repeat("This is a test. ", 100000);
    File file = new File("compressed" + compressionMethod.getExtension());
    PrintWriter printWriter = new PrintWriter(CompressionUtils.getOutputStream(file));

    printWriter.write(text);//from ww  w  .  j a  v  a  2  s. co  m
    printWriter.close();

    InputStream is = CompressionUtils.getInputStream(file.getPath(), new FileInputStream(file));
    assertEquals(text, IOUtils.toString(is));
    is.close();
    file.delete();
}

From source file:de.undercouch.gradle.tasks.download.ContentEncodingTest.java

@Override
protected Handler[] makeHandlers() throws IOException {
    ContextHandler contentEncodingHandler = new ContextHandler("/" + CONTENT_ENCODING) {
        @Override//from w w  w  .j a va 2s  .com
        public void handle(String target, HttpServletRequest request, HttpServletResponse response,
                int dispatch) throws IOException, ServletException {
            response.setStatus(200);
            if (contentEncoding != null) {
                response.setHeader("Content-Encoding", contentEncoding);
            }
            PrintWriter rw = response.getWriter();
            rw.write("ce: " + String.valueOf(contentEncoding));
            rw.close();
        }
    };
    return new Handler[] { contentEncodingHandler };
}

From source file:com.microsoftopentechnologies.intellij.helpers.AndroidStudioHelper.java

public static void newActivityTemplateManager() throws IOException, InterruptedException {
    String[] cmd = null;//w  ww  .  jav  a2 s  . c o m

    String templatePath = URLDecoder
            .decode(ApplicationComponent.class.getResource("").getPath().replace("file:/", ""), "UTF-8");
    templatePath = templatePath.replace("/", File.separator);
    templatePath = templatePath.substring(0, templatePath.indexOf(File.separator + "lib"));
    templatePath = templatePath + File.separator + "plugins" + File.separator + "android" + File.separator;
    templatePath = templatePath + "lib" + File.separator + "templates" + File.separator + "activities"
            + File.separator;

    String[] env = null;

    if (!new File(templatePath + mobileServicesTemplateName).exists()) {
        String tmpdir = getTempLocation();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(
                ServiceCodeReferenceHelper.getTemplateResource("ActivityTemplate.zip"));
        unZip(bufferedInputStream, tmpdir);

        if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
            try {
                copyFolder(new File(tmpdir + mobileServicesTemplateName),
                        new File(templatePath + mobileServicesTemplateName));
                copyFolder(new File(tmpdir + officeTemplateName), new File(templatePath + officeTemplateName));
            } catch (IOException ex) {
                PrintWriter printWriter = new PrintWriter(tmpdir + "\\script.bat");
                printWriter.println("@echo off");
                printWriter.println("md \"" + templatePath + mobileServicesTemplateName + "\"");
                printWriter.println("md \"" + templatePath + officeTemplateName + "\"");
                printWriter.println("xcopy \"" + tmpdir + mobileServicesTemplateName + "\" \"" + templatePath
                        + mobileServicesTemplateName + "\" /s /i /Y");
                printWriter.println("xcopy \"" + tmpdir + officeTemplateName + "\" \"" + templatePath
                        + officeTemplateName + "\" /s /i /Y");
                printWriter.flush();
                printWriter.close();

                String[] tmpcmd = { tmpdir + "\\elevate.exe", "script.bat", "1" };

                cmd = tmpcmd;

                ArrayList<String> tempenvlist = new ArrayList<String>();
                for (String envval : System.getenv().keySet())
                    tempenvlist.add(String.format("%s=%s", envval, System.getenv().get(envval)));

                tempenvlist.add("PRECOMPILE_STREAMLINE_FILES=1");
                env = new String[tempenvlist.size()];
                tempenvlist.toArray(env);

                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec(cmd, env, new File(tmpdir));
                proc.waitFor();

                //wait for elevate command to finish
                Thread.sleep(3000);

                if (!new File(templatePath + mobileServicesTemplateName).exists())
                    UIHelper.showException(
                            "Error copying template files. Please refer to documentation to copy manually.",
                            new Exception());
            }
        } else {
            if (System.getProperty("os.name").toLowerCase().startsWith("mac")) {

                String[] strings = { "osascript",
                        //        "-e",
                        //        "do shell script \"mkdir -p \\\"/" + templatePath + mobileServicesTemplateName + "\\\"\"",
                        //        "-e",
                        //        "do shell script \"mkdir -p \\\"/" + templatePath + officeTemplateName + "\\\"\"",
                        "-e",
                        "do shell script \"cp -Rp \\\"" + tmpdir + mobileServicesTemplateName + "\\\" \\\"/"
                                + templatePath + "\\\"\"",
                        "-e", "do shell script \"cp -Rp \\\"" + tmpdir + officeTemplateName + "\\\" \\\"/"
                                + templatePath + "\\\"\"" };

                exec(strings, tmpdir);
            } else {
                try {

                    copyFolder(new File(tmpdir + mobileServicesTemplateName),
                            new File(templatePath + mobileServicesTemplateName));
                    copyFolder(new File(tmpdir + officeTemplateName),
                            new File(templatePath + officeTemplateName));

                } catch (IOException ex) {

                    JPasswordField pf = new JPasswordField();
                    int okCxl = JOptionPane.showConfirmDialog(null, pf,
                            "To copy Microsoft Services templates, the plugin needs your password:",
                            JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

                    if (okCxl == JOptionPane.OK_OPTION) {
                        String password = new String(pf.getPassword());

                        exec(new String[] { "echo", password, "|", "sudo", "-S", "cp", "-Rp",
                                tmpdir + mobileServicesTemplateName,
                                templatePath + mobileServicesTemplateName }, tmpdir);

                        exec(new String[] { "echo", password, "|", "sudo", "-S", "cp", "-Rp",
                                tmpdir + officeTemplateName, templatePath + officeTemplateName }, tmpdir);
                    }
                }
            }
        }
    }
}

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

@RequestMapping(value = "/seller/addAd", method = RequestMethod.POST)
public void getItems(HttpServletRequest request, HttpServletResponse response)
        throws ParseException, IOException {

    String name = request.getParameter("adName");
    String itemId = request.getParameter("itemId");
    String startDate = request.getParameter("start");
    String endDate = request.getParameter("end");
    String weight = request.getParameter("weight");
    String description = request.getParameter("description");
    String picUrl = request.getParameter("pic-url");

    System.out.println(//from   www  .j a  v a  2 s  .c  o m
            name + ": " + itemId + ";" + startDate + ";" + endDate + "; " + weight + ";" + description);

    PsItem $ = psItemDao.findById(Integer.parseInt(itemId));
    SimpleDateFormat FMT = new SimpleDateFormat("yyyy-MM-dd");

    PsPromotItem pi = new PsPromotItem();
    pi.setPsItem($);
    pi.setDescription(description);
    pi.setTimeCreated(new Timestamp(System.currentTimeMillis()));
    pi.setPicUrl(picUrl);
    psPromotItemDAO.save(pi);

    PsAdItem ad = new PsAdItem();
    ad.setIdPromot(pi.getId());
    ad.setTimeStart(new Timestamp(FMT.parse(startDate).getTime()));
    ad.setTimeEnd(new Timestamp(FMT.parse(endDate).getTime()));
    ad.setWeight(Double.parseDouble(weight));

    psAdItemDAO.save(ad);

    PrintWriter out = response.getWriter();
    out.write("success");
    out.flush();
    out.close();
}

From source file:net.morphbank.webclient.ProcessFiles.java

public void processRequest(String url, String xmlFilename, String responseFilename) throws Exception {
    PrintWriter out = new PrintWriter(new FileWriter(responseFilename));
    InputStream response = post(url, xmlFilename, out);
    out.close();
}