Example usage for java.io OutputStreamWriter flush

List of usage examples for java.io OutputStreamWriter flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:org.apache.james.postage.result.PostageRunnerResultImpl.java

private void writeUnmatchedMailResults(OutputStreamWriter outputStreamWriter) throws IOException {
    writeMailResults(this.unmatchedMailResults, outputStreamWriter);
    outputStreamWriter.flush();
}

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 {//from w  ww .  j av a2 s  . c  o m
        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:org.exoplatform.wcm.connector.fckeditor.GadgetConnector.java

/**
 * Creates the file element.//from w  ww .  ja v  a  2  s  .  c  o m
 *
 * @param document The document.
 * @param applicationCategory The application category.
 *
 * @return the element
 *
 * @throws Exception the exception
 */
private Element createFileElement(Document document, ApplicationCategory applicationCategory, String host)
        throws Exception {
    Element files = document.createElement("Files");
    List<Application> listApplication = applicationRegistryService.getApplications(applicationCategory,
            ApplicationType.GADGET);
    for (Application application : listApplication) {
        Gadget gadget = gadgetRegistryService.getGadget(application.getApplicationName());
        Element file = document.createElement("File");
        file.setAttribute("name", gadget.getName());
        file.setAttribute("fileType", "nt_unstructured");
        file.setAttribute("size", "0");
        file.setAttribute("thumbnail", gadget.getThumbnail());
        file.setAttribute("description", gadget.getDescription());

        String fullurl = "";
        if (gadget.isLocal()) {
            fullurl = "/" + PortalContainer.getCurrentRestContextName() + "/" + gadget.getUrl();
        } else {
            fullurl = gadget.getUrl();
        }
        file.setAttribute("url", fullurl);

        String data = "{\"context\":{\"country\":\"US\",\"language\":\"en\"},\"gadgets\":[{\"moduleId\":0,\"url\":\""
                + fullurl + "\",\"prefs\":[]}]}";
        URL url = new URL(host + "/eXoGadgetServer/gadgets/metadata");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();
        String strMetadata = IOUtils.toString(conn.getInputStream(), "UTF-8");
        wr.close();
        JSONObject metadata = new JSONObject(strMetadata.toString());

        ConversationState conversationState = ConversationState.getCurrent();
        String userId = conversationState.getIdentity().getUserId();
        String token = createToken(gadget.getUrl(), userId, userId, new Random().nextLong(), "default");
        JSONObject obj = metadata.getJSONArray("gadgets").getJSONObject(0);
        obj.put("secureToken", token);

        file.setAttribute("metadata", metadata.toString());
        files.appendChild(file);
    }
    return files;
}

From source file:gate.util.Files.java

/**
  * Writes aString into a temporary file located inside
  * the default temporary directory defined by JVM, using the specific
  * anEncoding./*from   w w w .  ja v a2  s . co m*/
  * An unique ID is generated and associated automaticaly with the file name.
  * @param aString the String to be written. If is null then the file will be
  * empty.
  * @param anEncoding the encoding to be used. If is null then the default
  * encoding will be used.
  * @return the tmp file containing the string.
  */
public static File writeTempFile(String aString, String anEncoding)
        throws UnsupportedEncodingException, IOException {
    File resourceFile = null;
    OutputStreamWriter writer = null;

    // Create a temporary file name
    resourceFile = File.createTempFile("gateResource", ".tmp");
    resourceFile.deleteOnExit();

    if (aString == null)
        return resourceFile;
    // Prepare the writer
    if (anEncoding == null) {
        // Use default encoding
        writer = new OutputStreamWriter(new FileOutputStream(resourceFile));

    } else {
        // Use the specified encoding
        writer = new OutputStreamWriter(new FileOutputStream(resourceFile), anEncoding);
    } // End if

    // This Action is added only when a gate.Document is created.
    // So, is for sure that the resource is a gate.Document
    writer.write(aString);
    writer.flush();
    writer.close();
    return resourceFile;
}

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_course_browser);
    ListView lv = (ListView) this.findViewById(R.id.schools);
    this.setTitle("Course Browser");

    map_items = new HashMap<String, School>();
    map = new ArrayList<String>();
    this.sp = getPreferences(MODE_WORLD_READABLE);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, map);
    this.setTitle("Course Browser");

    if (!sp.contains("firstRun")) {
        SharedPreferences.Editor e = sp.edit();
        e.putBoolean("firstRun", false);
        e.commit();/*  ww  w.  j  a va  2 s  . c  o  m*/
        Intent intent = new Intent(SchoolActivity.this, AboutActivity.class);
        startActivity(intent);
    }

    addItem(new School("01", "Saunder's College of Business"));
    addItem(new School("03", "College of Engineering"));
    addItem(new School("05", "College of Liberal Arts"));
    addItem(new School("06", "Applied Science & Technology"));
    addItem(new School("08", "NTID"));
    addItem(new School("10", "College of Science"));
    addItem(new School("11", "Wellness"));
    addItem(new School("17", "Academic Services"));
    addItem(new School("20", "Imaging Arts and Sciences"));
    addItem(new School("30", "Interdisciplinary Studies"));
    addItem(new School("40", "GCCIS"));
    addItem(new School("50", "Institute for Sustainability"));

    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 School school = map_items.get(s);
            new AsyncTask<String, String, String>() {
                ProgressDialog p;

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

                protected String doInBackground(String... school) {
                    String params = "action=getDepartments&school=" + school[0] + "&quarter=20123";
                    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();
                        return null;
                    }
                    return back;
                }

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

                    try {
                        JSONObject jso = new JSONObject(s);
                        JSONArray jsa = new JSONArray(jso.getString("departments"));
                        ArrayList<Department> depts = new ArrayList<Department>();
                        for (int i = 0; i < jsa.length(); ++i) {
                            JSONObject obj = new JSONObject(jsa.get(i).toString());
                            depts.add(new Department(obj.getString("title"), obj.getString("id"),
                                    obj.getString("code")));
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        new AlertError(SchoolActivity.this, "Invalid JSON From Server").show();
                        p.dismiss();
                        return;
                    }

                    Intent intent = new Intent(SchoolActivity.this, DepartmentActivity.class);
                    intent.putExtra("from", school.deptName);
                    intent.putExtra("args", s);
                    intent.putExtra("qCode", sp.getString("quarter", "20122"));
                    startActivity(intent);
                    p.dismiss();
                }
            }.execute(school.deptNum);
        }

    });

}

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 .j  av a 2  s.  c  om*/
        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:ncbi2rkb.SparqlProxy.java

