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.amalto.workbench.editors.XSDDriver.java

public String outputXSD_UTF_8(String src, String fileName) {
    // File file = new File(fileName);
    try {/* w w w  . jav  a2 s  .  co  m*/
        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;
}

From source file:de.dentrassi.pm.maven.internal.MavenRepositoryChannelAggregator.java

private void makePrefixes(final OutputStream stream, final Set<String> groupIds) throws IOException {
    final OutputStreamWriter writer = new OutputStreamWriter(stream, StandardCharsets.UTF_8);

    writer.write("## repository-prefixes/2.0" + NL);
    writer.write("#" + NL);
    writer.write("# Generated by Package Drone " + VersionInformation.VERSION + NL);

    final String[] groups = groupIds.toArray(new String[groupIds.size()]);
    Arrays.sort(groups);// w  w  w  .  j a  v  a  2 s .  co m
    for (final String groupId : groups) {
        writer.write("/");
        writer.write(groupId.replace(".", "/"));
        writer.write(NL);
    }

    writer.close();
}

From source file:game.Clue.JerseyClient.java

public void requestLogintoServer(String name) {

    try {//from  w w w  .  ja v  a  2  s  . com
        for (int i = 0; i < 6; i++) {
            JSONObject jsonObject = new JSONObject(name);

            URL url = new URL(
                    "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/player"
                            + i);
            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 for logging into server");
            out.close();
        }
    } catch (Exception e) {
        e.printStackTrace();

    }

}

From source file:de.uni_koeln.spinfo.maalr.services.editor.server.EditorServiceImpl.java

public void export(Set<String> fields, MaalrQuery query, File dest) throws IOException, InvalidQueryException,
        NoIndexAvailableException, BrokenIndexException, InvalidTokenOffsetsException {
    query.setPageNr(0);//from  w ww .  j a va2  s.co m
    query.setPageSize(50);
    ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(dest));
    zout.putNextEntry(new ZipEntry("exported.tsv"));
    OutputStream out = new BufferedOutputStream(zout);
    OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
    for (String field : fields) {
        writer.write(field);
        writer.write("\t");
    }
    writer.write("\n");
    while (true) {
        QueryResult result = index.query(query, false);
        if (result == null || result.getEntries() == null || result.getEntries().size() == 0)
            break;
        List<LemmaVersion> entries = result.getEntries();
        for (LemmaVersion version : entries) {
            write(writer, version, fields);
            writer.write("\n");
        }
        query.setPageNr(query.getPageNr() + 1);
    }
    writer.flush();
    zout.closeEntry();
    writer.close();

}

From source file:edu.csh.coursebrowser.DepartmentActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_departments);
    // Show the Up button in the action bar.
    // getActionBar().setDisplayHomeAsUpEnabled(false);
    this.getActionBar().setHomeButtonEnabled(true);
    final Bundle b = this.getIntent().getExtras();
    map_item = new HashMap<String, Department>();
    map = new ArrayList<String>();
    Bundle args = this.getIntent().getExtras();
    this.setTitle(args.getCharSequence("from"));
    try {/* ww  w  . j  a  v a2 s .  c om*/
        JSONObject jso = new JSONObject(args.get("args").toString());
        JSONArray jsa = new JSONArray(jso.getString("departments"));
        ListView lv = (ListView) this.findViewById(R.id.department_list);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, map);
        for (int i = 0; i < jsa.length(); ++i) {
            String s = jsa.getString(i);
            JSONObject obj = new JSONObject(s);
            Department dept = new Department(obj.getString("title"), obj.getString("id"),
                    obj.getString("code"));
            addItem(dept);
            Log.v("Added", dept.toString());
        }
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                String s = ((TextView) arg1).getText().toString();
                final Department department = map_item.get(s);
                new AsyncTask<String, String, String>() {
                    ProgressDialog p;

                    protected void onPreExecute() {
                        p = new ProgressDialog(DepartmentActivity.this);
                        p.setTitle("Fetching Info");
                        p.setMessage("Contacting Server...");
                        p.setCancelable(false);
                        p.show();
                    }

                    protected String doInBackground(String... dep) {
                        String params = "action=getCourses&department=" + dep[0] + "&quarter="
                                + b.getString("qCode");
                        Log.v("Params", params);
                        URL url;
                        String back = "";
                        try {
                            url = new URL("http://iota.csh.rit" + ".edu/schedule/js/browseAjax" + ".php");

                            URLConnection conn = url.openConnection();
                            conn.setDoOutput(true);
                            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
                            writer.write(params);
                            writer.flush();
                            String line;
                            BufferedReader reader = new BufferedReader(
                                    new InputStreamReader(conn.getInputStream()));

                            while ((line = reader.readLine()) != null) {
                                Log.v("Back:", line);
                                back += line;
                            }
                            writer.close();
                            reader.close();
                        } catch (MalformedURLException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            return null;
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            p.dismiss();
                            return null;
                        }
                        return back;
                    }

                    protected void onPostExecute(String s) {
                        if (s == null || s == "") {
                            new AlertError(DepartmentActivity.this, "IO Error!").show();
                            return;
                        }

                        try {
                            JSONObject jso = new JSONObject(s);
                            JSONArray jsa = new JSONArray(jso.getString("courses"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                            new AlertError(DepartmentActivity.this, "Invalid JSON From Server").show();
                            p.dismiss();
                            return;
                        }
                        Intent intent = new Intent(DepartmentActivity.this, CourseActivity.class);
                        intent.putExtra("title", department.title);
                        intent.putExtra("id", department.id);
                        intent.putExtra("code", department.code);
                        intent.putExtra("args", s);
                        startActivity(intent);
                        p.dismiss();
                    }
                }.execute(department.id);
            }

        });

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        new AlertError(this, "Invalid JSON");
        e.printStackTrace();
    }

}

