Example usage for java.io Writer close

List of usage examples for java.io Writer close

Introduction

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

Prototype

public abstract void close() throws IOException;

Source Link

Document

Closes the stream, flushing it first.

Usage

From source file:com.oauth.servlet.AuthorizationCallbackServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {/* w w  w .j av  a 2 s.c om*/
        System.err.println(req.getQueryString());
        System.err.println(req.getRequestURI());
        String token = null;
        String responseBody = null;
        if (req.getParameter("code") != null) {
            HttpClient httpclient = new DefaultHttpClient();
            String authCode = req.getParameter("code");
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            try {
                if (req.getRequestURI().indexOf("git") > 0) {
                    HttpGet httpget = new HttpGet(client.getAccessTokenUrl(authCode));

                    responseBody = httpclient.execute(httpget, responseHandler);
                    int accessTokenStartIndex = responseBody.indexOf("access_token=")
                            + "access_token=".length();
                    token = responseBody.substring(accessTokenStartIndex,
                            responseBody.indexOf("&", accessTokenStartIndex));

                } else if (req.getRequestURI().indexOf("isam") > 0) {
                    System.err.println(iSAMClient.getAccessTokenUrl());
                    HttpPost httpPost = new HttpPost(iSAMClient.getAccessTokenUrl());
                    httpPost.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");

                    System.err.println("Post Params--------");
                    for (Iterator<NameValuePair> postParamIter = iSAMClient.getPostParams(authCode)
                            .iterator(); postParamIter.hasNext();) {
                        NameValuePair postParam = postParamIter.next();
                        System.err.println(postParam.getName() + "=" + postParam.getValue());
                    }
                    httpPost.setEntity(new UrlEncodedFormEntity(iSAMClient.getPostParams(authCode)));
                    System.err.println("Post Params--------");
                    responseBody = httpclient.execute(httpPost, responseHandler);
                    token = parseJsonString(responseBody);
                } else {
                    resp.sendError(HttpStatus.SC_FORBIDDEN);
                }
                System.err.println(responseBody);
                req.setAttribute("Response", responseBody);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                httpclient.getConnectionManager().shutdown();
            }
            resp.sendRedirect("userDetails.jsp?token=" + token);
        } /*else if(req.getParameter("access_token") != null) {
           Writer w = resp.getWriter();
                    
            w.write("<html><body><center>");
            w.write("<h3>");
            w.write("User Code [" + req.getParameter("access_token") + "] has successfully logged in!");
            w.write("</h3>");
            w.write("</center></body></html>");
                    
            w.flush();
            w.close();   
          } */else {
            Writer w = resp.getWriter();

            w.write("<html><body><center>");
            w.write("<h3>");
            w.write("UNAUTHORIZED Access!");
            w.write("</h3>");
            w.write("</center></body></html>");

            w.flush();
            w.close();
        }

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

From source file:net.officefloor.launch.woof.WoofServletContainerLauncherTest.java

/**
 * Writes the {@link File} (either creating new or overwriting).
 * //from   ww w.j  a va2s . co  m
 * @param directory
 *            Directory to contain the file.
 * @param fileName
 *            {@link File} name.
 * @param fileContent
 *            Content for {@link File}.
 */
private void writeFile(File directory, String fileName, String fileContent) throws IOException {
    Writer writer = new FileWriter(new File(directory, fileName));
    writer.append(fileContent);
    writer.close();
}

From source file:eu.planets_project.tb.gui.backing.exp.utils.ExpTypeWeeUtils.java

/**
 * Builds the currentXMLConfig from the given service/param configuration
 * and writes it to a temporary file that's accessible via an external url ref.
 * This can be used within the browser to download the currentXMLConfig
 * @return//from w ww  . ja  v a2 s .c om
 */
public String getTempFileDownloadLinkForCurrentXMLConfig() {
    if (this.wfConf == null || this.wfConfXML == null) {
        return null;
    }
    //save it's hashcode - for caching purposes
    if ((this.currXMLConfigHashCode != -1) && (this.currXMLConfigHashCode != this.wfConfXML.hashCode())) {
        this.currXMLConfigHashCode = wfConfXML.hashCode();

        try {
            //get a temporary file
            File f = dh.createTempFileInExternallyAccessableDir();
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-8"));
            out.write(wfConfXML);
            out.close();
            currXMLConfigTempFileURI = "" + dh.getHttpFileRef(f);
            return currXMLConfigTempFileURI;
        } catch (Exception e) {
            log.debug("Error getting TempFileDownloadLinkForCurrentXMLConfig " + e);
            return null;
        }
    } else {
        //FIXME: still missing to check if this temp file ref still exists
        //returned the cached object
        return this.currXMLConfigTempFileURI;
    }

}

From source file:com.hortonworks.registries.auth.client.AuthenticatorTestCase.java

protected void _testAuthentication(Authenticator authenticator, boolean doPost) throws Exception {
    start();//ww w .  jav a 2s. co m
    try {
        URL url = new URL(getBaseURL());
        AuthenticatedURL.Token token = new AuthenticatedURL.Token();
        Assert.assertFalse(token.isSet());
        TestConnectionConfigurator connConf = new TestConnectionConfigurator();
        AuthenticatedURL aUrl = new AuthenticatedURL(authenticator, connConf);
        HttpURLConnection conn = aUrl.openConnection(url, token);
        Assert.assertTrue(connConf.invoked);
        String tokenStr = token.toString();
        if (doPost) {
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
        }
        conn.connect();
        if (doPost) {
            Writer writer = new OutputStreamWriter(conn.getOutputStream());
            writer.write(POST);
            writer.close();
        }
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        if (doPost) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String echo = reader.readLine();
            Assert.assertEquals(POST, echo);
            Assert.assertNull(reader.readLine());
        }
        aUrl = new AuthenticatedURL();
        conn = aUrl.openConnection(url, token);
        conn.connect();
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        Assert.assertEquals(tokenStr, token.toString());
    } finally {
        stop();
    }
}