public boolean storeData(StringBuilder query) {
    boolean ret = true;
    query = SparqlProxy.makeQuery(query);
    HttpURLConnection connection = null;
    try {//from   w w  w.  ja v  a  2 s.com
        String urlParameters = "update=" + URLEncoder.encode(query.toString(), "UTF-8");
        URL url = new URL(this.urlServer + "update");
        //Create connection
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");

        connection.setDoOutput(true);

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());

        writer.write(urlParameters);
        writer.flush();

        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String rep = "";
        while ((line = reader.readLine()) != null) {
            rep += line;
        }
        writer.close();
        reader.close();
    } catch (Exception e) {
        System.err.println("ERROR UPDATE : " + e);
        SparqlProxy.saveQueryOnFile("Query.sparql", query.toString());
        ret = false;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return ret;
}

From source file:com.contrastsecurity.ide.eclipse.core.extended.ExtendedContrastSDK.java

private HttpURLConnection makeConnection(String url, String method, Object body) throws IOException {

    HttpURLConnection connection = makeConnection(url, method);

    connection.setDoOutput(true);//from w ww  .  j  a  v a  2  s . c  o m
    connection.setRequestProperty("Content-Type", "application/json");
    OutputStream os = connection.getOutputStream();
    OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");

    osw.write(gson.toJson(body));
    osw.flush();
    osw.close();
    os.close();

    return connection;
}

From source file:com.jaspersoft.jrx.query.JRXPathQueryExecuter.java

