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.moss.appsnap.keeper.windows.MSWindowsDesktopIntegrationStrategy.java

public void startLocalApiServer(final ApiMessageHandler handler) {
    try {//from   ww w .j  av  a2s.  c om
        {
            if (!snapFsLayout.portFile.exists() && !snapFsLayout.portFile.createNewFile()) {
                throw new RuntimeException("Could not create file: " + snapFsLayout.portFile.getAbsolutePath());
            }
            snapFsLayout.portFile.deleteOnExit();
            Writer w = new FileWriter(snapFsLayout.portFile);
            w.write(Integer.toString(KEEPER_LOCAL_PORT));
            w.close();
        }
        final ServerSocket server = new ServerSocket(KEEPER_LOCAL_PORT);//, 0, InetAddress.getLocalHost());

        new Thread("Local API Server Thread") {
            public void run() {
                while (true) {
                    try {
                        log.info("Waiting for local connection.");
                        Socket s = server.accept();
                        log.info("Connection established.");
                        handler.handle(new SocketMessageConnection(s));
                        log.info("Done");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

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

From source file:java2typescript.jackson.module.StaticFieldExporterTest.java

@Test
public void testTypeScriptDefinition() throws IOException, IllegalArgumentException {
    Writer out = new StringWriter();

    ArrayList<Class<?>> classesToConvert = new ArrayList<Class<?>>();
    classesToConvert.add(TestClass.class);

    Module module = new Module("mod");
    new StaticFieldExporter(module, null).export(classesToConvert);

    module.write(out);/* w w  w. ja v a  2  s  .  c o  m*/

    out.close();
    final String result = out.toString();
    System.out.println(result);
    assertTrue(result.contains("export class TestClassStatic"));
    assertTrue(result.contains("export enum ChangedEnumName"));
    assertTrue(result.contains("static MY_CONSTANT_STRING: string = 'Test';"));
    assertTrue(result.contains(
            "static MY_CONSTANT_ENUM_ARRAY_2: ChangedEnumName[] = [ ChangedEnumName.VAL1, ChangedEnumName.VAL2 ];"));
    assertFalse(result.contains("doNotExportAsStatic"));
}

From source file:com.tollefoto.tetravex.HighscoreJSONSerializer.java

public void saveHighscores(ArrayList<Highscore> highscores) throws JSONException, IOException {
    JSONArray jarray = new JSONArray();
    for (Highscore hs : highscores)
        jarray.put(hs.toJSON());/* w w w . j  a v a  2  s . c o m*/

    Writer writer = null;
    try {
        OutputStream outStream = getContext().openFileOutput(getFilename(), Context.MODE_PRIVATE);
        writer = new OutputStreamWriter(outStream);
        writer.write(jarray.toString());
    } finally {
        if (writer != null)
            writer.close();
    }
}

From source file:cn.vlabs.duckling.vwb.ui.action.EditPageAction.java

private void writeToResponse(HttpServletResponse response, String xml) {
    response.setContentType("text/html;charset=UTF-8");
    try {/*from w  w w  . ja v a  2  s.c  o m*/
        //String output = "<result>" + xml + "</result>";
        Writer wr = response.getWriter();
        wr.write(xml);
        wr.close();
    } catch (IOException e) {
        log.debug("Write xml to response error!", e);
    }
}

From source file:android.security.cts.BrowserTest.java

/**
 * See Bug 6212665 for detailed information about this issue.
 */// w w  w .  ja  v  a2  s .com
public void testBrowserPrivateDataAccess() throws Throwable {

    // Create a list of all intents for http display. This includes all browsers.
    List<Intent> intents = createAllIntents(Uri.parse("http://www.google.com"));
    String action = "\"" + mWebServer.getBaseUri() + "/\"";
    // test each browser
    for (Intent intent : intents) {
        // reset state
        mWebServer.resetRequestState();
        // define target file, which is supposedly protected from this app
        String targetFile = "file://" + getTargetFilePath();
        String html = "<html><body>\n" + "  <form name=\"myform\" action=" + action + " method=\"post\">\n"
                + "  <input type='text' name='val'/>\n"
                + "  <a href=\"javascript :submitform()\">Search</a></form>\n" + "<script>\n"
                + "  var client = new XMLHttpRequest();\n" + "  client.open('GET', '" + targetFile + "');\n"
                + "  client.onreadystatechange = function() {\n" + "  if(client.readyState == 4) {\n"
                + "    myform.val.value = client.responseText;\n" + "    document.myform.submit(); \n"
                + "  }}\n" + "  client.send();\n" + "</script></body></html>\n";
        String filename = "jsfileaccess.html";
        // create a local HTML to access protected file
        FileOutputStream out = mContext.openFileOutput(filename, mContext.MODE_WORLD_READABLE);
        Writer writer = new OutputStreamWriter(out, "UTF-8");
        writer.write(html);
        writer.flush();
        writer.close();

        String filepath = mContext.getFileStreamPath(filename).getAbsolutePath();
        Uri uri = Uri.parse("file://" + filepath);
        // do a file request
        intent.setData(uri);
        mContext.startActivity(intent);
        /*
         * Wait 5 seconds for the browser to contact the server, but
         * fail fast if we detect the bug
         */
        for (int j = 0; j < 5; j++) {
            // it seems that even when cross-origin policy prevents a file
            // access, browser is still doing a POST sometimes, but it just
            // sends the query part and no private data. Make sure this does not
            // cause a false alarm.
            if (mWebServer.getRequestEntities().size() > 0) {
                int len = 0;
                for (HttpEntity entity : mWebServer.getRequestEntities()) {
                    len += entity.getContentLength();
                }
                final int queryLen = "val=".length();
                assertTrue("Failed preventing access to private data", len <= queryLen);
            }
            Thread.sleep(1000);
        }
    }
}

From source file:net.ontopia.topicmaps.core.OccurrenceTest.java

public void testReader() throws Exception {
    // read file and store in object
    File filein = TestFileUtils.getTransferredTestInputFile("various", "clob.xml");
    File fileout = TestFileUtils.getTestOutputFile("various", "clob.xml.out");

    long inlen = filein.length();
    Reader ri = new FileReader(filein);
    try {//w  ww.  ja v  a2  s.  c o m
        occurrence.setReader(ri, inlen, DataTypes.TYPE_BINARY);
    } finally {
        try {
            ri.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        ;
    }
    assertTrue("Occurrence datatype is incorrect",
            Objects.equals(DataTypes.TYPE_BINARY, occurrence.getDataType()));

    // read and decode content
    Reader ro = occurrence.getReader();
    try {
        Writer wo = new FileWriter(fileout);
        try {
            IOUtils.copy(ro, wo);
        } finally {
            wo.close();
        }
    } finally {
        ro.close();
    }
    assertTrue("Reader value is null", ro != null);
    try {
        ri = new FileReader(filein);
        ro = new FileReader(fileout);
        long outlen = occurrence.getLength();
        try {
            assertTrue("Occurrence value put in is not the same as the one we get out.",
                    IOUtils.contentEquals(ro, ri));
            assertTrue("Occurrence value length is different", inlen == outlen);
        } finally {
            ri.close();
        }
    } finally {
        ro.close();
    }
}

From source file:fedora.utilities.install.Installer.java

private File buildWAR() throws InstallationFailedException {
    String fedoraWarName = _opts.getValue(InstallOptions.FEDORA_APP_SERVER_CONTEXT);
    System.out.println("Preparing " + fedoraWarName + ".war...");
    // build a staging area in FEDORA_HOME
    try {//  www  .j a va 2s  .c  o m
        File warStage = new File(installDir, "fedorawar" + File.separator);
        warStage.mkdirs();
        Zip.unzip(_dist.get(Distribution.FEDORA_WAR), warStage);

        // modify web.xml
        System.out.println("Processing web.xml");
        File distWebXML = new File(warStage, "WEB-INF/web.xml");
        FedoraWebXML webXML = new FedoraWebXML(distWebXML.getAbsolutePath(), _opts);
        Writer outputWriter = new BufferedWriter(new FileWriter(distWebXML));
        webXML.write(outputWriter);
        outputWriter.close();

        // Remove commons-collections, commons-dbcp, and commons-pool
        // from fedora.war if using Tomcat 5.0
        String container = _opts.getValue(InstallOptions.SERVLET_ENGINE);
        File webinfLib = new File(warStage, "WEB-INF/lib/");
        if (container.equals(InstallOptions.INCLUDED) || container.equals(InstallOptions.EXISTING_TOMCAT)) {
            File tomcatHome = new File(_opts.getValue(InstallOptions.TOMCAT_HOME));
            File dbcp55 = new File(tomcatHome, "common/lib/naming-factory-dbcp.jar");
            File dbcp6 = new File(tomcatHome, "lib/tomcat-dbcp.jar");

            if (!dbcp55.exists() && !dbcp6.exists()) {
                new File(webinfLib, Distribution.COMMONS_COLLECTIONS).delete();
                new File(webinfLib, Distribution.COMMONS_DBCP).delete();
                new File(webinfLib, Distribution.COMMONS_POOL).delete();
                // JDBC driver installation into common/lib for Tomcat 5.0 is
                // handled by ExistingTomcat50
            } else {
                installJDBCDriver(_dist, _opts, webinfLib);
            }
        } else {
            installJDBCDriver(_dist, _opts, webinfLib);
        }

        // Remove log4j if using JBoss Application Server
        if (container.equals(InstallOptions.OTHER)
                && _opts.getValue(InstallOptions.USING_JBOSS).equals("true")) {
            new File(webinfLib, Distribution.LOG4J).delete();
        }

        // FeSL configuration
        if (_opts.getBooleanValue(InstallOptions.FESL_ENABLED, false)) {
            File originalWsdd = new File(warStage, "WEB-INF/server-config.wsdd");
            originalWsdd.renameTo(new File(warStage, "WEB-INF/server-config.wsdd.backup.original"));

            File feslWsdd = new File(warStage, "WEB-INF/melcoe-pep-server-config.wsdd");
            feslWsdd.renameTo(new File(warStage, "WEB-INF/server-config.wsdd"));
        }

        File fedoraWar = new File(installDir, fedoraWarName + ".war");
        Zip.zip(fedoraWar, warStage.listFiles());
        return fedoraWar;

    } catch (FileNotFoundException e) {
        throw new InstallationFailedException(e.getMessage(), e);
    } catch (IOException e) {
        throw new InstallationFailedException(e.getMessage(), e);
    }
}

From source file:net.ontopia.topicmaps.core.VariantNameTest.java

public void testReader() throws Exception {
    // read file and store in object
    File filein = TestFileUtils.getTransferredTestInputFile("various", "clob.xml");
    File fileout = TestFileUtils.getTestOutputFile("various", "clob.xml.out");

    Reader ri = new FileReader(filein);
    long inlen = filein.length();
    variant.setReader(ri, inlen, DataTypes.TYPE_BINARY);

    assertTrue("Variant datatype is incorrect", Objects.equals(DataTypes.TYPE_BINARY, variant.getDataType()));

    // read and decode content
    Reader ro = variant.getReader();
    try {//from  w  w  w .j  av a 2s  .  c  om
        Writer wo = new FileWriter(fileout);
        try {
            IOUtils.copy(ro, wo);
        } finally {
            wo.close();
        }
    } finally {
        ro.close();
    }
    assertTrue("Reader value is null", ro != null);
    try {
        ri = new FileReader(filein);
        ro = new FileReader(fileout);
        long outlen = variant.getLength();
        try {
            assertTrue("Variant value put in is not the same as the one we get out.",
                    IOUtils.contentEquals(ro, ri));
            assertTrue("Variant value length is different", inlen == outlen);
        } finally {
            ri.close();
        }
    } finally {
        ro.close();
    }
}

From source file:com.attask.api.StreamClient.java

private Object request(String path, Map<String, Object> params, Set<String> fields, String method)
        throws StreamClientException {
    HttpURLConnection conn = null;

    try {//from   ww w.j  a v  a 2  s  . c  o m
        String query = "sessionID=" + sessionID + "&method=" + method;

        if (params != null) {
            for (String key : params.keySet()) {
                query += "&" + URLEncoder.encode(key, "UTF-8") + "="
                        + URLEncoder.encode(String.valueOf(params.get(key)), "UTF-8");
            }
        }

        if (fields != null) {
            query += "&fields=";
            for (String field : fields) {
                query += URLEncoder.encode(field, "UTF-8") + ",";
            }
            query = query.substring(0, query.lastIndexOf(","));
        }

        conn = createConnection(hostname + path, method);

        // Send request
        Writer out = new OutputStreamWriter(conn.getOutputStream());
        out.write(query);
        out.flush();
        out.close();

        // Read response
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;

        while ((line = in.readLine()) != null) {
            response.append(line);
        }

        in.close();

        // Decode JSON
        JSONObject result = new JSONObject(response.toString());

        // Verify result
        if (result.has("error")) {
            throw new StreamClientException(result.getJSONObject("error").getString("message"));
        } else if (!result.has("data")) {
            throw new StreamClientException("Invalid response from server");
        }

        // Manage the session
        if (path.equals(PATH_LOGIN)) {
            sessionID = result.getJSONObject("data").getString("sessionID");
        } else if (path.equals(PATH_LOGOUT)) {
            sessionID = null;
        }

        return result.get("data");
    } catch (Exception e) {
        throw new StreamClientException(e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.cpjit.swagger4j.support.internal.DefaultApiViewWriter.java

@Deprecated
@Override/*from w w  w  .  j  av  a2 s .c  o  m*/
public void writeIndex(HttpServletRequest request, HttpServletResponse response, String lang, Properties props)
        throws IOException {
    Map<String, Object> root = new HashMap<String, Object>();
    root.put("lang", lang);
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
    root.put("basePath", basePath);
    String host = request.getServerName() + ":" + request.getServerPort() + path;
    String suffix = props.getProperty("suffix");
    if (StringUtils.isBlank(suffix)) {
        suffix = "";
    }
    root.put("getApisUrl", "http://" + host + "/api" + suffix);
    root.put("apiDescription", props.getProperty("apiDescription"));
    root.put("apiTitle", props.getProperty("apiTitle"));
    root.put("apiVersion", props.getProperty("apiVersion"));
    root.put("suffix", suffix);
    Template template = FreemarkerUtils.getTemplate(getTemplateName());
    response.setContentType("text/html;charset=utf-8");
    Writer out = response.getWriter();
    try {
        template.process(root, out);
    } catch (TemplateException e) {
        throw new IOException(e);
    }
    out.flush();
    out.close();
}