Example usage for java.io OutputStreamWriter write

List of usage examples for java.io OutputStreamWriter write

Introduction

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

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:com.nextgis.firereporter.GetFiresService.java

protected boolean writeToFile(File filePath, String sData) {
    try {//www.j a va  2  s.  c  o m
        FileOutputStream os = new FileOutputStream(filePath, false);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(os);
        outputStreamWriter.write(sData);
        outputStreamWriter.close();
        return true;
    } catch (IOException e) {
        SendError(e.getLocalizedMessage());
        return false;
    }
}

From source file:gate.creole.gazetteer.GazetteerList.java

/**
 * Stores the list to the specified url/* ww w.j  a va2 s.c om*/
 * 
 * @throws ResourceInstantiationException
 */
public void store() throws ResourceInstantiationException {
    try {
        if (null == url) {
            throw new ResourceInstantiationException("URL not specified (null)");
        }

        File fileo = Files.fileFromURL(url);

        fileo.delete();
        OutputStreamWriter listWriter = new OutputStreamWriter(new FileOutputStream(fileo), encoding);
        // BufferedWriter listWriter = new BufferedWriter(new
        // FileWriter(fileo));
        Iterator<GazetteerNode> iter = entries.iterator();
        while (iter.hasNext()) {
            listWriter.write(iter.next().toString());
            listWriter.write(13);
            listWriter.write(10);
        }
        listWriter.close();
    } catch (Exception x) {
        throw new ResourceInstantiationException(x.getClass() + ":" + x.getMessage());
    }
    isModified = false;
}

From source file:com.createtank.payments.coinbase.CoinbaseApi.java

private boolean doTokenRequest(Map<String, String> params) throws IOException {
    Map<String, String> paramsBody = new HashMap<String, String>();
    paramsBody.put("client_id", clientId);
    paramsBody.put("client_secret", clientSecret);
    paramsBody.putAll(params);/*from   www .j av  a  2 s  .  co  m*/

    String bodyStr = RequestClient.createRequestParams(paramsBody);
    System.out.println(bodyStr);
    HttpURLConnection conn = (HttpsURLConnection) new URL(OAUTH_BASE_URL + "/token").openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(bodyStr);
    writer.flush();
    writer.close();

    int code = conn.getResponseCode();

    if (code == 401) {
        return false;
    } else if (code != 200) {
        throw new IOException("Got HTTP response code " + code);
    }
    String response = RequestClient.getResponseBody(conn.getInputStream());

    JsonParser parser = new JsonParser();
    JsonObject content = (JsonObject) parser.parse(response);
    System.out.print("content: " + content.toString());
    accessToken = content.get("access_token").getAsString();
    refreshToken = content.get("refresh_token").getAsString();
    return true;
}

From source file:com.entertailion.android.shapeways.api.ShapewaysClient.java

/**
 * Call a Shapeways API with POST//w  w  w .j a  v  a2 s .c om
 * 
 * @param apiUrl
 * @return
 * @throws Exception
 */
private String postResponseOld(String apiUrl, Map<String, String> parameters) throws Exception {
    Log.d(LOG_TAG, "postResponse: url=" + apiUrl);
    URLConnection urlConnection = getUrlConnection(apiUrl, true);

    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());

    Request request = new Request(POST);
    request.addParameter(OAUTH_CONSUMER_KEY, consumerKey);
    request.addParameter(OAUTH_TOKEN, oauthToken);

    for (String key : parameters.keySet()) {
        request.addParameter(key, parameters.get(key));
    }

    request.sign(apiUrl, consumerSecret, oauthTokenSecret);
    outputStreamWriter.write(request.toString());
    outputStreamWriter.close();

    return readResponse(urlConnection.getInputStream());
}

From source file:com.megahardcore.config.MHCConfig.java

