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:net.mindengine.oculus.frontend.web.controllers.SimpleAjaxController.java

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    AjaxModel model = null;/*from   ww  w.  java  2  s .  c o  m*/
    try {
        model = handleController(request);
        if (model == null)
            throw new Exception("The controller returned null model");
    } catch (Exception ex) {
        logger.error(ex, ex);
        model = new AjaxModel(ex);
    }

    OutputStream os = response.getOutputStream();
    OutputStreamWriter w = new OutputStreamWriter(os);
    response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");

    JSONValue jsonValue = JSONMapper.toJSON(model);
    w.write(jsonValue.render(true));

    w.flush();
    os.flush();
    os.close();

    return null;
}

From source file:com.culvereq.vimp.networking.ConnectionHandler.java

public String login(String username, String password) throws IOException {
    URL requestURL = new URL(loginURL);
    HttpURLConnection connection = (HttpURLConnection) requestURL.openConnection();
    connection.setDoInput(true);/*from ww  w . j ava2s .c om*/
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("charset", "utf-8");
    String urlParameters = "";
    urlParameters += "username=" + username;
    urlParameters += "&password=" + password;

    connection.setRequestProperty("Content-Length", "" + urlParameters.getBytes().length);
    connection.setUseCaches(false);
    OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    writer.write(urlParameters);
    writer.flush();
    writer.close();

    int responseCode = connection.getResponseCode();
    if (responseCode == 200) {
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString().trim();
    } else {
        return null;
    }
}

From source file:de.uni_koeln.spinfo.maalr.webapp.controller.EditorController.java