From source file:de.uni_koeln.spinfo.maalr.services.editor.server.EditorServiceImpl.java

public void export(Set<String> fields, EditorQuery query, File dest)
        throws NoDatabaseAvailableException, IOException {
    query.setCurrent(0);/*from w w  w .  j  a v a  2s  . co m*/
    ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(dest));
    zout.putNextEntry(new ZipEntry("exported.tsv"));
    OutputStream out = new BufferedOutputStream(zout);
    OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
    for (String field : fields) {
        writer.write(field);
        writer.write("\t");
    }
    writer.write("\n");
    while (true) {
        LexEntryList result = Database.getInstance().queryForLexEntries(query.getUserOrIp(), query.getRole(),
                query.getVerification(), query.getVerifier(), query.getStartTime(), query.getEndTime(),
                query.getState(), query.getPageSize(), query.getCurrent(), query.getSortColumn(),
                query.isSortAscending());
        if (result == null || result.getEntries() == null || result.getEntries().size() == 0)
            break;
        for (LexEntry lexEntry : result.entries()) {
            addUserInfos(lexEntry);
            LemmaVersion version = lexEntry.getCurrent();
            write(writer, version, fields);
            writer.write("\n");
        }
        query.setCurrent(query.getCurrent() + query.getPageSize());
    }
    writer.flush();
    zout.closeEntry();
    writer.close();
}

From source file:edu.msoe.se2800.h4.Logger.java

/**
 * Example usage://  w  w  w  .j a  v  a  2 s . c o m
 * <p/>
 * <code>
 * public class PerfectPerson {<br/>
 * public static final String TAG = "Logger";<br/>
 * public PerfectPerson() {<br/>
 * Logger.INSTANCE.log(TAG, "My eyes are %s and my hair is %s", new String[]{"Green", "Blonde"});<br/> 
 * }<br/>
 * }<br/>
 * </code><br/>
 * will produce (PerfectPerson, My eyes are Green and my hair is Blonde).
 * 
 * @param tag of the class making the call.
 * @param message to be logged. Use %s to indicate fields.
 * @param args Strings to populate fields with. These need to be in the order they are found in
 *            the message
 */
public void log(String tag, String message, String[] args) {
    synchronized (this) {
        OutputStreamWriter writer = null;
        try {
            writer = new OutputStreamWriter(new FileOutputStream(FILE_NAME, true));
            DateFormat format = DateFormat.getInstance();

            // Print the date/timestamp
            writer.write(format.format(new Date()));
            writer.write(" | ");

            // Print the tag
            writer.write(tag);
            writer.write(" | ");

            if (StringUtils.countMatches(message, "%s") != args.length) {
                throw new IllegalArgumentException("The number of placeholders in (" + message
                        + ") was not the same as the number of args (" + args.length + ").");
            }
            for (String s : args) {
                message = StringUtils.replaceOnce(message, "%s", s);
            }

            // Print the message
            writer.write(message);
            writer.write("\n");
        } catch (FileNotFoundException e1) {
            System.out.println("The specified file could not be found.");
        } catch (IOException e) {
            System.out.println("Unable to connect to the logger. This call to log() will be ignored.");
        } finally {
            if (writer != null) {
                try {
                    Closeables.close(writer, true);
                } catch (IOException e) {
                }
            }
        }
    }

}

From source file:edu.caltechUcla.sselCassel.projects.jMarkets.output.OutputWriter.java

