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:filesscanner.MainWindow.java

private void saveToJSONBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveToJSONBtnActionPerformed

    JSONObject object = new JSONObject();

    for (int i = 0; i < modelFiles.getSize(); i++) {

        object.put("filename" + i, modelFiles.get(i).toString());

    }//  w  ww.  j  ava 2 s  . c  o m

    File file = new File("C:");
    JFileChooser chooser = ShowChooser(file);
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setDialogType(JFileChooser.SAVE_DIALOG);
    int res = chooser.showDialog(this, "  ? ??!!!");
    if (res == JFileChooser.APPROVE_OPTION) {

        try {
            Writer writer = new FileWriter(chooser.getSelectedFile());
            object.writeJSONString(writer);
            JOptionPane.showMessageDialog(rootPane, "SAVED SUCCESFULLY!!!");
            writer.flush();
            writer.close();
        } catch (IOException ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(rootPane, "Something bad!!!");
        }

    }

}

From source file:com.github.rwitzel.streamflyer.core.ModifiableReaderUnitTest.java

private void assertModificationByWriter(String input, String expectedOutput, long positionForModification,
        Change modificationToApply) throws Exception {

    // setup: create modifier and reader
    StringWriter stringWriter = new StringWriter();
    Writer writer = createWriter(stringWriter, positionForModification, modificationToApply);

    // read the stream into an output stream
    for (int index = 0; index < input.length(); index++) {
        writer.append(input.charAt(index));
    }/*from w w  w.j  a  va  2s  .  c o m*/
    writer.flush();
    writer.close();

    String foundOutput = stringWriter.toString();

    // compare the expected result with the found result
    assertEquals(expectedOutput, foundOutput);
}

From source file:com.sun.faban.harness.webclient.Uploader.java

/**
 * Updates the tags file.//from ww w .j  av a 2 s.c o  m
 * @param req
 * @param resp
 * @throws java.io.IOException
 */
public void updateTagsFile(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String tags = req.getParameter("tags");
    String runId = req.getParameter("runId");
    RunResult result = RunResult.getInstance(new RunId(runId));
    StringBuilder formattedTags = new StringBuilder();
    File runTagFile = new File(Config.OUT_DIR + runId + "/META-INF/tags");
    if (tags != null && !"".equals(tags)) {
        StringTokenizer t = new StringTokenizer(tags, " \n,");
        ArrayList<String> tagList = new ArrayList<String>(t.countTokens());
        while (t.hasMoreTokens()) {
            String nextT = t.nextToken().trim();
            if (nextT != null && !"".equals(nextT)) {
                formattedTags.append(nextT + "\n");
                tagList.add(nextT);
            }
        }
        FileHelper.writeContentToFile(formattedTags.toString(), runTagFile);
        result.tags = tagList.toArray(new String[tagList.size()]);
    }
    try {
        uploadTags(runId);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(Uploader.class.getName()).log(Level.SEVERE, null, ex);
    }
    Writer w = resp.getWriter();
    w.write("Tags updating completed");
    w.flush();
    w.close();
}

From source file:com.theminequest.MineQuest.SQLExecutor.java

/**
 * Check for initialization. What this does is take the build number
 * and uses a fast forward mechanism from the previous build to see
 * if any changes should be merged.<br>
 * It acts similarly to SVN./*from w  ww .j a  v  a2  s.  com*/
 */