@RequestMapping("/editor/download/{fileName}.html")
public void export(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {
    File dir = new File("exports");
    File file = new File(dir, fileName);
    ServletOutputStream out = response.getOutputStream();
    if (!file.exists()) {
        OutputStreamWriter writer = new OutputStreamWriter(out);
        writer.write("This link has expired. Please re-export the data and try again.");
        writer.flush();
        return;//  w  w  w.ja  va  2s  .  c  o  m
    }
    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
    IOUtils.copy(in, out);
    in.close();
    out.close();
    file.delete();
}

From source file:net.wasdev.maven.plugins.swaggerdocgen.SwaggerProcessor.java

public void process() {
    final String document = getDocument();
    if (document != null) {
        OutputStreamWriter writer = null;
        try {// ww  w.  j a  va 2  s .co m
            writer = new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8");
            writer.write(document);
            writer.flush();
        } catch (IOException ioe) {
            logger.severe("Failed to write to the output document " + outputFile.getAbsolutePath());
        } finally {
            tryToClose(writer);
        }
    }
}

From source file:com.personalserver.DirCommandHandler.java

private HttpEntity getEntityFromUri(String uri, HttpResponse response) {
    String contentType = "text/html";
    String filepath = FOLDER_SHARE_PATH;

    if (uri.equalsIgnoreCase("/") || uri.length() <= 0) {
        filepath = FOLDER_SHARE_PATH + "/";
    } else {/*from  w ww .ja  va 2s .c om*/
        filepath = FOLDER_SHARE_PATH + "/" + URLDecoder.decode(uri);
    }

    System.out.println("request uri : " + uri);
    System.out.println("FOLDER SHARE PATH : " + FOLDER_SHARE_PATH);
    System.out.println("filepath : " + filepath);

    final File file = new File(filepath);

    HttpEntity entity = null;

    if (file.isDirectory()) {
        entity = new EntityTemplate(new ContentProducer() {
            public void writeTo(final OutputStream outstream) throws IOException {
                OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                String resp = getDirListingHTML(file);

                writer.write(resp);
                writer.flush();
            }
        });

        response.setHeader("Content-Type", contentType);
    } else if (file.exists()) {
        contentType = URLConnection.guessContentTypeFromName(file.getAbsolutePath());

        entity = new FileEntity(file, contentType);

        response.setHeader("Content-Type", contentType);
    } else {
        entity = new EntityTemplate(new ContentProducer() {
            public void writeTo(final OutputStream outstream) throws IOException {
                OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                String resp = "<html>" + "<head><title>ERROR : NOT FOUND</title></head>" + "<body>"
                        + "<center><h1>FILE OR DIRECTORY NOT FOUND !</h1></center>"
                        + "<p>Sorry, file or directory you request not available<br />"
                        + "Contact your administrator<br />" + "</p>" + "</body></html>";

                writer.write(resp);
                writer.flush();
            }
        });
        response.setHeader("Content-Type", "text/html");
    }

    return entity;
}

From source file:com.culvereq.vimp.networking.ConnectionHandler.java

public ServiceRecord addServiceRecord(TempServiceRecord serviceRecord) throws IOException, JSONException {
    URL requestURL = new URL(serviceURL + "add");
    HttpURLConnection connection = (HttpURLConnection) requestURL.openConnection();
    connection.setDoInput(true);/*from   w  w  w.  j  av a2s  . c  om*/
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("charset", "utf-8");
    String urlParameters = "";
    urlParameters += "key=" + Globals.access_key;
    urlParameters += "&vehicle-id=" + serviceRecord.getParentVehicle().getId();
    urlParameters += "&type-id=" + serviceRecord.getType().getValue();
    urlParameters += "&service-desc=" + serviceRecord.getDescription();
    urlParameters += "&service-date=" + serviceRecord.getServiceDate().getMillis() / 1000L;
    urlParameters += "&service-mileage=" + serviceRecord.getMileage();
    connection.setRequestProperty("Content-Length", "" + urlParameters.getBytes().length);
    connection.setUseCaches(false);
    OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    writer.write(urlParameters);
    writer.flush();
    writer.close();

    int responseCode = connection.getResponseCode();
    if (responseCode == 201) {
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        JSONObject json = new JSONObject(response.toString());
        return new Deserializer().deserializeService(json, response.toString());
    } else if (responseCode == 400) {
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        throw new IOException(response.toString());
    } else {
        throw new IOException("Got response code: " + responseCode);
    }
}

From source file:com.kurento.kmf.content.internal.ControlProtocolManager.java

/**
 * Internal implementation for sending JSON (called from sendJsonAnswer and
 * sendJsonError methods)./*from  ww w  .j av a2 s .  com*/
 * 
 * @param asyncCtx
 *            Asynchronous context
 * @param message
 *            JSON message (as a Java class)
 * @throws IOException
 *             Exception while parsing operating with asynchronous context
 */
private void internalSendJsonAnswer(AsyncContext asyncCtx, JsonRpcResponse message) {
    try {
        if (asyncCtx == null) {
            throw new KurentoMediaFrameworkException("Null asyncCtx found", 20017);
        }

        synchronized (asyncCtx) {
            if (!asyncCtx.getRequest().isAsyncStarted()) {
                throw new KurentoMediaFrameworkException("Cannot send message in completed asyncCtx", 1); // TODO
            }

            HttpServletResponse response = (HttpServletResponse) asyncCtx.getResponse();
            response.setContentType("application/json");
            OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream(), UTF8);
            osw.write(gson.toJson(message));
            osw.flush();
            log.info("Sent JsonRpc answer ...\n" + message);
            asyncCtx.complete();
        }
    } catch (IOException ioe) {
        throw new KurentoMediaFrameworkException(ioe.getMessage(), ioe, 20018);
    }
}

From source file:com.github.nethad.clustermeister.provisioning.cli.Provisioning.java

private void createDefaultConfiguration(String configFilePath) {
    final File configFile = new File(configFilePath);
    if (configFile.exists()) {
        return;// w  w  w .j  a  va 2s .  c om
    }
    configFile.getParentFile().mkdirs();

    OutputSupplier<OutputStreamWriter> writer = Files.newWriterSupplier(configFile, Charsets.UTF_8);
    OutputStreamWriter output = null;
    try {
        output = writer.getOutput();
        output.append(YamlConfiguration.defaultConfiguration());
        output.flush();
        output.close();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException ex) {
                // ignore
            }
        }
    }
}

From source file:com.culvereq.vimp.networking.ConnectionHandler.java

public Vehicle addVehicle(TempVehicle vehicle) throws IOException, JSONException {
    URL requestURL = new URL(vehicleURL + "add");
    HttpURLConnection connection = (HttpURLConnection) requestURL.openConnection();
    connection.setDoInput(true);//www  .  ja  va  2  s  .c om
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("charset", "utf-8");
    String urlParameters = "";
    urlParameters += "key=" + Globals.access_key;
    urlParameters += "&vehicle-name=" + vehicle.getName();
    urlParameters += "&vehicle-type-id=" + vehicle.getType().getValue();
    urlParameters += "&vehicle-make=" + vehicle.getMake();
    urlParameters += "&vehicle-model" + vehicle.getModel();
    urlParameters += "&vehicle-year" + vehicle.getYear();
    urlParameters += "&vehicle-mileage" + vehicle.getMileage();
    urlParameters += "&vehicle-vin" + vehicle.getVin();
    urlParameters += "&vehicle-license-no" + vehicle.getLicenseNumber();

    connection.setRequestProperty("Content-Length", "" + urlParameters.getBytes().length);
    connection.setUseCaches(false);
    OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    writer.write(urlParameters);
    writer.flush();
    writer.close();

    int responseCode = connection.getResponseCode();
    if (responseCode == 201) {
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        JSONObject json = new JSONObject(response.toString());
        return new Deserializer().deserializeVehicle(json, response.toString());
    } else if (responseCode == 400) {
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        throw new IOException(response.toString());
    } else {
        throw new IOException("Got response code: " + responseCode);
    }
}

