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:edu.cornell.mannlib.vitro.webapp.controller.datatools.dumprestore.RestoreModelsAction.java

private InputStream serialize(Collection<DumpTriple> triples) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Writer w = new OutputStreamWriter(out, "UTF-8");
    for (DumpTriple triple : triples) {
        w.write(triple.toNtriples());//from  w  w  w  . jav  a 2 s.co  m
    }
    w.close();
    return new ByteArrayInputStream(out.toByteArray());
}

From source file:org.jacocoveralls.jacocoveralls.JacocoverallsMojo.java

public void createTargetFile(JSONObject repositoryJSON) throws MojoExecutionException {
    try {/*w  w w  .j ava  2 s . com*/
        if (!targetFile.exists())
            targetFile.createNewFile();

        Writer writer = new BufferedWriter(new FileWriter(targetFile));
        writer.write(repositoryJSON.toString());
        writer.close();

    } catch (IOException e) {
        throw new MojoExecutionException("Error creating target file.", e);
    }
}

From source file:co.cask.cdap.internal.app.runtime.distributed.AbstractDistributedProgramRunner.java

private File saveHConf(Configuration conf, File file) throws IOException {
    Writer writer = Files.newWriter(file, Charsets.UTF_8);
    try {/*from  w  w w .j a va 2  s  .  com*/
        conf.writeXml(writer);
    } finally {
        writer.close();
    }
    return file;
}

From source file:co.cask.cdap.internal.app.runtime.distributed.AbstractDistributedProgramRunner.java

private File saveCConf(CConfiguration conf, File file) throws IOException {
    Writer writer = Files.newWriter(file, Charsets.UTF_8);
    try {//from ww  w . j  a  v a2  s.  c  om
        conf.writeXml(writer);
    } finally {
        writer.close();
    }
    return file;
}

From source file:com.osafe.services.OsafePayPalServices.java