private void checkInitialization() {
    if (!datafolder.exists()) {
        datafolder.mkdir();
    }
    File versionfile = new File(datafolder + File.separator + "version");
    Scanner s = null;
    String lastv = null;
    try {
        s = new Scanner(versionfile);
        if (s.hasNextLine()) {
            String dbtype = s.nextLine();
            if (dbtype.equalsIgnoreCase(databasetype.name())) {
                if (s.hasNextLine())
                    lastv = s.nextLine();
            }
        }
    } catch (FileNotFoundException e) {
        try {
            versionfile.createNewFile();
        } catch (IOException e1) {
            throw new RuntimeException(e1);
        }
    }
    if (lastv == null || lastv.compareTo(MineQuest.getVersion()) != 0) {
        if (lastv == null || lastv.equals("unofficialDev")) {
            if (lastv == null)
                MineQuest.log(Level.WARNING, "[SQL] No existing DBVERSION file; initializing DB as new.");
            else
                MineQuest.log(Level.WARNING,
                        "[SQL] I don't know what your previous build was; attempting to reinitialize.");
            lastv = "initial";
        }

        if (lastv != null && !lastv.equals("unofficialDev") && !lastv.equals("initial")) {
            int last = Integer.parseInt(lastv);
            MineQuest.log(Level.INFO, "[SQL] Fast forwarding through builds...");
            while (last < Integer.parseInt(MineQuest.getVersion())) {
                try {
                    MineQuest.log("[SQL] Fast forwarding from build " + last + " to " + (last + 1) + "...");
                    querySQL("update/" + last, "");
                    MineQuest.log("[SQL] Applied patch for build " + last + " to " + (last + 1) + "!");
                } catch (NoSuchElementException e) {
                    //MineQuest.log(Level.WARNING,"[SQL] No update path from build " + last + " to " + (last+1) + " build; Probably normal.");
                }
                last++;
            }
        } else {
            try {
                querySQL("update/" + lastv, "");
            } catch (NoSuchElementException e) {
                MineQuest.log(Level.WARNING,
                        "[SQL] No update path from build " + lastv + " to this build; Probably normal.");
            }
        }

        Writer out;
        try {
            out = new OutputStreamWriter(new FileOutputStream(versionfile));
            out.write(databasetype.name() + IOUtils.LINE_SEPARATOR + MineQuest.getVersion());
            out.close();
        } catch (FileNotFoundException e) {
            MineQuest.log(Level.SEVERE, "[SQL] Failed to commit DBVERSION: " + e.getMessage());
            throw new RuntimeException(e);
        } catch (IOException e) {
            MineQuest.log(Level.SEVERE, "[SQL] Failed to commit DBVERSION: " + e.getMessage());
            throw new RuntimeException(e);
        }
    }

}

From source file:com.cloudera.sqoop.manager.PostgresqlExportTest.java

protected void createTestFile(String filename, String[] lines) throws IOException {
    new File(getWarehouseDir()).mkdirs();
    File file = new File(getWarehouseDir() + "/" + filename);
    Writer output = new BufferedWriter(new FileWriter(file));
    for (String line : lines) {
        output.write(line);//from   ww w .j  av  a2s .com
        output.write("\n");
    }
    output.close();
}

From source file:no.uis.service.studinfo.commons.StudinfoValidator.java

protected List<String> validate(String studieinfoXml, StudinfoType infoType, int year, FsSemester semester,
        String language) throws Exception {

    // save xml/*from ww  w  . j  ava 2 s .  c  om*/
    File outFile = new File("target/out", infoType.toString() + year + semester + language + ".xml");
    if (outFile.exists()) {
        outFile.delete();
    } else {
        outFile.getParentFile().mkdirs();
    }
    File outBackup = new File("target/out", infoType.toString() + year + semester + language + "_orig.xml");
    Writer backupWriter = new OutputStreamWriter(new FileOutputStream(outBackup), IOUtils.UTF8_CHARSET);
    backupWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    IOUtils.copy(new StringReader(studieinfoXml), backupWriter, IOBUFFER_SIZE);
    backupWriter.flush();
    backupWriter.close();

    TransformerFactory trFactory = TransformerFactory.newInstance();
    Source schemaSource = new StreamSource(getClass().getResourceAsStream("/fspreprocess.xsl"));
    Transformer stylesheet = trFactory.newTransformer(schemaSource);

    Source input = new StreamSource(new StringReader(studieinfoXml));

    Result result = new StreamResult(outFile);
    stylesheet.transform(input, result);

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(false);
    factory.setNamespaceAware(true);

    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schema = schemaFactory
            .newSchema(new Source[] { new StreamSource(new File("src/main/xsd/studinfo.xsd")) });

    factory.setSchema(schema);

    SAXParser parser = factory.newSAXParser();

    XMLReader reader = parser.getXMLReader();
    ValidationErrorHandler errorHandler = new ValidationErrorHandler(infoType, year, semester, language);
    reader.setErrorHandler(errorHandler);
    reader.setContentHandler(errorHandler);
    try {
        reader.parse(
                new InputSource(new InputStreamReader(new FileInputStream(outFile), IOUtils.UTF8_CHARSET)));
    } catch (SAXException ex) {
        // do nothing. The error is handled in the error handler
    }
    return errorHandler.getMessages();
}

