Example usage for java.io OutputStreamWriter close

List of usage examples for java.io OutputStreamWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:org.openmrs.module.dataexchange.DataExporter.java

@Transactional
public void exportConcepts(String filePath, Set<Integer> ids) throws IOException {
    DatabaseConnection connection = getConnection();

    TableDefinition conceptTableDefinition = buildConceptTableDefinition();

    List<ITable> tables = new ArrayList<ITable>();

    try {/*from w ww  . j a va  2s  .  c om*/
        addTable(connection, tables, conceptTableDefinition, conceptTableDefinition.getPrimaryKey(), ids);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    OutputStreamWriter writer = null;
    try {
        writer = new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8");

        FlatXmlDataSet.write(new CompositeDataSet(tables.toArray(new ITable[tables.size()])), writer);

        writer.close();
    } catch (DataSetException e) {
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:cli.Manager.java

public void save() {
    String out = new JSONObject().put("username", username).put("password", password)
            .put("signalingKey", signalingKey).put("preKeyIdOffset", preKeyIdOffset)
            .put("nextSignedPreKeyId", nextSignedPreKeyId).put("axolotlStore", axolotlStore.getJson())
            .put("registered", registered).toString();
    try {/*from   w ww.  ja v a2 s  . c  o  m*/
        OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(getFileName()));
        writer.write(out);
        writer.flush();
        writer.close();
    } catch (Exception e) {
        System.err.println("Saving file error: " + e.getMessage());
    }
}

From source file:com.solidmaps.webapp.xml.GenerateFederalMapsServiceImpl.java

private MapProductEntity generateAndSaveFile(String map, CompanyEntity company, String monthYear,
        UserEntity userInsert) throws Exception {

    StringBuilder fileName = new StringBuilder();
    fileName.append("M").append(DateUtils.getYear(monthYear))
            .append(DateUtils.getMonthName(monthYear).substring(0, 3).toUpperCase())
            .append(NumberUtils.clear(company.getCnpj())).append(".txt");

    OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(FILE_PATH + fileName.toString()),
            "UTF-8");

    out.write(map);/*from   w  ww  .j ava 2  s . c  om*/
    out.close();

    MapProductEntity mapProduct = this.saveMapProducts(fileName.toString(), company, monthYear, userInsert);

    return mapProduct;

}

From source file:cz.cas.lib.proarc.common.config.AppConfigurationTest.java

@Test
public void testReadProperty() throws Exception {
    // init proarc.cfg
    final String expectedPropValue = "test-?"; // test UTF-8
    Properties props = new Properties();
    props.put(TEST_PROPERTY_NAME, expectedPropValue);
    createConfigFile(props, proarcCfg);//from  w  ww .  ja  va  2  s  .  c o  m

    AppConfiguration pconfig = factory.create(new HashMap<String, String>() {
        {
            put(AppConfiguration.PROPERTY_APP_HOME, confHome.toString());
        }
    });

    Configuration config = pconfig.getConfiguration();
    assertEquals(expectedPropValue, config.getString(TEST_PROPERTY_NAME));
    assertEquals(EXPECTED_DEFAULT_VALUE, config.getString(TEST_DEFAULT_PROPERTY_NAME));

    // test reload (like servlet reload)
    final String expectedReloadValue = "reload";
    props.put(TEST_PROPERTY_NAME, expectedReloadValue);
    OutputStreamWriter propsOut = new OutputStreamWriter(new FileOutputStream(proarcCfg), "UTF-8");
    // FileChangedReloadingStrategy waits 5s to reload changes so give it a chance
    Thread.sleep(5000);
    props.store(propsOut, null);
    propsOut.close();
    assertTrue(proarcCfg.exists());

    AppConfiguration pconfigNew = factory.create(new HashMap<String, String>() {
        {
            put(AppConfiguration.PROPERTY_APP_HOME, confHome.toString());
        }
    });

    Configuration configNew = pconfigNew.getConfiguration();
    assertEquals(expectedReloadValue, configNew.getString(TEST_PROPERTY_NAME));
    assertEquals(EXPECTED_DEFAULT_VALUE, configNew.getString(TEST_DEFAULT_PROPERTY_NAME));

    // test FileChangedReloadingStrategy
    assertEquals(expectedReloadValue, config.getString(TEST_PROPERTY_NAME));
    assertEquals(EXPECTED_DEFAULT_VALUE, config.getString(TEST_DEFAULT_PROPERTY_NAME));
}

From source file:fr.mby.saml2.sp.opensaml.query.engine.SloRequestQueryProcessor.java

/**
 * Send the SLO Response via the URL Api.
 * /* www.  j av  a2  s  . co m*/
 * @param binding
 *            the binding to use
 * @param sloResponseRequest
 *            the SLO Response request
 */
protected void sendSloResponse(final SamlBindingEnum binding, final IOutgoingSaml sloResponseRequest) {
    URL sloUrl = null;
    HttpURLConnection sloConnexion = null;

    try {
        switch (binding) {
        case SAML_20_HTTP_REDIRECT:
            final String redirectUrl = sloResponseRequest.getHttpRedirectBindingUrl();

            sloUrl = new URL(redirectUrl);
            sloConnexion = (HttpURLConnection) sloUrl.openConnection();
            sloConnexion.setReadTimeout(10000);
            sloConnexion.connect();
            break;

        case SAML_20_HTTP_POST:
            final String sloEndpointUrl = sloResponseRequest.getEndpointUrl();
            final Collection<Entry<String, String>> sloPostParams = sloResponseRequest
                    .getHttpPostBindingParams();
            final StringBuffer samlDatas = new StringBuffer(1024);
            final Iterator<Entry<String, String>> itParams = sloPostParams.iterator();
            final Entry<String, String> firstParam = itParams.next();
            samlDatas.append(firstParam.getKey());
            samlDatas.append("=");
            samlDatas.append(firstParam.getValue());
            while (itParams.hasNext()) {
                final Entry<String, String> param = itParams.next();
                samlDatas.append("&");
                samlDatas.append(param.getKey());
                samlDatas.append("=");
                samlDatas.append(param.getValue());
            }

            sloUrl = new URL(sloEndpointUrl);
            sloConnexion = (HttpURLConnection) sloUrl.openConnection();
            sloConnexion.setDoInput(true);

            final OutputStreamWriter writer = new OutputStreamWriter(sloConnexion.getOutputStream());
            writer.write(samlDatas.toString());
            writer.flush();
            writer.close();

            sloConnexion.setReadTimeout(10000);
            sloConnexion.connect();
            break;

        default:
            break;
        }

        if (sloConnexion != null) {
            final InputStream responseStream = sloConnexion.getInputStream();

            final StringWriter writer = new StringWriter();
            IOUtils.copy(responseStream, writer, "UTF-8");
            final String response = writer.toString();

            this.logger.debug(String.format("HTTP response to SLO Request sent: [%s] ", response));

            final int responseCode = sloConnexion.getResponseCode();

            final String samlMessage = sloResponseRequest.getSamlMessage();
            final String endpointUrl = sloResponseRequest.getEndpointUrl();
            if (responseCode < 0) {
                this.logger.error("Unable to send SAML 2.0 Single Logout Response [{}] to endpoint URL [{}] !",
                        samlMessage, endpointUrl);
            } else if (responseCode == 200) {
                this.logger.info("SAML 2.0 Single Logout Request correctly sent to [{}] !", endpointUrl);
            } else {
                this.logger.error(
                        "HTTP response code: [{}] ! Error while sending SAML 2.0 Single Logout Request [{}] to endpoint URL [{}] !",
                        new Object[] { responseCode, samlMessage, endpointUrl });
            }
        }

    } catch (final MalformedURLException e) {
        this.logger.error(String.format("Malformed SAML SLO request URL: [%s] !", sloUrl.toExternalForm()), e);
    } catch (final IOException e) {
        this.logger.error(String.format("Unable to send SAML SLO request URL: [%s] !", sloUrl.toExternalForm()),
                e);
    } finally {
        sloConnexion.disconnect();
    }
}

From source file:game.Clue.JerseyClient.java

public void sendPUT(String name) {
    System.out.println("SendPUT method called");
    try {//from   w  ww . ja va2s.c  o  m
        JSONObject jsonObject = new JSONObject("{name:" + name + "}");

        URL url = new URL(
                "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/game/player1");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        //setDoOutput(true);
        connection.setRequestProperty("PUT", "application/json");

        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(jsonObject.toString());

        System.out.println("Sent PUT message to server");
        out.close();

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

}

From source file:br.ufjf.taverna.core.TavernaClientBase.java

protected HttpURLConnection request(String endpoint, TavernaServerMethods method, int expectedResponseCode,
        String acceptData, String contentType, String filePath, String putData) throws TavernaException {
    HttpURLConnection connection = null;

    try {/*from w  ww .j  a v a2  s  . c o  m*/
        String uri = this.getBaseUri() + endpoint;
        URL url = new URL(uri);
        connection = (HttpURLConnection) url.openConnection();
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Cache-Control", "no-cache");
        String authorization = this.username + ":" + this.password;
        String encodedAuthorization = "Basic " + new String(Base64.encodeBase64(authorization.getBytes()));
        connection.setRequestProperty("Authorization", encodedAuthorization);
        connection.setRequestMethod(method.getMethod());

        if (acceptData != null) {
            connection.setRequestProperty("Accept", acceptData);
        }

        if (contentType != null) {
            connection.setRequestProperty("Content-Type", contentType);
        }

        if (TavernaServerMethods.GET.equals(method)) {

        } else if (TavernaServerMethods.POST.equals(method)) {
            FileReader fr = new FileReader(filePath);
            char[] buffer = new char[1024 * 10];
            int read;
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            while ((read = fr.read(buffer)) != -1) {
                writer.write(buffer, 0, read);
            }
            writer.flush();
            writer.close();
            fr.close();
        } else if (TavernaServerMethods.PUT.equals(method)) {
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(putData);
            writer.flush();
            writer.close();
        } else if (TavernaServerMethods.DELETE.equals(method)) {

        }

        int responseCode = connection.getResponseCode();
        if (responseCode != expectedResponseCode) {
            throw new TavernaException(
                    String.format("Invalid HTTP Response Code. Expected %d, actual %d, URL %s",
                            expectedResponseCode, responseCode, url));
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return connection;
}

From source file:org.mapfish.print.ShellMapPrinter.java

public void run() throws IOException, JSONException, DocumentException, InterruptedException {
    MapPrinter printer = context.getBean(MapPrinter.class);
    printer.setYamlConfigFile(new File(config));
    OutputStream outFile = null;//from  www.j  ava  2  s. c  o  m
    try {
        if (clientConfig) {
            outFile = getOutputStream("");
            final OutputStreamWriter writer = new OutputStreamWriter(outFile, Charset.forName("UTF-8"));
            JSONWriter json = new JSONWriter(writer);
            json.object();
            {
                printer.printClientConfig(json);
            }
            json.endObject();

            writer.close();

        } else {
            final InputStream inFile = getInputStream();
            final PJsonObject jsonSpec = MapPrinter
                    .parseSpec(FileUtilities.readWholeTextStream(inFile, "UTF-8"));
            outFile = getOutputStream(printer.getOutputFormat(jsonSpec).getFileSuffix());
            Map<String, String> headers = new HashMap<String, String>();
            if (referer != null) {
                headers.put("Referer", referer);
            }
            if (cookie != null) {
                headers.put("Cookie", cookie);
            }
            printer.print(jsonSpec, outFile, headers);
        }
    } finally {
        if (outFile != null)
            outFile.close();
        if (context != null)
            context.destroy();
    }
}

From source file:com.cloudera.learnavro.test.GenerateTestAvro.java

/**
 *///from   ww w.j  av  a 2  s.  com
void emitSchema(File outSchema, Schema schema) throws IOException {
    OutputStreamWriter out = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(outSchema)));
    try {
        out.write(schema.toString(true));
    } finally {
        out.close();
    }
}

From source file:com.amalto.workbench.editors.XSDDriver.java

public String outputXSD_UTF_8(String src, String fileName) {
    // File file = new File(fileName);
    try {/*from   w w  w  .ja  v a 2  s  . com*/
        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(fileName),
                DEFAULT_OUTPUT_ENCODING);
        out.write(src);
        // System.out.println("OutputStreamWriter: "+out.getEncoding());
        out.flush();
        out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        log.error(e.getMessage(), e);
        return null;
    }
    return Messages.XSDDriver_SUCCESS;
}