private void writeHeader() {
    if (mHeader == null)
        return;//from   w  ww .ja  v  a2  s .c om
    ByteArrayOutputStream memHeaderStream = null;
    OutputStreamWriter memWriter = null;
    try {
        //Write Header to a temporary file
        memHeaderStream = new ByteArrayOutputStream();
        memWriter = new OutputStreamWriter(memHeaderStream, Charset.forName("UTF-8").newEncoder());
        memWriter.write(mHeader.toString());
        memWriter.close();
        //Copy Header to the beginning of the config file
        IoHelper.writeHeader(mConfigFile, memHeaderStream);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (memHeaderStream != null)
                memHeaderStream.close();
            if (memWriter != null)
                memWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:fi.cosky.sdk.API.java

private <T extends BaseData> T sendRequest(Link l, Class<T> tClass, Object object) throws IOException {
    URL serverAddress;//  ww  w . ja v  a  2  s. c  o m
    BufferedReader br;
    String result = "";
    HttpURLConnection connection = null;
    String url = l.getUri().contains("://") ? l.getUri() : this.baseUrl + l.getUri();
    try {
        String method = l.getMethod();
        String type = l.getType();

        serverAddress = new URL(url);
        connection = (HttpURLConnection) serverAddress.openConnection();
        boolean doOutput = doOutput(method);
        connection.setDoOutput(doOutput);
        connection.setRequestMethod(method);
        connection.setInstanceFollowRedirects(false);

        if (method.equals("GET") && useMimeTypes)
            if (type == null || type.equals("")) {
                addMimeTypeAcceptToRequest(object, tClass, connection);
            } else {
                connection.addRequestProperty("Accept", helper.getSupportedType(type));
            }
        if (!useMimeTypes)
            connection.setRequestProperty("Accept", "application/json");

        if (doOutput && useMimeTypes) {
            //this handles the case if the link is self made and the type field has not been set.
            if (type == null || type.equals("")) {
                addMimeTypeContentTypeToRequest(l, tClass, connection);
                addMimeTypeAcceptToRequest(l, tClass, connection);
            } else {
                connection.addRequestProperty("Accept", helper.getSupportedType(type));
                connection.addRequestProperty("Content-Type", helper.getSupportedType(type));
            }
        }

        if (!useMimeTypes)
            connection.setRequestProperty("Content-Type", "application/json");

        if (tokenData != null) {
            connection.addRequestProperty("Authorization",
                    tokenData.getTokenType() + " " + tokenData.getAccessToken());
        }

        addVersionNumberToHeader(object, url, connection);

        if (method.equals("POST") || method.equals("PUT")) {
            String json = object != null ? gson.toJson(object) : ""; //should handle the case when POST without object.
            connection.addRequestProperty("Content-Length", json.getBytes("UTF-8").length + "");
            OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
            osw.write(json);
            osw.flush();
            osw.close();
        }

        connection.connect();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED
                || connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER) {
            ResponseData data = new ResponseData();
            Link link = parseLocationLinkFromString(connection.getHeaderField("Location"));
            link.setType(type);
            data.setLocation(link);
            connection.disconnect();
            return (T) data;
        }

        if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            System.out.println(
                    "Authentication expired " + connection.getResponseMessage() + " trying to reauthenticate");
            if (retry && this.tokenData != null) {
                this.tokenData = null;
                retry = false;
                if (authenticate()) {
                    System.out.println("Reauthentication success, will continue with " + l.getMethod()
                            + " request on " + l.getRel());
                    return sendRequest(l, tClass, object);
                }
            } else
                throw new IOException(
                        "Tried to reauthenticate but failed, please check the credentials and status of NFleet-API");
        }

        if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
            return (T) objectCache.getObject(url);
        }

        if (connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) {
            return (T) new ResponseData();
        }

        if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST
                && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) {
            System.out.println("ErrorCode: " + connection.getResponseCode() + " "
                    + connection.getResponseMessage() + " " + url + ", verb: " + method);

            String errorString = readErrorStreamAndCloseConnection(connection);
            throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class);
        } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) {
            if (retry) {
                System.out.println("Request caused internal server error, waiting " + RETRY_WAIT_TIME
                        + " ms and trying again.");
                return waitAndRetry(connection, l, tClass, object);
            } else {
                System.out.println("Requst caused internal server error, please contact dev@nfleet.fi");
                String errorString = readErrorStreamAndCloseConnection(connection);
                throw new IOException(errorString);
            }
        }

        if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_GATEWAY) {
            if (retry) {
                System.out.println("Could not connect to NFleet-API, waiting " + RETRY_WAIT_TIME
                        + " ms and trying again.");
                return waitAndRetry(connection, l, tClass, object);
            } else {
                System.out.println(
                        "Could not connect to NFleet-API, please check service status from http://status.nfleet.fi and try again later.");
                String errorString = readErrorStreamAndCloseConnection(connection);
                throw new IOException(errorString);
            }

        }

        result = readDataFromConnection(connection);

    } catch (MalformedURLException e) {
        throw e;
    } catch (ProtocolException e) {
        throw e;
    } catch (UnsupportedEncodingException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } catch (SecurityException e) {
        throw e;
    } catch (IllegalArgumentException e) {
        throw e;
    } finally {
        assert connection != null;
        connection.disconnect();
    }
    Object newEntity = gson.fromJson(result, tClass);
    objectCache.addUri(url, newEntity);
    return (T) newEntity;
}