From source file:com.palantir.stash.stashbot.servlet.BuildStatusReportingServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {//from   w  w  w. j ava  2 s  . c  o  m
        // Look at JenkinsManager class if you change this:
        // final two arguments could be empty...
        final String URL_FORMAT = "BASE_URL/REPO_ID_OR_SLUG/PULLREQUEST_ID]";
        final String pathInfo = req.getPathInfo();
        final String[] parts = pathInfo.split("/");

        // need at *least* 3 parts to be correct
        if (parts.length < 3) {
            throw new IllegalArgumentException("The format of the URL is " + URL_FORMAT);
        }

        // Last part is always the PR
        String pullRequestPart = parts[parts.length - 1];

        // First part is always empty because string starts with '/', last is pr, the rest is the slug
        String slugOrId = StringUtils.join(Arrays.copyOfRange(parts, 1, parts.length - 1), "/");

        Repository repo;
        try {
            int repoId = Integer.valueOf(slugOrId);
            repo = rs.getById(repoId);
            if (repo == null) {
                throw new IllegalArgumentException("Unable to find repository for repo id " + repoId);
            }
        } catch (NumberFormatException e) {
            // we have a slug, try to get a repo ID from that
            // slug should look like this: projects/PROJECT_KEY/repos/REPO_SLUG/pull-requests
            String[] newParts = slugOrId.split("/");

            if (newParts.length != 5) {
                throw new IllegalArgumentException(
                        "The format of the REPO_ID_OR_SLUG is an ID, or projects/PROJECT_KEY/repos/REPO_SLUG/pull-requests");
            }
            Project p = ps.getByKey(newParts[1]);
            if (p == null) {
                throw new IllegalArgumentException("Unable to find project for project key" + newParts[1]);
            }
            repo = rs.getBySlug(p.getKey(), newParts[3]);
            if (repo == null) {
                throw new IllegalArgumentException("Unable to find repository for project key" + newParts[1]
                        + " and repo slug " + newParts[3]);
            }
        }

        final long pullRequestId;
        final PullRequest pullRequest;

        try {
            pullRequestId = Long.parseLong(pullRequestPart);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Unable to parse pull request id " + parts[7], e);
        }
        pullRequest = prs.getById(repo.getId(), pullRequestId);
        if (pullRequest == null) {
            throw new IllegalArgumentException("Unable to find pull request for repo id "
                    + repo.getId().toString() + " pr id " + pullRequestId);
        }

        PullRequestMergeability canMerge = prs.canMerge(repo.getId(), pullRequestId);

        JSONObject output = new JSONObject();
        output.put("repoId", repo.getId());
        output.put("prId", pullRequestId);
        output.put("url", nb.repo(repo).pullRequest(pullRequest.getId()).buildAbsolute());
        output.put("canMerge", canMerge.canMerge());
        if (!canMerge.canMerge()) {
            JSONArray vetoes = new JSONArray();
            for (PullRequestMergeVeto prmv : canMerge.getVetos()) {
                JSONObject prmvjs = new JSONObject();
                prmvjs.put("summary", prmv.getSummaryMessage());
                prmvjs.put("details", prmv.getDetailedMessage());
                vetoes.put(prmvjs);
            }
            // You might expect a conflict would be included in the list of merge blockers.  You'd be mistaken.
            if (canMerge.isConflicted()) {
                JSONObject prmvjs = new JSONObject();
                prmvjs.put("summary", "This pull request is unmergeable due to conflicts.");
                prmvjs.put("details", "You will need to resolve conflicts to be able to merge.");
                vetoes.put(prmvjs);
            }
            output.put("vetoes", vetoes);
        }

        log.debug("Serving build status: " + output.toString());
        printOutput(output, req, res);
    } catch (Exception e) {
        res.reset();
        res.setStatus(500);
        res.setContentType("application/json");
        Writer w = res.getWriter();
        try {
            w.append(new JSONObject().put("error", e.getMessage()).toString());
        } catch (JSONException e1) {
            throw new RuntimeException("Errorception!", e1);
        }
        w.close();
    }
}