/** Output the data for the given session to the given path, if the session exists */
public boolean outputSession(int sessionId, String path) {
    try {//from   www.j  a  v  a2  s . c  om
        if (!sessionExists(sessionId)) {
            log.warn("Session " + sessionId + " does not exist -- cannot write output file");
            return false;
        }

        File file = new File(path);
        file.createNewFile();

        FileOutputStream outStream = new FileOutputStream(file);
        OutputStreamWriter writer = new OutputStreamWriter(outStream);

        OutputTable txnTable = new TransactionHistoryTable(dbw, sessionId);
        OutputFormatter formatter = new CSVFormatter();

        String output = formatter.formatTable(txnTable);

        writer.write(output);

        OutputTable orderTable = new OrderHistoryTable(dbw, sessionId);
        formatter = new CSVFormatter();

        output = formatter.formatTable(orderTable);

        writer.write(output);

        OutputTable subjectTable = new SubjectTable(dbw, sessionId);
        formatter = new CSVFormatter();
        output = formatter.formatTable(subjectTable);
        writer.write(output);

        OutputTable payoffTable = new PayoffTable(dbw, sessionId);
        output = formatter.formatTable(payoffTable);
        writer.write(output);

        writer.close();
        outStream.close();

        return true;
    } catch (Exception e) {
        log.error("Error attempting to write output file for session " + sessionId, e);
    }
    return false;
}

From source file:de.hybris.platform.marketplaceintegrationbackoffice.utils.MarketplaceintegrationbackofficeHttpUtilImpl.java

/**
 * Post data// w w w  . j a  v a2s.  c o  m
 *
 * @param url
 * @param data
 * @return boolean
 * @throws IOException
 */
@Override
public boolean post(final String url, final String data) throws IOException {
    httpURL = new URL(url);
    final HttpURLConnection conn = (HttpURLConnection) httpURL.openConnection();
    conn.setDoOutput(true);
    initConnection(conn);
    OutputStreamWriter writer = null;
    OutputStream outStream = null;
    try {
        outStream = conn.getOutputStream();
        writer = new OutputStreamWriter(outStream, "UTF-8");
        writer.write(data);
        writer.flush();
    } finally {
        if (outStream != null) {
            try {
                outStream.close();
            } catch (final IOException ex) {
                LOG.error(ex.getMessage(), ex);
            }
        }
        if (writer != null) {
            try {
                writer.close();
            } catch (final IOException ex) {
                LOG.error(ex.getMessage(), ex);
            }
        }
    }
    final int status = conn.getResponseCode();
    conn.disconnect();
    return status == HttpURLConnection.HTTP_OK;
}

From source file:com.lhtechnologies.DoorApp.AuthenticatorService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent.getAction().equals(stopAction)) {
        stopSelf();//w  w w. j  a va  2 s . com
    } else if (intent.getAction().equals(authenticateAction)) {
        //Check if we want to open the front door or flat door
        String doorToOpen = FrontDoor;
        String authCode = null;
        if (intent.hasExtra(FlatDoor)) {
            doorToOpen = FlatDoor;
            authCode = intent.getCharSequenceExtra(FlatDoor).toString();
        }

        if (intent.hasExtra(LetIn)) {
            doorToOpen = LetIn;
        }

        //Now run the connection code (Hope it runs asynchronously and we do not need AsyncTask --- NOPE --YES
        urlConnection = null;
        URL url;

        //Prepare the return intent
        Intent broadcastIntent = new Intent(AuthenticationFinishedBroadCast);

        try {
            //Try to create the URL, return an error if it fails
            url = new URL(address);

            if (!url.getProtocol().equals("https")) {
                throw new MalformedURLException("Please only use https protocol!");
            }

            String password = "password";
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(getResources().getAssets().open("LH Technologies Root CA.bks"),
                    password.toCharArray());

            TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
            tmf.init(keyStore);

            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, tmf.getTrustManagers(), null);

            urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setSSLSocketFactory(context.getSocketFactory());
            urlConnection.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            urlConnection.setConnectTimeout(15000);
            urlConnection.setRequestMethod("POST");

            urlConnection.setDoOutput(true);
            urlConnection.setChunkedStreamingMode(0);

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

            //Write our stuff to the output stream;
            out.write("deviceName=" + deviceName + "&udid=" + udid + "&secret=" + secret + "&clientVersion="
                    + clientVersion + "&doorToOpen=" + doorToOpen);
            if (doorToOpen.equals(FlatDoor)) {
                out.write("&authCode=" + authCode);
                //Put an extra in so the return knows we opened the flat door
                broadcastIntent.putExtra(FlatDoor, FlatDoor);
            }

            out.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

            //Read the answer
            String decodedString;
            String returnString = "";
            while ((decodedString = in.readLine()) != null) {
                returnString += decodedString;
            }
            in.close();

            broadcastIntent.putExtra(AuthenticatorReturnCode, returnString);

        } catch (MalformedURLException e) {
            broadcastIntent.putExtra(AuthenticatorReturnCode, ClientErrorMalformedURL);
        } catch (Exception e) {
            broadcastIntent.putExtra(AuthenticatorReturnCode, ClientErrorUndefined);
            broadcastIntent.putExtra(AuthenticatorErrorDescription, e.getLocalizedMessage());
        } finally {
            if (urlConnection != null)
                urlConnection.disconnect();
            //Now send a broadcast with the result
            sendOrderedBroadcast(broadcastIntent, null);
            Log.e(this.getClass().getSimpleName(), "Send Broadcast!");
        }
    }

}