private Document getDocumentFromUrl(Map<String, ? extends JRValueParameter> parametersMap) throws Exception {
    // Get the url...
    String urlString = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_URL);

    // add GET parameters to the urlString...
    Iterator<String> i = parametersMap.keySet().iterator();

    String div = "?";
    URL url = new URL(urlString);
    if (url.getQuery() != null)
        div = "&";

    while (i.hasNext()) {
        String keyName = "" + i.next();
        if (keyName.startsWith("XML_GET_PARAM_")) {
            String paramName = keyName.substring("XML_GET_PARAM_".length());
            String value = (String) getParameterValue(keyName);

            urlString += div + URLEncoder.encode(paramName, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8");
            div = "&";
        }//  ww  w. jav a 2  s  .  c  om
    }

    url = new URL(urlString);

    if (url.getProtocol().toLowerCase().equals("file")) {
        // do nothing
        return JRXmlUtils.parse(url.openStream());
    } else if (url.getProtocol().toLowerCase().equals("http")
            || url.getProtocol().toLowerCase().equals("https")) {
        String username = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_USERNAME);
        String password = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_PASSWORD);

        if (url.getProtocol().toLowerCase().equals("https")) {
            JRPropertiesUtil dPROP = PropertiesHelper.DPROP;
            String socketFactory = dPROP
                    .getProperty("net.sf.jasperreports.query.executer.factory.xPath.DefaultSSLSocketFactory");
            if (socketFactory == null) {
                socketFactory = dPROP.getProperty(
                        "net.sf.jasperreports.query.executer.factory.XPath.DefaultSSLSocketFactory");
            }

            if (socketFactory != null) {
                // setSSLSocketFactory
                HttpsURLConnection.setDefaultSSLSocketFactory(
                        (SSLSocketFactory) Class.forName(socketFactory).newInstance());
            } else {
                log.debug("No SSLSocketFactory defined, using default");
            }

            String hostnameVerifyer = dPROP
                    .getProperty("net.sf.jasperreports.query.executer.factory.xPath.DefaultHostnameVerifier");
            if (hostnameVerifyer == null) {
                hostnameVerifyer = dPROP.getProperty(
                        "net.sf.jasperreports.query.executer.factory.XPath.DefaultHostnameVerifier");
            }

            if (hostnameVerifyer != null) {
                // setSSLSocketFactory
                HttpsURLConnection.setDefaultHostnameVerifier(
                        (HostnameVerifier) Class.forName(hostnameVerifyer).newInstance());
            } else {
                log.debug("No HostnameVerifier defined, using default");
            }
        }

        URLConnection conn = url.openConnection();

        if (username != null && username.length() > 0 && password != null) {
            ByteArrayInputStream bytesIn = new ByteArrayInputStream((username + ":" + password).getBytes());
            ByteArrayOutputStream dataOut = new ByteArrayOutputStream();
            Base64Encoder enc = new Base64Encoder(bytesIn, dataOut);
            enc.process();
            String encoding = dataOut.toString();
            conn.setRequestProperty("Authorization", "Basic " + encoding);
        }

        // add POST parameters to the urlString...
        i = parametersMap.keySet().iterator();

        String data = "";
        div = "";
        while (i.hasNext()) {
            String keyName = "" + i.next();
            if (keyName.startsWith("XML_POST_PARAM_")) {
                String paramName = keyName.substring("XML_POST_PARAM_".length());
                String value = (String) getParameterValue(keyName);
                data += div + URLEncoder.encode(paramName, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8");
                div = "&";
            }
        }

        conn.setDoOutput(true);

        if (data.length() > 0) {
            conn.setDoInput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();
        }

        try {
            return XMLUtils.parseNoValidation(conn.getInputStream());
        } catch (SAXException e) {
            throw new JRException("Failed to parse the xml document", e);
        } catch (IOException e) {
            throw new JRException("Failed to parse the xml document", e);
        } catch (ParserConfigurationException e) {
            throw new JRException("Failed to create a document builder factory", e);
        }

        // return JRXmlUtils.parse(conn.getInputStream());
    } else {
        throw new JRException("URL protocol not supported");
    }
}

From source file:net.sourceforge.atunes.kernel.modules.network.NetworkHandler.java

/**
 * Sends a POST request with given parameters and receives response with
 * given charset/* w w  w. j ava 2  s  .  co  m*/
 * 
 * @param requestURL
 * @param params
 * @param charset
 * @return
 * @throws IOException
 */
@Override
public String readURL(final String requestURL, final Map<String, String> params, final String charset)
        throws IOException {
    URLConnection connection = getConnection(requestURL);
    connection.setUseCaches(false);
    connection.setDoInput(true);

    if (params != null && params.size() > 0) {
        connection.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(formatPOSTParameters(params));
        writer.flush();
    }

    InputStream input = null;
    try {
        input = connection.getInputStream();
        return IOUtils.toString(input, charset);
    } finally {
        ClosingUtils.close(input);
    }
}