From source file:org.abstracthorizon.proximity.maven.MavenProximityLogic.java

/**
 * This postprocessing simply merges the fetched list of metadatas.
 * /*from  w w  w. j av  a2  s  .co m*/
 * @param request the request
 * @param groupRequest the group request
 * @param listOfProxiedItems the list of proxied items
 * 
 * @return the merged metadata.
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 */
public Item postprocessItemList(ProximityRequest request, ProximityRequest groupRequest,
        List listOfProxiedItems) throws IOException {

    if (listOfProxiedItems.size() == 0) {

        throw new IllegalArgumentException("The listOfProxiedItems list cannot be 0 length!");
    }

    Item item = (Item) listOfProxiedItems.get(0);
    ItemProperties itemProps = item.getProperties();

    if (listOfProxiedItems.size() > 1) {

        if (MavenArtifactRecognizer.isChecksum(request.getPath())) {

            File tmpFile = new File(System.getProperty("java.io.tmpdir"),
                    request.getPath().replace(ItemProperties.PATH_SEPARATOR.charAt(0), '_'));
            if (tmpFile.exists()) {
                logger.info("Item for path " + request.getPath() + " SPOOFED with merged metadata checksum.");
                item.setStream(new DeleteOnCloseFileInputStream(tmpFile));
                itemProps.setSize(tmpFile.length());
            } else {
                logger.debug("Item for path " + request.getPath() + " SPOOFED with first got from repo group.");
            }

        } else {
            logger.debug("Item for path " + request.getPath() + " found in total of "
                    + listOfProxiedItems.size() + " repositories, will merge them.");

            MetadataXpp3Reader metadataReader = new MetadataXpp3Reader();
            MetadataXpp3Writer metadataWriter = new MetadataXpp3Writer();
            InputStreamReader isr;

            Metadata mergedMetadata = null;

            for (int i = 0; i < listOfProxiedItems.size(); i++) {

                Item currentItem = (Item) listOfProxiedItems.get(i);
                try {
                    isr = new InputStreamReader(currentItem.getStream());
                    Metadata imd = metadataReader.read(isr);
                    if (mergedMetadata == null) {
                        mergedMetadata = imd;
                    } else {
                        mergedMetadata.merge(imd);
                    }
                    isr.close();
                } catch (XmlPullParserException ex) {
                    logger.warn("Could not merge M2 metadata: " + currentItem.getProperties().getDirectoryPath()
                            + " from repository " + currentItem.getProperties().getRepositoryId(), ex);
                } catch (IOException ex) {
                    logger.warn("Got IOException during merge of M2 metadata: "
                            + currentItem.getProperties().getDirectoryPath() + " from repository "
                            + currentItem.getProperties().getRepositoryId(), ex);
                }

            }

            try {
                // we know that maven-metadata.xml is relatively small
                // (few
                // KB)
                MessageDigest md5alg = MessageDigest.getInstance("md5");
                MessageDigest sha1alg = MessageDigest.getInstance("sha1");
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                DigestOutputStream md5os = new DigestOutputStream(bos, md5alg);
                DigestOutputStream sha1os = new DigestOutputStream(md5os, sha1alg);
                OutputStreamWriter osw = new OutputStreamWriter(sha1os);
                metadataWriter.write(osw, mergedMetadata);
                osw.flush();
                osw.close();

                storeDigest(request, md5alg);
                storeDigest(request, sha1alg);

                ByteArrayInputStream is = new ByteArrayInputStream(bos.toByteArray());
                item.setStream(is);
                itemProps.setSize(bos.size());
            } catch (NoSuchAlgorithmException ex) {
                throw new IllegalArgumentException("No MD5 or SHA1 algorithm?");
            }
        }

    }

    return item;
}