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:io.mingle.v1.Connection.java

public Response run(String comprehension) {
    String expr = "{ \"query\": \"" + comprehension + "\", \"limit\": 10000 }";
    try {// w ww  . j  av a2s  .com
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.connect();

        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        out.write(expr, 0, expr.length());
        out.flush();
        out.close();

        InputStream in = conn.getInputStream();
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        byte[] chunk = new byte[4096];
        int read = 0;
        while ((read = in.read(chunk)) > 0) {
            buf.write(chunk, 0, read);
        }
        in.close();

        String str = buf.toString();
        System.out.println("GOT JSON: " + str);
        return new Response(JSONValue.parse(str));
    } catch (Exception e) {
        System.err.printf("failed to execute: %s\n", expr);
        e.printStackTrace();
    }

    return null;
}

From source file:com.mobilis.android.nfc.activities.MagTekFragment.java

public static void WriteSettings(Context context, String data, String file) throws IOException {
    FileOutputStream fos = null;//from  www . j  a va2s .c  o m
    OutputStreamWriter osw = null;
    fos = context.openFileOutput(file, Context.MODE_PRIVATE);
    osw = new OutputStreamWriter(fos);
    osw.write(data);
    osw.close();
    fos.close();
}

From source file:com.ksc.auth.profile.ProfilesConfigFileWriter.java

/**
 * Write all the credential profiles to a file. Note that this method will
 * clobber the existing content in the destination file if it's in the
 * overwrite mode. Use {@link #modifyOrInsertProfiles(File, Profile...)}
 * instead, if you want to perform in-place modification on your existing
 * credentials file.//from w  w w . java 2s .  c om
 *
 * @param destination
 *            The destination file where the credentials will be written to.
 * @param overwrite
 *            If true, this method If false, this method will throw
 *            exception if the file already exists.
 * @param profiles
 *            All the credential profiles to be written.
 */
public static void dumpToFile(File destination, boolean overwrite, Profile... profiles) {
    if (destination.exists() && !overwrite) {
        throw new KscClientException("The destination file already exists. "
                + "Set overwrite=true if you want to clobber the existing "
                + "content and completely re-write the file.");
    }

    OutputStreamWriter writer;
    try {
        writer = new OutputStreamWriter(new FileOutputStream(destination, false), StringUtils.UTF8);

    } catch (IOException ioe) {
        throw new KscClientException("Unable to open the destination file.", ioe);
    }

    try {
        final Map<String, Profile> modifications = new LinkedHashMap<String, Profile>();
        for (Profile profile : profiles) {
            modifications.put(profile.getProfileName(), profile);
        }
        ProfilesConfigFileWriterHelper writerHelper = new ProfilesConfigFileWriterHelper(writer, modifications);

        writerHelper.writeWithoutExistingContent();
    } finally {
        try {
            writer.close();
        } catch (IOException ioe) {
        }
    }

}

From source file:me.cybermaxke.mobiletools.utils.converter.AlphaYamlConfiguration.java

@Override
public void save(File file) throws IOException {
    Validate.notNull(file, "File cannot be null");

    Files.createParentDirs(file);

    String data = this.saveToString();

    FileOutputStream stream = new FileOutputStream(file);
    OutputStreamWriter writer = new OutputStreamWriter(stream, Charset.forName("UTF-8"));

    try {// w ww  .j  a va  2  s  .c om
        writer.write(data);
    } finally {
        writer.close();
    }
}

From source file:io.openvidu.server.utils.CustomFileManager.java

private void writeAndCloseOnOutputStreamWriter(FileOutputStream fos, String text) throws IOException {
    OutputStreamWriter osw = null;
    try {/*from  w ww  . j a va  2 s .  co  m*/
        osw = new OutputStreamWriter(fos);
        osw.write(text);
    } finally {
        osw.close();
        fos.close();
    }
}

From source file:cd.education.data.collector.android.utilities.EncryptionUtils.java

private static void writeSubmissionManifest(EncryptedFormInformation formInfo, File submissionXml,
        List<File> mediaFiles) throws EncryptionException {

    Document d = new Document();
    d.setStandalone(true);//from  w w w.  j av  a 2s.c  o  m
    d.setEncoding(UTF_8);
    Element e = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, DATA);
    e.setPrefix(null, XML_ENCRYPTED_TAG_NAMESPACE);
    e.setAttribute(null, ID, formInfo.formId);
    if (formInfo.formVersion != null) {
        e.setAttribute(null, VERSION, formInfo.formVersion);
    }
    e.setAttribute(null, ENCRYPTED, "yes");
    d.addChild(0, Node.ELEMENT, e);

    int idx = 0;
    Element c;
    c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, BASE64_ENCRYPTED_KEY);
    c.addChild(0, Node.TEXT, formInfo.base64RsaEncryptedSymmetricKey);
    e.addChild(idx++, Node.ELEMENT, c);

    c = d.createElement(XML_OPENROSA_NAMESPACE, META);
    c.setPrefix("orx", XML_OPENROSA_NAMESPACE);
    {
        Element instanceTag = d.createElement(XML_OPENROSA_NAMESPACE, INSTANCE_ID);
        instanceTag.addChild(0, Node.TEXT, formInfo.instanceMetadata.instanceId);
        c.addChild(0, Node.ELEMENT, instanceTag);
    }
    e.addChild(idx++, Node.ELEMENT, c);
    e.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

    if (mediaFiles != null) {
        for (File file : mediaFiles) {
            c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, MEDIA);
            Element fileTag = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, FILE);
            fileTag.addChild(0, Node.TEXT, file.getName() + ".enc");
            c.addChild(0, Node.ELEMENT, fileTag);
            e.addChild(idx++, Node.ELEMENT, c);
            e.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);
        }
    }

    c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, ENCRYPTED_XML_FILE);
    c.addChild(0, Node.TEXT, submissionXml.getName() + ".enc");
    e.addChild(idx++, Node.ELEMENT, c);

    c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, BASE64_ENCRYPTED_ELEMENT_SIGNATURE);
    c.addChild(0, Node.TEXT, formInfo.getBase64EncryptedElementSignature());
    e.addChild(idx++, Node.ELEMENT, c);

    FileOutputStream fout = null;
    OutputStreamWriter writer = null;
    try {
        fout = new FileOutputStream(submissionXml);
        writer = new OutputStreamWriter(fout, UTF_8);

        KXmlSerializer serializer = new KXmlSerializer();
        serializer.setOutput(writer);
        // setting the response content type emits the xml header.
        // just write the body here...
        d.writeChildren(serializer);
        serializer.flush();
        writer.flush();
        fout.getChannel().force(true);
        writer.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        String msg = "Error writing submission.xml for encrypted submission: "
                + submissionXml.getParentFile().getName();
        Log.e(t, msg);
        throw new EncryptionException(msg, ex);
    } finally {
        IOUtils.closeQuietly(writer);
        IOUtils.closeQuietly(fout);
    }
}