public static Map<String, Object> payPalCheckoutUpdate(DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    HttpServletRequest request = (HttpServletRequest) context.get("request");
    HttpServletResponse response = (HttpServletResponse) context.get("response");

    Map<String, Object> paramMap = UtilHttp.getParameterMap(request);

    String token = (String) paramMap.get("TOKEN");
    WeakReference<ShoppingCart> weakCart = tokenCartMap.get(new TokenWrapper(token));
    ShoppingCart cart = null;/*from w w  w .j a va2 s . co  m*/
    if (weakCart != null) {
        cart = weakCart.get();
    }
    if (cart == null) {
        Debug.logError("Could locate the ShoppingCart for token " + token, module);
        return ServiceUtil.returnSuccess();
    }
    // Since most if not all of the shipping estimate codes requires a persisted contactMechId we'll create one and
    // then delete once we're done, now is not the time to worry about updating everything
    String contactMechId = null;
    Map<String, Object> inMap = FastMap.newInstance();
    inMap.put("address1", paramMap.get("SHIPTOSTREET"));
    inMap.put("address2", paramMap.get("SHIPTOSTREET2"));
    inMap.put("city", paramMap.get("SHIPTOCITY"));
    String countryGeoCode = (String) paramMap.get("SHIPTOCOUNTRY");
    String countryGeoId = OsafePayPalServices.getCountryGeoIdFromGeoCode(countryGeoCode, delegator);
    if (countryGeoId == null) {
        return ServiceUtil.returnSuccess();
    }
    inMap.put("countryGeoId", countryGeoId);
    inMap.put("stateProvinceGeoId",
            parseStateProvinceGeoId((String) paramMap.get("SHIPTOSTATE"), countryGeoId, delegator));
    inMap.put("postalCode", paramMap.get("SHIPTOZIP"));

    try {
        GenericValue userLogin = delegator.findOne("UserLogin", true, UtilMisc.toMap("userLoginId", "system"));
        inMap.put("userLogin", userLogin);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    boolean beganTransaction = false;
    Transaction parentTransaction = null;
    try {
        parentTransaction = TransactionUtil.suspend();
        beganTransaction = TransactionUtil.begin();
    } catch (GenericTransactionException e1) {
        Debug.logError(e1, module);
    }
    try {
        Map<String, Object> outMap = dispatcher.runSync("createPostalAddress", inMap);
        contactMechId = (String) outMap.get("contactMechId");
    } catch (GenericServiceException e) {
        Debug.logError(e.getMessage(), module);
        return ServiceUtil.returnSuccess();
    }
    try {
        TransactionUtil.commit(beganTransaction);
        if (parentTransaction != null)
            TransactionUtil.resume(parentTransaction);
    } catch (GenericTransactionException e) {
        Debug.logError(e, module);
    }
    // clone the cart so we can modify it temporarily
    CheckOutHelper coh = new CheckOutHelper(dispatcher, delegator, cart);
    String oldShipAddress = cart.getShippingContactMechId();
    coh.setCheckOutShippingAddress(contactMechId);
    ShippingEstimateWrapper estWrapper = new ShippingEstimateWrapper(dispatcher, cart, 0);
    int line = 0;
    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "CallbackResponse");

    for (GenericValue shipMethod : estWrapper.getShippingMethods()) {
        BigDecimal estimate = estWrapper.getShippingEstimate(shipMethod);
        //Check that we have a valid estimate (allowing zero value estimates for now)
        if (estimate == null || estimate.compareTo(BigDecimal.ZERO) < 0) {
            continue;
        }
        cart.setShipmentMethodTypeId(shipMethod.getString("shipmentMethodTypeId"));
        cart.setCarrierPartyId(shipMethod.getString("partyId"));
        try {
            coh.calcAndAddTax();
        } catch (GeneralException e) {
            Debug.logError(e, module);
            continue;
        }
        String estimateLabel = shipMethod.getString("partyId") + " - " + shipMethod.getString("description");
        encoder.add("L_SHIPINGPOPTIONLABEL" + line, estimateLabel);
        encoder.add("L_SHIPPINGOPTIONAMOUNT" + line,
                estimate.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        // Just make this first one default for now
        encoder.add("L_SHIPPINGOPTIONISDEFAULT" + line, line == 0 ? "true" : "false");
        encoder.add("L_TAXAMT" + line,
                cart.getTotalSalesTax().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        line++;
    }
    String responseMsg = null;
    try {
        responseMsg = encoder.encode();
    } catch (PayPalException e) {
        Debug.logError(e, module);
    }
    if (responseMsg != null) {
        try {
            response.setContentLength(responseMsg.getBytes("UTF-8").length);
        } catch (UnsupportedEncodingException e) {
            Debug.logError(e, module);
        }

        try {
            Writer writer = response.getWriter();
            writer.write(responseMsg);
            writer.close();
        } catch (IOException e) {
            Debug.logError(e, module);
        }
    }

    // Remove the temporary ship address
    try {
        GenericValue postalAddress = delegator.findOne("PostalAddress", false,
                UtilMisc.toMap("contactMechId", contactMechId));
        postalAddress.remove();
        GenericValue contactMech = delegator.findOne("ContactMech", false,
                UtilMisc.toMap("contactMechId", contactMechId));
        contactMech.remove();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    coh.setCheckOutShippingAddress(oldShipAddress);
    return ServiceUtil.returnSuccess();
}

From source file:net.pkhsolutions.ceres.common.builder.processor.BuildableAP.java

private void createSourceFile(String fileName, Template template, VelocityContext vc) {
    try {/*w ww .  ja va 2 s  .co m*/
        JavaFileObject jfo = processingEnv.getFiler().createSourceFile(fileName);
        Writer writer = jfo.openWriter();
        template.merge(vc, writer);
        writer.close();
    } catch (IOException e) {
        throw new RuntimeException("Could not create source file", e);
    }
}

From source file:com.streamsets.pipeline.stage.origin.spooldir.TestSpoolDirSourceOnErrorHandling.java

private SpoolDirSource createSourceIOEx() throws Exception {
    String dir = createTestDir();
    File file1 = new File(dir, "file-0.json").getAbsoluteFile();
    Writer writer = new FileWriter(file1);
    IOUtils.write("[1,", writer);
    writer.close();
    File file2 = new File(dir, "file-1.json").getAbsoluteFile();
    writer = new FileWriter(file2);
    IOUtils.write("[2]", writer);
    writer.close();// www .j  a va2 s  .  c om

    SpoolDirConfigBean conf = new SpoolDirConfigBean();
    conf.dataFormat = DataFormat.JSON;
    conf.spoolDir = dir;
    conf.batchSize = 10;
    conf.overrunLimit = 100;
    conf.poolingTimeoutSecs = 1;
    conf.filePattern = "file-[0-9].json";
    conf.maxSpoolFiles = 10;
    conf.initialFileToProcess = null;
    conf.dataFormatConfig.compression = Compression.NONE;
    conf.dataFormatConfig.filePatternInArchive = "*";
    conf.errorArchiveDir = null;
    conf.postProcessing = PostProcessingOptions.ARCHIVE;
    conf.archiveDir = dir;
    conf.retentionTimeMins = 10;
    conf.dataFormatConfig.jsonContent = JsonMode.ARRAY_OBJECTS;
    conf.dataFormatConfig.jsonMaxObjectLen = 100;
    conf.dataFormatConfig.onParseError = OnParseError.ERROR;
    conf.dataFormatConfig.maxStackTraceLines = 0;

    return new SpoolDirSource(conf);
}

From source file:com.zht.common.codegen.excute.impl.AbstractGenerator.java

/**
 * /*  w ww. j a va  2s  .  c  o  m*/
 */
public void generate(String templateFileName, Map<?, ?> data, String fileName) {
    try {
        String templateFileDir = templateFileName.substring(0, templateFileName.lastIndexOf("/"));
        String templateFile = templateFileName.substring(templateFileName.lastIndexOf("/") + 1,
                templateFileName.length());

        String genFileDir = fileName.substring(0, fileName.lastIndexOf("/"));
        Template template = GenConfigurationHelper.getConfiguration(templateFileDir).getTemplate(templateFile);
        template.setEncoding("UTF-8");
        org.apache.commons.io.FileUtils.forceMkdir(new File(genFileDir));
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8"));
        // File output = new File(fileName);
        //Writer writer = new FileWriter(output);
        template.process(data, writer);
        writer.close();
    } catch (TemplateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

private String getTargetFilePath() throws Exception {
    FileOutputStream out = mContext.openFileOutput("target.txt", mContext.MODE_WORLD_READABLE);
    Writer writer = new OutputStreamWriter(out, "UTF-8");
    writer.write("testing");
    writer.flush();/*ww  w . j  a v  a 2  s . c o m*/
    writer.close();
    return mContext.getFileStreamPath("target.txt").getAbsolutePath();
}

From source file:org.ofbiz.common.CommonServices.java

public static Map<String, Object> streamTest(DispatchContext dctx, Map<String, ?> context) {
    InputStream in = (InputStream) context.get("inputStream");
    OutputStream out = (OutputStream) context.get("outputStream");

    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    Writer writer = new OutputStreamWriter(out);
    String line;//ww  w.  j  ava2 s . c  om

    try {
        while ((line = reader.readLine()) != null) {
            Debug.log("Read line: " + line, module);
            writer.write(line);
        }
    } catch (IOException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    } finally {
        try {
            writer.close();
        } catch (Exception e) {
            Debug.logError(e, module);
        }
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("contentType", "text/plain");
    return result;
}