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:com.example.abrahamsofer.ident.Camera2Fragment.java

public void sendText() throws UnsupportedEncodingException {
    // Get user defined values
    // Create data variable for sent values to server

    JSONObject toSend = new JSONObject();
    try {/*from  ww w  .  j av  a  2s.com*/
        toSend.put("Price", price);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    String text = "";
    BufferedReader reader = null;

    // Send data
    try {
        // Defined URL  where to send data
        URL url = new URL(serverAddress);
        // Send POST data request

        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(toSend.toString());
        wr.flush();

        // Get the server response

        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while ((line = reader.readLine()) != null) {
            // Append server response in string
            sb.append(line + "\n");
        }

        text = sb.toString();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {

            reader.close();
        }

        catch (Exception ex) {
        }
    }

    // Show response on activity

}

From source file:net.sourceforge.ganttproject.io.GanttCSVExport.java

/**
 * Save the project as CSV on a stream/*from w w w  .j a  v a2  s. c  o  m*/
 *
 * @throws IOException
 */
public void save(OutputStream stream) throws IOException {
    OutputStreamWriter writer = new OutputStreamWriter(stream);
    CSVFormat format = CSVFormat.DEFAULT.withEscape('\\');
    if (csvOptions.sSeparatedChar.length() == 1) {
        format = format.withDelimiter(csvOptions.sSeparatedChar.charAt(0));
    }
    if (csvOptions.sSeparatedTextChar.length() == 1) {
        format = format.withEncapsulator(csvOptions.sSeparatedTextChar.charAt(0));
    }

    CSVPrinter csvPrinter = new CSVPrinter(writer, format);

    if (csvOptions.bFixedSize) {
        // TODO The CVS library we use is lacking support for fixed size
        getMaxSize();
    }

    writeTasks(csvPrinter);

    if (myProject.getHumanResourceManager().getResources().size() > 0) {
        csvPrinter.println();
        csvPrinter.println();
        writeResources(csvPrinter);
    }
    writer.flush();
    writer.close();
}

From source file:net.mindengine.oculus.frontend.web.controllers.project.ProjectAjaxBrowseController.java

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String id = request.getParameter("id");
    if (id == null || !id.startsWith("p"))
        throw new InvalidRequest();
    Long projectId = Long.parseLong(id.substring(1));

    boolean asRoot = false;
    if (request.getParameter("asRoot") != null) {
        asRoot = true;/*from  w  ww .j a v a 2  s.  c om*/
    }
    List<Project> projects = projectDAO.getSubprojects(projectId);
    List<Test> tests = testDAO.getTestsByProjectId(projectId);

    OutputStream os = response.getOutputStream();
    response.setContentType("text/xml");
    OutputStreamWriter w = new OutputStreamWriter(os);

    w.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    w.write("<tree id=\"");
    if (projectId.equals(0L) || asRoot) {
        w.write("0");
    } else
        w.write(id);
    w.write("\">");
    for (Project project : projects) {
        w.write("<item text=\"");
        w.write(StringEscapeUtils.escapeXml(project.getName()));
        w.write("\" id=\"p");
        w.write(Long.toString(project.getId()));
        w.write("\" im0=\"tombs.gif\" im1=\"tombs_open.gif\" im2=\"tombs.gif\" ");
        if (project.getSubprojectsCount() > 0 || project.getTestsCount() > 0) {
            w.write(" child=\"1\" ");
        }
        w.write("></item>");
    }

    for (Test test : tests) {
        w.write("<item text=\"");
        w.write(StringEscapeUtils.escapeXml(test.getName()));
        w.write("\" id=\"t");
        w.write(Long.toString(test.getId()));
        w.write("\" im0=\"iconTest.png\" im1=\"iconTest.png\" im2=\"iconTest.png\" ");
        w.write("></item>");
    }
    w.write("</tree>");

    w.flush();
    w.close();
    return null;
}

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);//www  . j ava2 s  .c o 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:fr.gouv.finances.dgfip.xemelios.importers.archives.ArchiveImporter.java