From source file:at.tugraz.sss.serv.util.SSFileU.java

public static void writeStr(final String str, final String filePath) throws SSErr {

    OutputStreamWriter out = null;

    try {/*  w w  w  .  j av a  2  s.com*/

        out = new OutputStreamWriter(openOrCreateFileWithPathForWrite(filePath), SSEncodingU.utf8.toString());

        out.write(str);
    } catch (Exception error) {
        SSServErrReg.regErrThrow(error);
    } finally {

        if (out != null) {
            try {
                out.close();
            } catch (IOException ex) {
                SSLogU.err(ex);
            }
        }
    }
}

From source file:com.example.appengine.java8.LaunchDataflowTemplate.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    String project = "YOUR_PROJECT_NAME";
    String bucket = "gs://YOUR_BUCKET_NAME";

    ArrayList<String> scopes = new ArrayList<String>();
    scopes.add("https://www.googleapis.com/auth/cloud-platform");
    final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
    final AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes);

    JSONObject jsonObj = null;//from  ww  w.  ja  v  a  2  s. co  m
    try {
        JSONObject parameters = new JSONObject().put("datastoreReadGqlQuery", "SELECT * FROM Entries")
                .put("datastoreReadProjectId", project).put("textWritePrefix", bucket + "/output/");
        JSONObject environment = new JSONObject().put("tempLocation", bucket + "/tmp/")
                .put("bypassTempDirValidation", false);
        jsonObj = new JSONObject().put("jobName", "template-" + UUID.randomUUID().toString())
                .put("parameters", parameters).put("environment", environment);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    URL url = new URL(String.format("https://dataflow.googleapis.com/v1b3/projects/%s/templates"
            + ":launch?gcs_path=gs://dataflow-templates/latest/Datastore_to_GCS_Text", project));
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken());
    conn.setRequestProperty("Content-Type", "application/json");

    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    jsonObj.write(writer);
    writer.close();

    int respCode = conn.getResponseCode();
    if (respCode == HttpURLConnection.HTTP_OK) {
        response.setContentType("application/json");
        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = reader.readLine()) != null) {
            response.getWriter().println(line);
        }
        reader.close();

    } else {
        StringWriter w = new StringWriter();
        IOUtils.copy(conn.getErrorStream(), w, "UTF-8");
        response.getWriter().println(w.toString());
    }
}

From source file:com.packpublishing.asynchronousandroid.chapter7.SyncTask.java

private void uploadJsonToServer(HttpURLConnection urlConn, String body) throws Exception {
    OutputStreamWriter writer = new OutputStreamWriter(urlConn.getOutputStream());
    writer.write(body);//from   w  w  w.ja v a 2  s . c  om
    writer.flush();
    writer.close();
    int resultCode = urlConn.getResponseCode();
    if (resultCode != HttpURLConnection.HTTP_OK) {
        throw new Exception("Failed to sync with server :" + resultCode);
    }
}

From source file:com.aylien.textapi.HttpSender.java

public String post(String url, Map<String, String> parameters, Map<String, String> headers)
        throws IOException, TextAPIException {
    try {//  www.  j  av a 2  s.  c o m
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        for (Map.Entry<String, String> header : headers.entrySet()) {
            connection.setRequestProperty(header.getKey(), header.getValue());
        }
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("User-Agent", USER_AGENT);

        StringBuilder payload = new StringBuilder();
        for (Map.Entry<String, String> e : parameters.entrySet()) {
            if (payload.length() > 0) {
                payload.append('&');
            }
            payload.append(URLEncoder.encode(e.getKey(), "UTF-8")).append('=')
                    .append(URLEncoder.encode(e.getValue(), "UTF-8"));
        }

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(payload.toString());
        writer.close();

        responseHeaders = connection.getHeaderFields();

        InputStream inputStream = connection.getResponseCode() == 200 ? connection.getInputStream()
                : connection.getErrorStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        if (connection.getResponseCode() >= 300) {
            extractTextAPIError(response.toString());
        }

        return response.toString();
    } catch (MalformedURLException e) {
        throw new IOException(e);
    }
}