From source file:com.streamsets.datacollector.util.TestConfiguration.java

@Test
public void testFileRefs() throws IOException {
    File dir = new File("target", UUID.randomUUID().toString());
    Assert.assertTrue(dir.mkdirs());/*w w  w .  java  2s. co m*/
    Configuration.setFileRefsBaseDir(dir);

    Writer writer = new FileWriter(new File(dir, "hello.txt"));
    IOUtils.write("secret\nfoo\n", writer);
    writer.close();
    Configuration conf = new Configuration();

    conf.set("a", "@hello.txt@");
    Assert.assertEquals("secret\nfoo\n", conf.get("a", null));

    conf.set("aa", "${file(\"hello.txt\")}");
    Assert.assertEquals("secret\nfoo\n", conf.get("aa", null));

    conf.set("aaa", "${file('hello.txt')}");
    Assert.assertEquals("secret\nfoo\n", conf.get("aaa", null));

    writer = new FileWriter(new File(dir, "config.properties"));
    conf.save(writer);
    writer.close();

    conf = new Configuration();
    Reader reader = new FileReader(new File(dir, "config.properties"));
    conf.load(reader);
    reader.close();

    Assert.assertEquals("secret\nfoo\n", conf.get("a", null));

    reader = new FileReader(new File(dir, "config.properties"));
    StringWriter stringWriter = new StringWriter();
    IOUtils.copy(reader, stringWriter);
    reader.close();
    Assert.assertTrue(stringWriter.toString().contains("@hello.txt@"));
    Assert.assertTrue(stringWriter.toString().contains("${file(\"hello.txt\")}"));
    Assert.assertTrue(stringWriter.toString().contains("${file('hello.txt')}"));
    Assert.assertFalse(stringWriter.toString().contains("secret\nfoo\n"));
}

From source file:de.hybris.platform.atddengine.ant.tasks.GenerateProxies.java