protected FileInfo doImportManifeste(Document manif, String archiveName) throws IOException {
    DocumentModel dm = documentsModel.getDocumentById("manifeste2");
    String idColl = "0000";
    String libColl = "Traabilit";
    String idBudg = "00";
    String libBudg = "--";

    Pair collectivite = new Pair(idColl, libColl);
    Pair budget = new Pair(idBudg, libBudg);
    if (importedArchiveManifeste != null) {
        try {//from  w w w  .j  ava2s.c o m
            DataLayerManager.getImplementation().removeDocument(dm, budget, collectivite, archiveName + ".xml",
                    user);
        } catch (Exception ex) {
            logger.error("while dropping previous manifeste", ex);
        }
    }

    File outputFile = null;
    try {
        outputFile = new File(FileUtils.getTempDir(), archiveName + ".xml");
        Charset cs = Charset.forName("UTF-8");
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(outputFile), cs);
        osw.write(manif.toXML());
        osw.flush();
        osw.close();
        Class clazz = Class.forName(dm.getImportClass());
        Constructor cc = clazz.getConstructor(XemeliosUser.class, PropertiesExpansion.class);
        Object obj = cc.newInstance(getUser(), applicationProperties);
        if (!(obj instanceof EtatImporteur)) {
            throw new DataConfigurationException(
                    "Cette classe n'est pas un importeur.\nLe fichier de configuration qui vous a t livr est certainement invalide.\nVeuillez contacter votre fournisseur.");
        }
        EtatImporteur ei = (EtatImporteur) obj;
        // WARNING : if one name per archive (and not one per volume), change this
        ei.setArchiveName(archiveName);
        ei.setImpSvcProvider(importServiceProvider);
        importServiceProvider.setEtatImporter(ei);
        ei.setOverwriteRule("never");
        ei.setApplicationConfiguration(applicationProperties);

        ei.setDocument(dm);
        File[] fichiers = new File[] { outputFile };
        ei.setFilesToImport(fichiers);

        importServiceProvider.setCollectivite(collectivite);
        importServiceProvider.setBudget(budget);
        ei.setCollectivite(collectivite);
        ei.setBudget(budget);

        ei.run();
        FileInfo fInfo = ei.getFileInfo();
        if (ei.getWarningCount() > 0)
            fInfo.setWarningCount(ei.getWarningCount());
        return fInfo;
    } catch (Exception ex) {
        logger.error("importer", ex);
        return new FileInfo();
    } finally {
        if (outputFile.exists()) {
            outputFile.delete();
        }
    }
}

From source file:org.jared.synodroid.ds.server.SimpleSynoServer.java

/**
 * Send a request to the server./*from   w  w  w  .  ja v  a  2  s  .c  o  m*/
 * 
 * @param uriP
 *            The part of the URI ie: /webman/doit.cgi
 * @param requestP
 *            The query in the form 'param1=foo&param2=yes'
 * @param methodP
 *            The method to send this request
 * @return A JSONObject containing the response of the server
 * @throws DSMException
 */
public JSONObject sendJSONRequest(String uriP, String requestP, String methodP, boolean log, int MAX_RETRY)
        throws Exception {
    HttpURLConnection con = null;
    OutputStreamWriter wr = null;
    BufferedReader br = null;
    StringBuffer sb = null;
    Exception last_exception = null;
    try {

        // For some reason in Gingerbread I often get a response code of -1.
        // Here I retry for a maximum of MAX_RETRY to send the request and it usually succeed at the second try...
        int retry = 0;
        while (retry <= MAX_RETRY) {
            try {
                // Create the connection
                con = createConnection(uriP, requestP, methodP, log);
                // Add the parameters
                wr = new OutputStreamWriter(con.getOutputStream());
                wr.write(requestP);
                // Send the request
                wr.flush();
                wr.close();

                // Try to retrieve the session cookie
                String newCookie = con.getHeaderField("set-cookie");
                if (newCookie != null) {
                    synchronized (this) {
                        setCookie(newCookie);
                    }
                    if (DEBUG)
                        Log.v(Synodroid.DS_TAG, "Retreived cookies: " + cookies);
                }

                // Now read the reponse and build a string with it
                br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                sb = new StringBuffer();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                // Verify is response if not -1, otherwise take reason from the header
                if (con.getResponseCode() == -1) {
                    retry++;
                    last_exception = null;
                    if (DEBUG)
                        Log.w(Synodroid.DS_TAG, "Response code is -1 (retry: " + retry + ")");
                } else {
                    if (DEBUG)
                        Log.d(Synodroid.DS_TAG, "Response is: " + sb.toString());
                    JSONObject respJSO = null;
                    try {
                        respJSO = new JSONObject(sb.toString());
                    } catch (JSONException je) {
                        respJSO = new JSONObject();
                    }
                    return respJSO;
                }
            } catch (EOFException e) {
                if (DEBUG)
                    Log.w(Synodroid.DS_TAG, "Caught EOFException while contacting the server, retying...");
                retry++;
                last_exception = e;
            } catch (SocketException e) {
                if (DEBUG)
                    Log.e(Synodroid.DS_TAG, "Caught SocketException while contacting the server, stopping...");
                throw e;
            } catch (SSLHandshakeException e) {
                if (DEBUG)
                    Log.e(Synodroid.DS_TAG,
                            "Caught SSLHandshakeException while contacting the server, stopping...");
                throw e;
            } catch (FileNotFoundException e) {
                String msg = e.getMessage();
                if (DEBUG)
                    Log.e(Synodroid.DS_TAG,
                            "Could not find file " + msg + "\nProbably wrong DSM version, stopping...");
                throw e;
            } catch (Exception e) {
                if (DEBUG)
                    Log.e(Synodroid.DS_TAG, "Caught exception while contacting the server, retying...", e);
                retry++;
                last_exception = e;
            } finally {
                con.disconnect();
            }

        }
        if (last_exception != null)
            throw last_exception;
        throw new GenericException();
    }
    // Finally close everything
    finally {
        wr = null;
        br = null;
        sb = null;
        con = null;
    }
}