From source file:com.extrahardmode.config.EHMConfig.java

private void writeHeader() {
    if (mHeader == null)
        return;/*  w  ww .java  2  s .  c  o  m*/
    ByteArrayOutputStream memHeaderStream = null;
    OutputStreamWriter memWriter = null;
    try {
        //Write Header to a temporary file
        memHeaderStream = new ByteArrayOutputStream();
        memWriter = new OutputStreamWriter(memHeaderStream, Charset.forName("UTF-8").newEncoder());
        memWriter.write(String.format(mHeader.toString()));
        memWriter.close();
        //Copy Header to the beginning of the config file
        IoHelper.writeHeader(mConfigFile, memHeaderStream);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (memHeaderStream != null)
                memHeaderStream.close();
            if (memWriter != null)
                memWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.hangum.tadpole.importdb.core.dialog.importdb.csv.CsvToRDBImportDialog.java

private void saveLog() {
    try {//  w w  w.ja  v  a2s .  c  o  m
        if ("".equals(textSQL.getText())) { //$NON-NLS-1$
            MessageDialog.openError(null, Messages.CsvToRDBImportDialog_4,
                    Messages.SQLToDBImportDialog_LogEmpty);
            return;
        }
        String filename = PublicTadpoleDefine.TEMP_DIR + userDB.getDisplay_name() + "_SQLImportResult.log"; //$NON-NLS-1$

        FileOutputStream fos = new FileOutputStream(filename);
        OutputStreamWriter bw = new OutputStreamWriter(fos, "UTF-8"); //$NON-NLS-1$

        bw.write(textSQL.getText());
        bw.close();

        String strImportResultLogContent = FileUtils.readFileToString(new File(filename));

        downloadExtFile(userDB.getDisplay_name() + "_SQLImportResult.log", strImportResultLogContent);//sbExportData.toString()); //$NON-NLS-1$
    } catch (Exception ee) {
        logger.error("log writer", ee); //$NON-NLS-1$
    }
}

From source file:biblivre3.cataloging.holding.HoldingBO.java

private File createIsoFile(Database database) {
    try {/*from  w ww  .j a  v  a 2  s. c  o m*/
        File file = File.createTempFile("bib3_", null);
        FileOutputStream fos = new FileOutputStream(file);
        OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8");
        HoldingDAO holdingDao = new HoldingDAO();
        int limit = 100;
        int recordCount = holdingDao.countAll(database);

        for (int offset = 0; offset < recordCount; offset += limit) {
            List<HoldingDTO> records = holdingDao.list(database, offset, limit);
            for (HoldingDTO dto : records) {
                writer.write(dto.getIso2709());
                writer.write(ApplicationConstants.LINE_BREAK);
            }
        }
        writer.flush();
        writer.close();
        return file;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return null;
}

From source file:com.googlecode.CallerLookup.Main.java

public void saveUserLookupEntries() {
    try {/*from ww  w .j  a v a  2 s .co  m*/
        FileOutputStream file = getApplicationContext().openFileOutput(SAVED_FILE, MODE_PRIVATE);
        JSONArray userLookupEntries = new JSONArray();
        for (String lookupEntryName : mUserLookupEntries.keySet()) {
            try {
                userLookupEntries.put(mUserLookupEntries.get(lookupEntryName).toJSONObject());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        OutputStreamWriter content = new OutputStreamWriter(file);
        content.write(userLookupEntries.toString());
        content.flush();
        content.close();
        file.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}