private void generateJUnitProxy(final File packageDir, final File testSuiteFile) throws IOException {
    try {/*from w  w w  .  ja  v a2s .c o m*/
        final RobotTestSuite robotTestSuite = getRobotTestSuiteFactory().parseTestSuite(testSuiteFile);

        final String testSuiteName = robotTestSuite.getName().replaceAll(Pattern.quote(" "), "_");

        final Map<String, Object> binding = new HashMap<String, Object>();

        binding.put("packageName",
                rootPackagePath.replaceAll(Pattern.quote("/"), ".") + "." + packageDir.getName());
        binding.put("testSuiteName", testSuiteName);
        binding.put("testSuitePath", testSuiteFile.getPath().replaceAll(Pattern.quote(File.separator), "/"));
        binding.put("projectName", packageDir.getName());

        final List<String> testNames = new ArrayList<String>();

        for (final RobotTest robotTest : robotTestSuite.getRobotTests()) {
            testNames.add(robotTest.getName());
        }

        binding.put("testNames", testNames);

        final File targetFile = new File(packageDir, testSuiteName + ".java");

        final TemplateProcessor templateProcessor = getTemplateProcessorFactory().createTemplateProcessor();

        final Writer writer = new FileWriter(targetFile);
        templateProcessor.processTemplate(writer, templateFile.getName(), binding);
        writer.close();
    } catch (final PyException e) {
        LOG.warn(String.format("Test suite file [%s] is malformed and will be ignored.",
                testSuiteFile.getName()));
    }
}

From source file:de.uzk.hki.da.at.ATUseCaseAudit.java

private void destroyFileInCIEnvironment(String identifier) {

    File file = Path.makeFile(archiveStoragePath, identifier, identifier + ".pack_1.tar");
    if (!file.exists()) {
        fail(file + " does not exist!");
    }/*  w  w  w  .  j a  v a2s  . com*/
    Writer writer = null;
    try {
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
        writer.write("Something");
    } catch (IOException ex) {
        fail("writing to file");
    } finally {
        try {
            writer.close();
        } catch (Exception ex) {
            fail();
        }
    }

}

From source file:org.openmrs.module.dataexchange.web.controller.DataExchangeController.java

@RequestMapping(value = "/import", method = RequestMethod.POST)
public void importData(@RequestParam("file") MultipartFile file, Model model) throws IOException {
    Writer writer = null;
    File tempFile = null;/* w  w w .  j a  v  a 2s. co m*/
    try {
        tempFile = File.createTempFile("concepts", ".xml");
        writer = new OutputStreamWriter(new FileOutputStream(tempFile), "UTF-8");
        IOUtils.copy(file.getInputStream(), writer, "UTF-8");
        writer.close();

        dataImporter.importData(tempFile.getPath());
    } finally {
        IOUtils.closeQuietly(writer);
        if (tempFile != null) {
            tempFile.delete();
        }
    }

    model.addAttribute("success", true);
}

From source file:de.innovationgate.wgpublisher.design.fs.FileSystemDesignProvider.java

private static void resourceInToOut(InputStream in, String sourceEncoding, OutputStream out,
        String targetEncoding) throws UnsupportedEncodingException, IOException {
    if (sourceEncoding != null && targetEncoding != null) {
        Reader inReader = new InputStreamReader(in, sourceEncoding);
        Writer outWriter = new OutputStreamWriter(out, targetEncoding);
        WGUtils.inToOut(inReader, outWriter, 4096);
        inReader.close();//from   w w  w .j a va  2  s.  c  o m
        outWriter.flush();
        outWriter.close();
    } else {
        WGUtils.inToOut(in, out, 4096);
        in.close();
        out.flush();
        out.close();
    }
}

From source file:com.kysoft.cpsi.audit.controller.SelfCheckAjaxUploadController.java

/**
 * /*  w  ww .ja  v a 2  s  .c  o m*/
 * @param response
 * @param state
 */
@SuppressWarnings("unused")
private void responseMessage(HttpServletResponse response, State state) {
    response.setCharacterEncoding(HuskyConstants.ENCODING_UTF8);
    response.setContentType("text/html; charset=UTF-8");
    Writer writer = null;
    try {
        writer = response.getWriter();
        writer.write("{\"code\":" + state.getCode() + ",\"message\":\"" + state.getMessage() + "\"}");
        writer.flush();
        writer.close();
    } catch (Exception e) {
    } finally {
        IOUtils.closeQuietly(writer);
    }
}