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.orga.ivy.plugins.p4resolver.BaseTestCase.java

protected void createDummyFile(String path, String name, String content) {
    Writer fw = null;

    File dir = new File(path);
    try {//from www .j av a2s .  c  o m
        if (dir.mkdirs() == false) {
            Assert.fail("Couldn't create create dir for dummy-file: " + path);
        }

        fw = new FileWriter(path + "/" + name);
        fw.write(content);
        //fw.append( System.getProperty("line.separator") ); // e.g. "\n" 
    } catch (IOException e) {
        Assert.fail("Couldn't create dummy-file " + path + "/" + name);
    } finally {
        if (fw != null)
            try {
                fw.close();
            } catch (IOException e) {
                System.err.println("Couldn't close dummy-file " + path + "/" + name);
                Assert.fail("Couldn't close dummy-file " + path + "/" + name);
            }
    }

}

From source file:hu.dolphio.tprttapi.service.TrackingFlushServiceTpImpl.java

@Override
public ArrayList<UserStory> getUserStories() throws IOException {

    ArrayList<UserStory> userStories = new ArrayList<UserStory>();

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(config)
            .setDefaultCredentialsProvider(credsProvider).build();

    try {/*from   w  w  w  .j  a va 2 s  .  c o m*/
        StringBuilder urlBuilder = new StringBuilder().append("/api/v1/Context/?ids=1184");

        HttpGet httpGet = new HttpGet(urlBuilder.toString());

        CloseableHttpResponse execute = httpclient.execute(targetHost, httpGet, clientContext);
        String acid = IOUtils.toString(execute.getEntity().getContent(), "utf-8");
        LOG.info("Search for TP times return: " + execute);

        acid = acid.substring(acid.indexOf("\"") + 1);
        acid = acid.substring(0, acid.indexOf("\""));

        //userstories
        urlBuilder = new StringBuilder().append("/api/v1/Userstories/?acid=").append(acid);

        httpGet = new HttpGet(urlBuilder.toString());

        execute = httpclient.execute(targetHost, httpGet, clientContext);
        String userStoriesXml = IOUtils.toString(execute.getEntity().getContent(), "utf-8");
        LOG.info("Search for TP times return: " + execute);

        //features

        urlBuilder = new StringBuilder().append("/api/v1/Features/?acid=").append(acid);

        httpGet = new HttpGet(urlBuilder.toString());

        execute = httpclient.execute(targetHost, httpGet, clientContext);
        String featuresXml = IOUtils.toString(execute.getEntity().getContent(), "utf-8");
        LOG.info("Search for TP times return: " + execute);

        //                
        //                File fileObj = new File("C:\\Users\\zemcov.tamas\\Desktop\\test\\us2.xml");
        //
        //                PrintWriter writer = null;
        //                try {
        //                writer = new PrintWriter(fileObj);
        //               }  catch (FileNotFoundException e) {
        //                 e.printStackTrace();
        //                 }
        //    
        //    
        //
        //               writer.println(userStoriesXml);
        //             writer.close(); 
        //                
        Writer out = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream("C:\\Users\\zemcov.tamas\\Desktop\\test\\us.xml"), "UTF-8"));
        try {
            out.write(userStoriesXml);
        } finally {
            out.close();
        }

        //

        //

        try {
            //String parsableUserStories = new String("<?xml version=\"1.0\"?>\n").concat(userStoriesXml);

            File fXmlFile = new File("C:\\Users\\zemcov.tamas\\Desktop\\test\\us.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            //Document doc = dBuilder.parse(UserStoriesUtf8);
            Document doc = dBuilder.parse(fXmlFile);

            NodeList nList = doc.getElementsByTagName("UserStory");

            for (int temp = 0; temp < nList.getLength(); temp++) {

                Node nNode = nList.item(temp);

                if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element eElement = (Element) nNode;

                    UserStory us = new UserStory();

                    us.setName(eElement.getAttribute("Name"));
                    if (eElement.getElementsByTagName("Team").item(0).getAttributes()
                            .getNamedItem("Name") != null) {
                        us.setResponsible(eElement.getElementsByTagName("Team").item(0).getAttributes()
                                .getNamedItem("Name").getTextContent());
                    } else
                        us.setResponsible(null);
                    us.setStatus(eElement.getElementsByTagName("Progress").item(0).getTextContent());
                    us.setDueDate(eElement.getElementsByTagName("PlannedEndDate").item(0).getTextContent());
                    us.setEntityState(eElement.getElementsByTagName("EntityState").item(0).getAttributes()
                            .getNamedItem("Name").getTextContent());

                    userStories.add(us);

                    //                        System.out.println("Name : " + eElement.getAttribute("Name"));
                    //                        if (eElement.getElementsByTagName("Team").item(0).getAttributes().getNamedItem("Name") != null){
                    //                        System.out.println("responsible : " + eElement.getElementsByTagName("Team").item(0).getAttributes().getNamedItem("Name").getTextContent());
                    //                        }
                    //                        System.out.println("status : " + eElement.getElementsByTagName("Progress").item(0).getTextContent());
                    //         System.out.println("duedate : " + eElement.getElementsByTagName("PlannedEndDate").item(0).getTextContent());
                    //         System.out.println("entity state : " + eElement.getElementsByTagName("EntityState").item(0).getAttributes().getNamedItem("Name").getTextContent());

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //
        httpclient.close();
    } catch (IOException ex) {
        LOG.warn(ex.getMessage(), ex);
    }

    return userStories;
}

From source file:com.esri.ges.solutions.processor.geometry.QueryProcessor.java

private void ParseResponses(String timestamp, String file) {
    Set<String> keys = responseMap.keySet();
    Iterator<String> it = keys.iterator();
    String body = "";
    while (it.hasNext()) {
        String k = it.next();//from w w w .j a  va2 s .  c  o m
        @SuppressWarnings("unchecked")
        HashMap<String, Object> response = (HashMap<String, Object>) responseMap.get(k);
        FeatureSet fset = (FeatureSet) response.get("fset");
        String cfg = (String) response.get("config");
        @SuppressWarnings("unchecked")
        HashMap<String, Object> tokenmap = (HashMap<String, Object>) response.get("tokenmap");
        String layer = (String) response.get("layer");
        Graphic[] features = fset.getGraphics();
        String lyrHeader = (String) response.get("lyrheader");
        if (!lyrHeader.isEmpty()) {
            lyrHeader = "<h3>" + lyrHeader + "</h3>";
        }
        String items = "";

        items += "<b>" + layer.toUpperCase() + ": </b>";

        Boolean usingDist = (Boolean) response.get("calcdist");
        String distUnits = (String) response.get("distunits");
        String distToken = (String) response.get("disttoken");
        SpatialReference fsetSr = fset.getSpatialReference();
        for (int i = 0; i < features.length; ++i) {
            Graphic f = features[i];
            Map<String, Object> att = f.getAttributes();
            Set<String> fields = tokenmap.keySet();
            Iterator<String> itFields = fields.iterator();
            String item = cfg;
            if (usingDist) {
                String d = this.GetDistAsString(f, fsetSr, distUnits);
                item = item.replace(distToken, d);
            }
            while (itFields.hasNext()) {
                String fldname = itFields.next();
                String token = (String) tokenmap.get(fldname);
                item = item.replace(token, att.get(fldname).toString());

                if (i > 0) {
                    items += ", ";
                }
                items += item;

            }
        }
        items = "<p>" + items + "</p>";
        body += lyrHeader + items;
    }
    String content = "";
    try {
        //String name = this.getClass().getName();
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("ReportTemplate.html");
        //FileInputStream is = new FileInputStream(file);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String ln;
        while ((ln = br.readLine()) != null) {
            content += ln;
        }
        String title = properties.get("title").getValueAsString();
        String header = properties.get("header").getValueAsString();
        if (!timestamp.isEmpty()) {
            String tsToken = properties.get("timestamptoken").getValueAsString();
            title = title.replace(tsToken, timestamp);
            header = header.replace(tsToken, timestamp);
            body = body.replace(tsToken, timestamp);
        }
        content = content.replace("[$TITLE]", "<h1>" + title + "</h1>");
        content = content.replace("[$HEADING]", "<h2>" + header + "</h2>");
        content = content.replace("[$BODY]", body);
        br.close();
        String filename = "assets/reports/" + file;
        File outfile = new File(filename);
        FileOutputStream fos = new FileOutputStream(outfile);
        OutputStreamWriter osw = new OutputStreamWriter(fos);
        Writer w = new BufferedWriter(osw);
        w.write(content);
        w.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.microsoft.tfs.core.clients.versioncontrol.engines.internal.CheckinEngine.java

/**
 * Creates a temporary file for symbolic links to work with before
 * uploading./*from  www  . j av a2 s.co  m*/
 *
 * @param change
 *        The PendingChange that is being filtered
 * @return A string representing the temporary file we created
 * @throws IOException
 *         If the file could not be created
 */
private String createTempFileForSymbolicLink(final String localItem, final String targetLink)
        throws IOException {
    final String tempFile = TempStorageService.getInstance().createTempFile().getAbsolutePath();
    log.trace(MessageFormat.format("Using temporary file {0} for symbolic link {1}", tempFile, localItem)); //$NON-NLS-1$

    final Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile)));
    out.write(targetLink);
    out.close();

    log.trace(MessageFormat.format("Symbolic link target {0} written to temporary file {1} as contents", //$NON-NLS-1$
            targetLink, tempFile));

    return tempFile;
}