From source file:org.callimachusproject.auth.DigestPasswordAccessor.java

public Set<?> changeDigestPassword(Set<RDFObject> files, String[] passwords, String webapp,
        ObjectConnection con) throws RepositoryException, IOException {
    int i = 0;//from  w  ww.j  a va  2 s  .  com
    Set<Object> set = new LinkedHashSet<Object>();
    for (URI uuid : getPasswordFiles(files, passwords.length, webapp, con)) {
        String password = passwords[i++];
        if (password == null || password.length() == 0)
            throw new BadRequest("New password cannot be empty");
        Writer writer = con.getBlobObject(uuid).openWriter();
        try {
            writer.write(password);
        } finally {
            writer.close();
        }
        set.add(con.getObject(uuid));
    }
    return set;
}

From source file:com.googlecode.fascinator.indexer.RuleManager.java

public void run(Reader in, Writer out) throws IOException {
    File tmpFile;// w  w w. j ava  2  s  .  co  m
    Reader tmpIn = in;
    Writer tmpOut = null;
    OutputStream tmpOutStream;
    cancelled = false;
    for (Rule rule : rules) {
        try {
            tmpFile = createTempFile("rule", ".xml");
            tmpOutStream = new FileOutputStream(tmpFile);
            tmpOut = new OutputStreamWriter(tmpOutStream, "UTF-8");
            rule.run(tmpIn, tmpOut);
            tmpOut.close();
            tmpOutStream.close();
            tmpIn.close();
            tmpIn = new InputStreamReader(new FileInputStream(tmpFile), "UTF-8");
        } catch (Exception e) {
            if (rule.isRequired()) {
                cancelled = true;
                log.error("Stopping since " + rule + " failed: ", e);
                break;
            } else {
                log.warn("Rule " + rule + " failed: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }
    if (!cancelled) {
        IOUtils.copy(tmpIn, out);
    }
    tmpIn.close();
    out.close();
    cleanupTempFiles();
}

From source file:fr.jetoile.hadoopunit.integrationtest.ManualIntegrationBootstrapTest.java

@Test
public void oozieShouldStart() throws Exception {

    LOGGER.info("OOZIE: Test Submit Workflow Start");

    org.apache.hadoop.conf.Configuration conf = new org.apache.hadoop.conf.Configuration();
    conf.set("fs.default.name",
            "hdfs://127.0.0.1:" + configuration.getInt(HadoopUnitConfig.HDFS_NAMENODE_PORT_KEY));

    URI uri = URI.create("hdfs://127.0.0.1:" + configuration.getInt(HadoopUnitConfig.HDFS_NAMENODE_PORT_KEY));

    FileSystem hdfsFs = FileSystem.get(uri, conf);

    OozieClient oozieClient = new OozieClient("http://" + configuration.getString(OozieBootstrap.OOZIE_HOST)
            + ":" + configuration.getInt(OozieBootstrap.OOZIE_PORT) + "/oozie");

    Path appPath = new Path(hdfsFs.getHomeDirectory(), "testApp");
    hdfsFs.mkdirs(new Path(appPath, "lib"));
    Path workflow = new Path(appPath, "workflow.xml");

    //write workflow.xml
    String wfApp = "<workflow-app xmlns='uri:oozie:workflow:0.1' name='test-wf'>" + "    <start to='end'/>"
            + "    <end name='end'/>" + "</workflow-app>";

    Writer writer = new OutputStreamWriter(hdfsFs.create(workflow));
    writer.write(wfApp);/*from  w  w w  .j  a  va2  s. c o  m*/
    writer.close();

    //write job.properties
    Properties oozieConf = oozieClient.createConfiguration();
    oozieConf.setProperty(OozieClient.APP_PATH, workflow.toString());
    oozieConf.setProperty(OozieClient.USER_NAME, UserGroupInformation.getCurrentUser().getUserName());

    //submit and check
    final String jobId = oozieClient.submit(oozieConf);
    WorkflowJob wf = oozieClient.getJobInfo(jobId);
    Assert.assertNotNull(wf);
    assertEquals(WorkflowJob.Status.PREP, wf.getStatus());

    LOGGER.info("OOZIE: Workflow: {}", wf.toString());
    hdfsFs.close();

}