Example usage for java.io FileWriter close

List of usage examples for java.io FileWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:au.edu.unsw.cse.soc.federatedcloud.curator.CuratorAPI.java

/**
 * This is a temporary method until a proper DB is figured out.
 * @param description/*from ww w  .  j  a  v a  2 s. com*/
 */
private void persistDescription(CloudResourceDescription description) throws Exception {
    //convert the description to json object
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String json = gson.toJson(description);

    try {
        FileWriter writer = new FileWriter(KB_LOCATION + description.getName() + ".json");
        writer.write(json);
        writer.close();
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw e;
    }

}

From source file:co.edu.uniandes.bigdata.ProyectoBigData.logica.FeedsReader.java

private List<Feed> filterXquery(String category, String source, String property, String filterText,
        boolean excludes) throws IOException, XQException {

    String fileName = getXMLName(category, source);
    String xmlPath = getXMLPath(fileName);

    String exclude_xquery_strg_ini = "";
    String exclude_xquery_strg_end = "";
    if (excludes) {
        exclude_xquery_strg_ini = "not(";
        exclude_xquery_strg_end = ")";
    }//from  w  w  w.  j  a  v a  2  s. c  om

    String xq_query = "";

    if (property.equals("title_description")) { // create xQuery looking for title and description
        xq_query += "for $item in doc(\"" + xmlPath + "\")/rss/channel/item\n";
        xq_query += "where " + exclude_xquery_strg_ini + "contains(upper-case($item/title),upper-case(\""
                + filterText + "\"))" + " or contains(upper-case($item/description),upper-case(\"" + filterText
                + "\"))" + exclude_xquery_strg_end + "\n";
        xq_query += "return concat($item/data(title), '|', $item/data(pubDate), '|', $item/data(link))\n\n";
    } else { // create xQuery for property
        xq_query += "for $item in doc(\"" + xmlPath + "\")/rss/channel/item\n";
        xq_query += "where " + exclude_xquery_strg_ini + "contains(upper-case($item/title),upper-case(\""
                + filterText + "\"))" + exclude_xquery_strg_end + "\n";
        xq_query += "return concat($item/data(title), '|', $item/data(pubDate), '|', $item/data(link))\n\n";
    }

    // create xq file for evidence
    File file = new File(getXQPath(fileName));
    FileWriter out = new FileWriter(file);
    out.write(xq_query);
    out.close();

    // executes XQuery
    XQDataSource ds = new SaxonXQDataSource();
    XQConnection conn = ds.getConnection();
    XQPreparedExpression exp = conn.prepareExpression(xq_query);
    XQResultSequence result = exp.executeQuery();

    // creates feeds List splitting values from xq result
    List<Feed> feeds = new ArrayList<>();

    while (result.next()) {
        String feedText = result.getItemAsString(null);
        String[] feed = feedText.split("\\|");
        String title = feed[0], pubDate = feed[1], urlLink = feed[2];
        feeds.add(new Feed(category, source, cleanTitle(title), urlLink, pubDate));
    }

    return feeds;

}

From source file:org.sift.batch.tag.service.TagCloudMarshallerService.java

/**
 * Helper method to write the tag cloud to the file system using the Marshaller
 * @param filePath the absolute path to the data file
 * @param tagCloudModel the TagCloudModel whose data is to be written to the specified file
 * @throws RuntimeException in case of errors in writing the data file
 *///from   w ww.jav a2  s.c o  m
private void marshallTagCloud(String filePath, TagCloudModel tagCloudModel) throws RuntimeException {
    File file = new File(filePath);
    if (file.exists()) {
        file.delete();
    }
    try {
        file.createNewFile();
        String data = this.marshaller.marshal(tagCloudModel);
        FileWriter writer = new FileWriter(file);
        writer.write(data);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        throw new RuntimeException(
                "Error writing tag cloud image for : " + tagCloudModel.getSubject() + " to file : " + filePath,
                e);
    }
}