From source file:org.eclipse.virgo.ide.runtime.internal.core.ServerPublishOperation.java

/**
 * Creates a dummy manifest for WTP Dynamic Web Projects only
 *///from w w  w  . j a  v  a 2 s  .  c o  m
private void publishManifest(IModule module, IPath path) {

    if (FacetUtils.hasProjectFacet(module.getProject(), FacetCorePlugin.WEB_FACET_ID)) {
        File manifestFile = path.append(BundleManifestCorePlugin.MANIFEST_FOLDER_NAME)
                .append(BundleManifestCorePlugin.MANIFEST_FILE_NAME).toFile();
        if (manifestFile.exists()) {
            return;
        }
        BundleManifest manifest = BundleManifestFactory.createBundleManifest();
        Writer writer = null;
        try {
            manifestFile.getParentFile().mkdirs();
            writer = new FileWriter(manifestFile);
            manifest.write(writer);
        } catch (IOException e) {
        } finally {
            if (writer != null) {
                try {
                    writer.flush();
                    writer.close();
                } catch (IOException e) {
                }
            }
        }
    }
}

From source file:com.morty.podcast.writer.PodCastGenerator.java

private void generateCompleteFeed(List podcastFiles) throws Exception {

    try {//from ww w .  jav a  2s  . c om

        //Get the default info file from the podcast directory, and see if there are any overrides
        File defaultInfo = new File(m_directoryToTraverse + File.separator + PodCastConstants.INFO_FILE);
        HashMap defaultFeedValues = new HashMap();
        if (defaultInfo.exists())
            defaultFeedValues = PodCastUtils.parseInfoFile(defaultInfo);

        final SyndFeed feed = new SyndFeedImpl();
        feed.setFeedType(PodCastConstants.FEED_TYPE);

        feed.setTitle(PodCastUtils.getMapValue(defaultFeedValues, PodCastConstants.FEED_TITLE_KEY,
                PodCastConstants.DEFAULT_FEED_TITLE));
        if (m_feedLink == null)
            feed.setLink(PodCastUtils.generateHttpLink(m_httpRoot, m_fileToCreate, m_urlSuffix));
        else
            feed.setLink(m_feedLink);
        feed.setDescription(PodCastUtils.getMapValue(defaultFeedValues, PodCastConstants.FEED_DESCRIPTION_KEY,
                PodCastConstants.DEFAULT_FEED_DESCRIPTION));
        feed.setCopyright(PodCastUtils.getMapValue(defaultFeedValues, PodCastConstants.FEED_COPYRIGHT_KEY,
                PodCastConstants.DEFAULT_FEED_COPYRIGHT));

        //Set the image on the Feed.
        SyndImage img = new SyndImageImpl();
        img.setDescription(feed.getDescription());
        img.setLink(feed.getLink());
        img.setTitle(PodCastUtils.getMapValue(defaultFeedValues, PodCastConstants.FEED_IMAGE_TITLE,
                PodCastConstants.DEFAULT_IMAGE_TITLE));
        img.setUrl(PodCastUtils.generateHttpLink(m_httpRoot, PodCastUtils.getMapValue(defaultFeedValues,
                PodCastConstants.FEED_IMAGE_NAME, PodCastConstants.DEFAULT_IMAGE_NAME), m_urlSuffix));
        feed.setImage(img);

        //Set image on all episodes.
        FeedInformation episodeFeed = new FeedInformationImpl();
        episodeFeed.setImage(new URL(img.getUrl()));

        Iterator it = podcastFiles.iterator();
        while (it.hasNext()) {
            SyndEntry podcastEntry = (SyndEntry) it.next();
            podcastEntry.getModules().add(episodeFeed);
        }

        //Generate the itunes image!
        FeedInformation itunesFeed = new FeedInformationImpl();
        itunesFeed.setImage(new URL(img.getUrl()));
        itunesFeed.setSummary(feed.getDescription());
        feed.getModules().add(itunesFeed);

        feed.setEntries(podcastFiles);

        final Writer fileWriter = new FileWriter(m_fileToCreate);
        final SyndFeedOutput feedOutput = new SyndFeedOutput();
        feedOutput.output(feed, fileWriter);
        fileWriter.flush();
        fileWriter.close();

        m_logger.info("Podcast created [" + m_fileToCreate + "]");

    } catch (Exception ex) {
        m_logger.error("ERROR: " + ex.getMessage());
        throw ex;
    }

}