From source file:net.solarnetwork.web.support.SimpleXmlView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Map<String, Object> finalModel = setupDateFormat(model);

    response.setContentType(getContentType());
    String charset = getResponseCharacterEncoding();
    OutputStreamWriter out;
    try {/*w  w w.  j a va  2 s . com*/
        out = new OutputStreamWriter(response.getOutputStream(), charset);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }

    // write XML start
    out.write("<?xml version=\"1.0\" encoding=\"");
    out.write(charset);
    out.write("\"?>\n");

    Object singleBean = finalModel.size() == 1 && this.singleBeanAsRoot ? finalModel.values().iterator().next()
            : null;

    if (singleBean != null) {
        outputObject(singleBean, finalModel.keySet().iterator().next().toString(), out, rootElementAugmentor);
    } else {
        writeElement(this.rootElementName, null, out, false, rootElementAugmentor);

        for (Map.Entry<String, Object> me : finalModel.entrySet()) {
            outputObject(me.getValue(), me.getKey(), out, null);
        }

        // end root element
        closeElement(this.rootElementName, out);
    }

    out.flush();
    SDF.remove();
}

From source file:org.jared.synodroid.ds.server.SimpleSynoServer.java

/**
 * Send a request to the server.//w w  w.j a va  2  s. c o m
 * 
 * @param uriP
 *            The part of the URI ie: /webman/doit.cgi
 * @param requestP
 *            The query in the form 'param1=foo&param2=yes'
 * @param methodP
 *            The method to send this request
 * @return A JSONObject containing the response of the server
 * @throws DSMException
 */
public JSONArray sendJSONRequestArray(String uriP, String requestP, String methodP, boolean log)
        throws Exception {
    HttpURLConnection con = null;
    OutputStreamWriter wr = null;
    BufferedReader br = null;
    StringBuffer sb = null;
    Exception last_exception = null;
    try {

        // For some reason in Gingerbread I often get a response code of -1.
        // Here I retry for a maximum of MAX_RETRY to send the request and it usually succeed at the second try...
        int retry = 0;
        int MAX_RETRY = 2;
        while (retry <= MAX_RETRY) {
            try {
                // Create the connection
                con = createConnection(uriP, requestP, methodP, log);
                // Add the parameters
                wr = new OutputStreamWriter(con.getOutputStream());
                wr.write(requestP);
                // Send the request
                wr.flush();
                wr.close();

                // Try to retrieve the session cookie
                String newCookie = con.getHeaderField("set-cookie");
                if (newCookie != null) {
                    synchronized (this) {
                        setCookie(newCookie);
                    }
                    if (DEBUG)
                        Log.v(Synodroid.DS_TAG, "Retreived cookies: " + cookies);
                }

                // Now read the reponse and build a string with it
                br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                sb = new StringBuffer();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                // Verify is response if not -1, otherwise take reason from the header
                if (con.getResponseCode() == -1) {
                    retry++;
                    if (DEBUG)
                        Log.w(Synodroid.DS_TAG, "Response code is -1 (retry: " + retry + ")");
                } else {
                    if (DEBUG)
                        Log.d(Synodroid.DS_TAG, "Response is: " + sb.toString());
                    JSONArray respJSO = null;
                    try {
                        respJSO = new JSONArray(sb.toString());
                    } catch (JSONException je) {
                        respJSO = new JSONArray();
                    }
                    return respJSO;
                }
            } catch (EOFException e) {
                if (DEBUG)
                    Log.w(Synodroid.DS_TAG, "Caught EOFException while contacting the server, retying...");
                retry++;
                last_exception = e;
            } catch (SocketException e) {
                if (DEBUG)
                    Log.e(Synodroid.DS_TAG, "Caught SocketException while contacting the server, stopping...");
                throw e;
            } catch (SSLHandshakeException e) {
                if (DEBUG)
                    Log.e(Synodroid.DS_TAG,
                            "Caught SSLHandshakeException while contacting the server, stopping...");
                throw e;
            } catch (FileNotFoundException e) {
                String msg = e.getMessage();
                if (DEBUG)
                    Log.e(Synodroid.DS_TAG,
                            "Could not find file " + msg + "\nProbably wrong DSM version, stopping...");
                throw e;
            } catch (Exception e) {
                if (DEBUG)
                    Log.e(Synodroid.DS_TAG, "Caught exception while contacting the server, retying...", e);
                retry++;
                last_exception = e;
            } finally {
                con.disconnect();
            }

        }
        if (last_exception != null)
            throw last_exception;
        throw new GenericException();
    } finally {
        wr = null;
        br = null;
        sb = null;
        con = null;
    }
}