From source file:br.com.atmatech.sac.webService.WebServiceAtivacao.java

public Boolean login(String url, String user, String password, String cnpj) throws IOException {
    Boolean chave = false;/*from   w ww. ja v a 2  s. c  o  m*/
    HttpPost post = new HttpPost(url);
    boolean result = false;
    /* Configura os parmetros do POST */
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("login", user));
    nameValuePairs.add(new BasicNameValuePair("senha", password));
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs, Consts.UTF_8));

    HttpResponse response = client.execute(post);

    EntityUtils.consume(response.getEntity());
    HttpGet get = new HttpGet("http://atma.serveftp.com/atma/view/nav/header_chave.php?cnpj=" + cnpj);
    response = client.execute(get);

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line;
    FileWriter out = new FileWriter("./ativacao.html");
    PrintWriter gravarArq = new PrintWriter(out);
    while ((line = rd.readLine()) != null) {
        gravarArq.print(line + "\n");
        chave = true;
    }
    out.close();
    return chave;
}

From source file:co.mcme.animations.animations.commands.AnimationFactory.java

public static boolean saveAnimationData(Player p) {
    //Perform Animation integrity checks
    if (animationName.trim().isEmpty()) {
        p.sendMessage(ChatColor.RED/*w w  w.  j  ava2  s .  co m*/
                + "Animation name has not been set. Use /anim name while in Animation setup mode to set up the animation name");
        return false;
    }

    if ((null == animationDescription) || (animationDescription.trim().isEmpty())) {
        p.sendMessage(ChatColor.RED
                + "The animation needs a description. Use /anim description while in Animation setup mode to set up the animation description");
        return false;
    }

    if (null == origin) {
        p.sendMessage(ChatColor.RED
                + "Origin has not been set. Use /anim origin while in Animation setup mode to set up the animation origin");
        return false;
    }

    if (null == type) {
        p.sendMessage(ChatColor.RED
                + "Animation type has not been set. Use /anim type while in Animation setup mode to set up the animation type");
        return false;
    }

    if (frames.isEmpty()) {
        p.sendMessage(ChatColor.RED + "The Animation doesn't contain any Frame!");
        return false;
    }

    if (clips.isEmpty()) {
        p.sendMessage(ChatColor.RED + "The Animation doesn't contain any Clipboard!");
        return false;
    }
    if (triggers.isEmpty()) {
        p.sendMessage(ChatColor.RED + "The Animation doesn't contain any Trigger!");
        return false;
    }
    //Save all the schematics
    File animationFolder = new File(MCMEAnimations.MCMEAnimationsInstance.getDataFolder() + File.separator
            + "schematics" + File.separator + "animations" + File.separator + animationName);
    if (animationFolder.exists()) {
        try {
            delete(animationFolder);
        } catch (IOException ex) {
            Logger.getLogger(AnimationFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    animationFolder.mkdirs();

    for (MCMEClipboardStore cs : clips) {
        if (cs.getUses() > 0) {
            saveClipboardToFile(cs.getClip(), cs.getSchematicName(), animationFolder);
        }
    }

    //Save the configuration file
    JSONObject configuration = new JSONObject();
    configuration.put("name", animationName);
    configuration.put("world-index", p.getWorld().getName());
    JSONArray frameList = new JSONArray();
    JSONArray durationList = new JSONArray();
    for (int i = 0; i < frames.size(); i++) {
        frameList.add(frames.get(i).getSchematic().getSchematicName());
        durationList.add(frames.get(i).getDuration());
    }
    configuration.put("frames", frameList);
    configuration.put("durations", durationList);

    JSONArray originPoints = new JSONArray();
    originPoints.add((int) Math.floor(origin.getX()));
    originPoints.add((int) Math.floor(origin.getY()));
    originPoints.add((int) Math.floor(origin.getZ()));
    configuration.put("origin", originPoints);

    configuration.put("type", type.toString());

    JSONArray interactions = new JSONArray();
    for (AnimationTrigger at : triggers) {
        interactions.add(at.toJSON());
    }

    configuration.put("interactions", interactions);

    JSONArray animationActions = new JSONArray();
    for (AnimationAction a : actions) {
        animationActions.add(a.toJSON());
    }
    if (animationActions.size() > 0) {
        configuration.put("actions", animationActions);
    }

    configuration.put("creator", owner.getDisplayName());
    configuration.put("description", animationDescription);

    try {
        FileWriter fw = new FileWriter(new File(MCMEAnimations.MCMEAnimationsInstance.getDataFolder()
                + File.separator + "schematics" + File.separator + "animations" + File.separator + animationName
                + File.separator + "conf.json"));
        fw.write(configuration.toJSONString());
        fw.flush();
        fw.close();
    } catch (IOException ex) {
        p.sendMessage("Error saving Animation configuration file!");
        return false;
    }

    p.sendMessage(ChatColor.BLUE + "" + ChatColor.BOLD + "Animation " + animationName
            + " saved and ready to run! Use /anim reset to reload the configuration.");
    return true;
}

From source file:dk.dma.aisvirtualnet.Settings.java

public void save() {
    int count;/*  w w w  .  j  ava2s .  c o m*/
    Properties saveProps = new Properties();
    Map<String, AisSerialReader> serialSources = new HashMap<String, AisSerialReader>();
    Map<String, AisTcpReader> tcpSources = new HashMap<String, AisTcpReader>();
    Map<String, Transponder> transponders = new HashMap<String, Transponder>();

    count = 0;
    for (Transponder transponder : AisVirtualNet.getTransponders()) {
        transponders.put("TRANS" + (count++), transponder);
    }

    count = 0;
    for (AisReader aisReader : AisVirtualNet.getSourceReader().getReaders()) {
        String name = "SOURCE" + (count++);
        if (aisReader instanceof AisTcpReader) {
            tcpSources.put(name, (AisTcpReader) aisReader);
        } else {
            serialSources.put(name, (AisSerialReader) aisReader);
        }
    }

    saveProps.put("serial_sources", StringUtils.join(serialSources.keySet(), ","));
    for (String name : serialSources.keySet()) {
        AisSerialReader aisSerialReader = serialSources.get(name);
        saveProps.put("serial_port." + name, aisSerialReader.getPortName());
    }

    saveProps.put("tcp_sources", StringUtils.join(tcpSources.keySet(), ","));
    for (String name : tcpSources.keySet()) {
        AisTcpReader aisTcpReader = tcpSources.get(name);
        saveProps.put("tcp_source_host." + name, aisTcpReader.getHostname());
        saveProps.put("tcp_source_port." + name, Integer.toString(aisTcpReader.getPort()));
    }

    saveProps.put("transponders", StringUtils.join(transponders.keySet(), ","));
    for (String name : transponders.keySet()) {
        Transponder transponder = transponders.get(name);
        saveProps.put("transponder_mmsi." + name, Long.toString(transponder.getMmsi()));
        saveProps.put("transponder_tcp_port." + name, Integer.toString(transponder.getTcpPort()));
        saveProps.put("transponder_own_message_force." + name,
                Integer.toString(transponder.getForceOwnInterval()));
    }

    try {
        FileWriter outFile = new FileWriter(filename);
        saveProps.store(outFile, "AisVirtualNet settings");
        outFile.close();
    } catch (IOException e) {
        LOG.error("Failed to save settings: " + e.getMessage());
    }
}

From source file:com.roncoo.pay.reconciliation.fileDown.impl.AlipayFileDown.java

/**
 * ?//  w w w .  j  a  v a 2s  . c  o  m
 * 
 * @param bill_date
 *            ?
 * @param stringResult
 *            
 * @param dir
 *            ?
 * @return
 * @throws IOException
 */
private File createFile(String bill_date, String stringResult, String dir) throws IOException {

    // ?
    // String dir = "/home/roncoo/app/accountcheck/billfile/alipay";
    File file = new File(dir, bill_date + "_" + ".xml");
    int index = 1;
    // ??
    while (file.exists()) {
        file = new File(dir, bill_date + "_" + index + ".xml");
        index++;
    }

    // ?,?
    if (!file.getParentFile().exists()) {
        if (!file.getParentFile().mkdirs()) {
            // 
            throw new IOException("(), filepath: " + file.getAbsolutePath());
        }
    }
    // ??
    if (!file.exists()) {
        if (!file.createNewFile()) {
            // 
            throw new IOException(", filepath: " + file.getAbsolutePath());
        }
    }

    try {
        // ??
        FileWriter fileWriter = new FileWriter(file);
        fileWriter.write(stringResult);
        fileWriter.close(); // ??

    } catch (IOException e) {
        LOG.info("??:" + e);
    }

    return file;
}

From source file:com.zimbra.doc.soap.changelog.SoapApiChangeLog.java

private void writeChangelog() throws IOException, TemplateException {
    File templateDirFile = new File(templateDir, CHANGELOG_TEMPLATE_SUBDIR);
    Configuration config = new Configuration();
    config.setDirectoryForTemplateLoading(templateDirFile);
    config.setObjectWrapper(new BeansWrapper());
    fmTemplate = config.getTemplate(TEMPLATE_FILE);
    File of = new File(outputDir, OUTPUT_FILE);
    FileWriter out = new FileWriter(of);
    try {// w w  w. j ava2s. c om
        fmTemplate.process(changelogDataModel, out);
    } finally {
        try {
            out.close();
        } catch (Exception e) {
            // worst case scenario...clean-up quietly
        }
    }
}

From source file:com.github.thesmartenergy.sparql.generate.jena.engine.TestBase.java

void testPlanExecution() throws Exception {
    String query = IOUtils.toString(fileManager.open("query.rqg"), "UTF-8");
    System.out.println("query is: \n" + query);
    SPARQLGenerateQuery q = (SPARQLGenerateQuery) QueryFactory.create(query, SPARQLGenerate.SYNTAX);

    // create generation plan
    PlanFactory factory = new PlanFactory(fileManager);
    RootPlan plan = factory.create(q);/*from   ww w .j  av  a 2 s  .  co  m*/
    Model output = ModelFactory.createDefaultModel();
    QuerySolutionMap initialBinding = null;

    // execute plan
    plan.exec(initialBinding, output);

    // write output

    String fileName = exampleDir.toString() + "/output.ttl";
    FileWriter out = new FileWriter(fileName);
    try {
        output.write(out, "TTL");
    } finally {
        try {
            out.close();
        } catch (IOException closeException) {
            LOG.debug("Error while writing to file");
        }
    }

    fileName = exampleDir.toString() + "/output.ttl";
    out = new FileWriter(fileName);
    try {
        output.write(out, "TTL");
    } finally {
        try {
            out.close();
        } catch (IOException closeException) {
            LOG.debug("Error while writing to file");
        }
    }

    URI expectedOutputUri = exampleDir.toURI().resolve("expected_output.ttl");
    Model expectedOutput = RDFDataMgr.loadModel(expectedOutputUri.toString());
    StringWriter sw = new StringWriter();
    LOG.debug(expectedOutput.write(sw, "TTL"));

    assertTrue(output.isIsomorphicWith(expectedOutput));
}

From source file:gov.nih.nci.caintegrator.domain.application.AbstractPersistedAnalysisJob.java

/**
 * Writes the job description to the given file.
 * @param file to write to.//from  w  w  w . j av a  2  s .  c  o m
 * @throws IOException if unable to write to file.
 */
public void writeJobDescriptionToFile(File file) throws IOException {
    FileWriter fw = new FileWriter(file);
    fw.append(toString());
    fw.flush();
    fw.close();
}