From source file:datainstiller.data.DataPersistence.java

/**
 * This method serializes this object to the given file
 * @param filePath file path to serialize this object
 *///from   w w  w  .  j  av a  2  s .c o  m
public void toFile(String filePath) {
    FileOutputStream fos = null;
    Writer writer = null;
    try {
        fos = new FileOutputStream(filePath);
        writer = new OutputStreamWriter(fos, "UTF-8");
        writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n");
        getXstream().toXML(this, writer);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {

        try {
            if (writer != null)
                writer.close();
            if (fos != null)
                fos.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

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

private Object request(String path, Map<String, Object> params, Set<String> fields, String method,
        int retryCount, File file) throws StreamClientException {
    HttpURLConnection conn = null;
    int responseCode = -1;

    try {/*  www .  ja v a2  s .com*/
        String authenticationParam = "";
        if (apiKey != null) {
            authenticationParam += "apiKey=" + apiKey;
        } else if (sessionID != null) {
            authenticationParam += "sessionID=" + sessionID;
        }
        String methodParam = "method=" + method;
        String query = authenticationParam + "&" + methodParam;

        if (params != null) {
            for (String key : params.keySet()) {
                if (params.get(key) instanceof String[]) {
                    String[] paramVal = (String[]) params.get(key);
                    for (int i = 0; i < paramVal.length; i++) {
                        String val = paramVal[i];
                        query += "&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(val, "UTF-8");
                    }
                } else {
                    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);

        String boundary = Long.toHexString(System.currentTimeMillis());

        if (file != null) {
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            conn.setRequestProperty("User-Agent", "Workfront Java StreamClient");
        }

        // Send request
        OutputStream outputStream = conn.getOutputStream();
        Writer out = new OutputStreamWriter(outputStream);
        if (file != null) {
            addFileToRequest(boundary, out, outputStream, file);
        } else {
            out.write(query);
        }

        out.flush();
        out.close();

        // Get response code
        responseCode = conn.getResponseCode();

        // 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 (ConnectException connectException) {
        throw new StreamClientException("Unable to connect to " + hostname + path);
    } catch (IOException e) {
        //getErrorStream() can return null if no error data was sent back
        if (conn.getErrorStream() != null) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();

            try {
                copyStream(conn.getErrorStream(), out);
            } catch (IOException e1) {
                // Removed printStackTrace call
            }

            throw new StreamClientException(new String(out.toByteArray()));
        } else {
            //I believe this use case happens when the we are sending to many requests at one time...
            if (retryCount < 3) {
                return request(path, params, fields, method, ++retryCount);
            } else {
                throw new StreamClientException(
                        "An error happened but no error data was sent... 3 time... Response Code = "
                                + responseCode);
            }
        }
    } catch (Exception e) {
        throw new StreamClientException(e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:mx.itesm.imb.EcoreImbEditor.java

/**
 * /* w ww .j ava  2s .  c  o m*/
 * @param imbProject
 * @param templateProject
 * @param provider
 * @param imbTypes
 * @throws IOException
 */
private static void writeEcoreController(final File imbProject, final File templateProject, final File provider,
        final List<File> imbTypes) throws IOException {
    String type;
    Writer writer;
    boolean typeFound;
    String packageName;
    VelocityContext context;

    context = new VelocityContext();
    type = provider.getName().replace("ItemProvider.java", "");
    packageName = provider.getPath().substring(provider.getPath().indexOf("src") + "src".length() + 1,
            provider.getPath().indexOf(type) - 1).replace('/', '.');
    typeFound = false;
    for (File imbType : imbTypes) {
        if (imbType.getName().equals(type + ".java")) {
            typeFound = true;
            context.put("imbTypePackage",
                    imbType.getPath().substring(imbType.getPath().indexOf("src") + "src".length() + 1,
                            imbType.getPath().indexOf(type) - 1).replace(File.separatorChar, '.'));
            break;
        }
    }

    if (typeFound) {
        context.put("type", type);
        context.put("packageName", packageName);
        writer = new FileWriter(
                new File(imbProject, "/imb/src/main/java/mx/itesm/ecore/web/EcoreController" + type + ".java"));
        EcoreImbEditor.controllerTemplate.merge(context, writer);
        writer.close();

        // Configuration properties file
        FileUtils.copyFile(new File(templateProject, "/templates/configuration-template.properties"),
                new File(imbProject, "/imb/src/main/resources/mx/itesm/imb/configuration.properties"));
    }
}