From source file:org.huahinframework.manager.rest.service.PigService.java

@Path("/dump")
@POST/*from w  w  w . ja  v a  2 s  .  c o m*/
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaTypeUtils.MULTIPART_FORM_DATA)
public void dump(@Context HttpServletResponse response, InMultiPart inMP) throws IOException {
    OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream());
    try {
        if (!inMP.hasNext()) {
            throw new RuntimeException("ARGUMENTS is empty");
        }

        JSONObject argument = createJSON(inMP.next().getInputStream());
        String dump = argument.getString(JSON_DUMP);
        if (dump == null || dump.isEmpty()) {
            error(out, "Dump is empty");
            return;
        }

        String query = argument.getString(JSON_QUERY);
        if (query == null || query.isEmpty()) {
            error(out, "Query is empty");
            return;
        }

        PigServer server = new PigServer(ExecType.MAPREDUCE, properties);
        server.registerQuery(query);
        Iterator<Tuple> ite = server.openIterator(dump);
        Schema schema = server.dumpSchema(dump);
        while (ite.hasNext()) {
            JSONObject jsonObject = new JSONObject();
            Tuple t = ite.next();
            for (int i = 0; i < t.size(); i++) {
                Object o = t.get(i);
                jsonObject.put(schema.getField(i).alias, o);
            }
            out.write(jsonObject.toString());
            out.flush();
        }
        server.shutdown();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
        log.error(e);
        error(out, e.getMessage());
    }
}

From source file:com.mocap.MocapFragment.java

public void SaveOBJ(Context context, MyGLSurfaceView glview) {
    Log.i(TAG, "DIR: ");
    float sVertices[] = glview.getsVertices();
    FileOutputStream fOut = null;
    OutputStreamWriter osw = null;

    File mFile;/*from  w ww.j  a  v  a 2  s. c o m*/

    if (Environment.DIRECTORY_PICTURES != null) {
        try {
            mFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    "mocap.obj");

            Log.i(TAG, "Long Vertices: " + sVertices.length);
            fOut = new FileOutputStream(mFile);
            osw = new OutputStreamWriter(fOut);
            osw.write("# *.obj file (Generate by Mocap 3D)\n");
            osw.flush();

            for (int i = 0; i < sVertices.length - 4; i = i + 3) {

                try {
                    String data = "v " + Float.toString(sVertices[i]) + " " + Float.toString(sVertices[i + 1])
                            + " " + Float.toString(sVertices[i + 2]) + "\n";
                    Log.i(TAG, i + ": " + data);
                    osw.write(data);
                    osw.flush();

                } catch (Exception e) {
                    Toast.makeText(context, "erreur d'criture: " + e, Toast.LENGTH_SHORT).show();
                    Log.i(TAG, "Erreur: " + e);
                }

            }

            osw.write("# lignes:\n");
            osw.write("l ");
            osw.flush();
            ;
            for (int i = 1; i < (-1 + sVertices.length / 3); i++) {
                osw.write(i + " ");
                osw.flush();
            }
            //popup surgissant pour le rsultat
            Toast.makeText(getActivity(), "Save : " + Environment.DIRECTORY_PICTURES + "/mocap.obj ",
                    Toast.LENGTH_SHORT).show();

            //lancement d'un explorateur de fichiers vers le fichier crer
            //systeme des intend
            try {
                File root = new File(Environment.DIRECTORY_PICTURES);
                Uri uri = Uri.fromFile(mFile);

                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_GET_CONTENT);
                intent.setData(uri);

                // Verify that the intent will resolve to an activity
                if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
                    Log.i(TAG, "intent pk: ");
                    getActivity().startActivityForResult(intent, 1);
                }
            } catch (Exception e) {
                Log.i(TAG, "Erreur intent: " + e);
            }
        } catch (Exception e) {
            Toast.makeText(context, "Settings not saved", Toast.LENGTH_SHORT).show();
        } finally {
            try {
                osw.close();
                fOut.close();
            } catch (IOException e) {
                Toast.makeText(context, "Settings not saved", Toast.LENGTH_SHORT).show();
            }

        }

    } else {
        Toast.makeText(context, "Pas de carte ext", Toast.LENGTH_SHORT).show();
    }
}