Example usage for java.io DataOutputStream flush

List of usage examples for java.io DataOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this data output stream.

Usage

From source file:me.cybermaxke.merchants.v16r3.SMerchant.java

protected void sendUpdate() {
    if (this.customers.isEmpty()) {
        return;//from   ww w .j a  v a2  s  .  c o  m
    }

    ByteArrayOutputStream baos0 = new ByteArrayOutputStream();
    DataOutputStream dos0 = new DataOutputStream(baos0);

    // Write the recipe list
    this.offers.a(dos0);

    try {
        dos0.flush();
        dos0.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Get the bytes
    byte[] data = baos0.toByteArray();

    // Send a packet to all the players
    Iterator<Player> it = this.customers.iterator();
    while (it.hasNext()) {
        EntityPlayer player0 = ((CraftPlayer) it.next()).getHandle();

        // Every player has a different window id
        ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
        DataOutputStream dos1 = new DataOutputStream(baos1);

        try {
            dos1.writeInt(player0.activeContainer.windowId);
            dos1.write(data);
            dos1.flush();
            dos1.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        player0.playerConnection.sendPacket(new Packet250CustomPayload("MC|TrList", baos1.toByteArray()));
    }
}

From source file:ro.bmocanu.trafficproxy.peers.PacketSenderImpl.java

/**
 * {@inheritDoc}/*  w w w.  j a  v a  2 s  .c o m*/
 */
@Override
protected void internalRun() {
    DataOutputStream targetOutputStream = peerChannel.getOutputStream();

    Packet packet = packetQueue.poll();
    if (packet != null) {
        try {
            targetOutputStream.writeInt(packet.getConnectorId());
            targetOutputStream.writeInt(packet.getWorkerId());
            targetOutputStream.writeInt(packet.getCommand().getCode());
            targetOutputStream.writeInt(packet.getContentLength());
            targetOutputStream.write(packet.getContent());
            targetOutputStream.flush();
        } catch (IOException exception) {
            LOG.error("Missed one packet; command=" + packet.getCommand().name() + ", connectorId="
                    + packet.getConnectorId(), exception);
        }
    }
}

From source file:prince.app.ccm.tools.Task.java

private void sendPost(String url, String postParams) throws Exception {

    URL obj = new URL(url);
    conn = (HttpURLConnection) obj.openConnection();

    // Acts like a browser
    conn.setUseCaches(false);/*  ww w  .j  a v  a 2 s  .co m*/
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Host", "www.iglesiamallorca.com");
    conn.setRequestProperty("User-Agent", USER_AGENT);
    conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    conn.setRequestProperty("Accept-Language", "en-US,en;q=0.8,es;q=0.6,ca;q=0.4");

    if (cookies != null) {
        for (String cookie : this.cookies) {
            conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
        }
    }
    conn.setRequestProperty("Connection", "keep-alive");
    conn.setRequestProperty("Referer", log);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));

    conn.setDoOutput(true);
    conn.setDoInput(true);

    // Send post request
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(postParams);
    wr.flush();
    wr.close();

    Log.d(TAG, "sendPost: " + conn.getResponseCode());

    int responseCode = conn.getResponseCode();

    if (conn.getHeaderField("Cache-Control") == null) {
        Log.e(TAG, "An error occurred");
    } else {
        Log.e(TAG, "Everything worked out well");
    }

    Log.e(TAG, conn.getHeaderFields().toString());

    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + postParams);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    // System.out.println(response.toString());

    Log.d(TAG, "Done in sendPost");

}

From source file:com.stratuscom.harvester.codebase.ClassServer.java

private boolean processBadRequest(String[] args, DataOutputStream out) throws IOException {
    logger.log(Level.FINE, MessageNames.CLASS_SERVER_BAD_REQUEST, args);
    out.writeBytes("HTTP/1.0 400 Bad Request\r\n\r\n");
    out.flush();
    return true;/* w  w  w .j a  v  a2 s.co  m*/
}

From source file:com.db.comserv.main.utilities.HttpCaller.java

@Override
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "DM_DEFAULT_ENCODING")
public HttpResult runRequest(String type, String methodType, URL url, List<Map<String, String>> headers,
        String requestBody, String sslByPassOption, int connTimeOut, int readTimeout, HttpServletRequest req)
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException,
        UnsupportedEncodingException, IOException, UnknownHostException, URISyntaxException {

    StringBuffer response = new StringBuffer();
    HttpResult httpResult = new HttpResult();
    boolean gzip = false;
    final long startNano = System.nanoTime();
    try {//  w  w w. ja va 2 s .  c o m
        URL encodedUrl = new URL(Utility.encodeUrl(url.toString()));
        HttpURLConnection con = (HttpURLConnection) encodedUrl.openConnection();
        TrustModifier.relaxHostChecking(con, sslByPassOption);

        // connection timeout 5s
        con.setConnectTimeout(connTimeOut);

        // read timeout 10s
        con.setReadTimeout(readTimeout * getQueryCost(req));

        methodType = methodType.toUpperCase();
        con.setRequestMethod(methodType);

        sLog.debug("Performing '{}' to '{}'", methodType, ServletUtil.filterUrl(url.toString()));

        // Get headers & set request property
        for (int i = 0; i < headers.size(); i++) {
            Map<String, String> header = headers.get(i);
            con.setRequestProperty(header.get("headerKey").toString(), header.get("headerValue").toString());
            sLog.debug("Setting Header '{}' with value '{}'", header.get("headerKey").toString(),
                    ServletUtil.filterHeaderValue(header.get("headerKey").toString(),
                            header.get("headerValue").toString()));
        }

        if (con.getRequestProperty("Accept-Encoding") == null) {
            con.setRequestProperty("Accept-Encoding", "gzip");
        }

        if (requestBody != null && !requestBody.equals("")) {
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.write(Utility.toUtf8Bytes(requestBody));
            wr.flush();
            wr.close();

        }

        // push response
        BufferedReader in = null;
        String inputLine;

        List<String> contentEncoding = con.getHeaderFields().get("Content-Encoding");
        if (contentEncoding != null) {
            for (String val : contentEncoding) {
                if ("gzip".equalsIgnoreCase(val)) {
                    sLog.debug("Gzip enabled response");
                    gzip = true;
                    break;
                }
            }
        }

        sLog.debug("Response: '{} {}' with headers '{}'", con.getResponseCode(), con.getResponseMessage(),
                ServletUtil.buildHeadersForLog(con.getHeaderFields()));

        if (con.getResponseCode() != 200 && con.getResponseCode() != 201) {
            if (con.getErrorStream() != null) {
                if (gzip) {
                    in = new BufferedReader(
                            new InputStreamReader(new GZIPInputStream(con.getErrorStream()), "UTF-8"));
                } else {
                    in = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8"));
                }
            }
        } else {
            String[] urlParts = url.toString().split("\\.");
            if (urlParts.length > 1) {
                String ext = urlParts[urlParts.length - 1];
                if (ext.equalsIgnoreCase("png") || ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("jpeg")
                        || ext.equalsIgnoreCase("gif")) {
                    BufferedImage imBuff;
                    if (gzip) {
                        imBuff = ImageIO.read(new GZIPInputStream(con.getInputStream()));
                    } else {
                        BufferedInputStream bfs = new BufferedInputStream(con.getInputStream());
                        imBuff = ImageIO.read(bfs);
                    }
                    BufferedImage newImage = new BufferedImage(imBuff.getWidth(), imBuff.getHeight(),
                            BufferedImage.TYPE_3BYTE_BGR);

                    // converting image to greyScale
                    int width = imBuff.getWidth();
                    int height = imBuff.getHeight();
                    for (int i = 0; i < height; i++) {
                        for (int j = 0; j < width; j++) {
                            Color c = new Color(imBuff.getRGB(j, i));
                            int red = (int) (c.getRed() * 0.21);
                            int green = (int) (c.getGreen() * 0.72);
                            int blue = (int) (c.getBlue() * 0.07);
                            int sum = red + green + blue;
                            Color newColor = new Color(sum, sum, sum);
                            newImage.setRGB(j, i, newColor.getRGB());
                        }
                    }

                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    ImageIO.write(newImage, "jpg", out);
                    byte[] bytes = out.toByteArray();

                    byte[] encodedBytes = Base64.encodeBase64(bytes);
                    String base64Src = new String(encodedBytes);
                    int imageSize = ((base64Src.length() * 3) / 4) / 1024;
                    int initialImageSize = imageSize;
                    int maxImageSize = Integer.parseInt(properties.getValue("Reduced_Image_Size"));
                    float quality = 0.9f;
                    if (!(imageSize <= maxImageSize)) {
                        //This means that image size is greater and needs to be reduced.
                        sLog.debug("Image size is greater than " + maxImageSize + " , compressing image.");
                        while (!(imageSize < maxImageSize)) {
                            base64Src = compress(base64Src, quality);
                            imageSize = ((base64Src.length() * 3) / 4) / 1024;
                            quality = quality - 0.1f;
                            DecimalFormat df = new DecimalFormat("#.0");
                            quality = Float.parseFloat(df.format(quality));
                            if (quality <= 0.1) {
                                break;
                            }
                        }
                    }
                    sLog.debug("Initial image size was : " + initialImageSize + " Final Image size is : "
                            + imageSize + "Url is : " + url + "quality is :" + quality);
                    String src = "data:image/" + urlParts[urlParts.length - 1] + ";base64,"
                            + new String(base64Src);
                    JSONObject joResult = new JSONObject();
                    joResult.put("Image", src);
                    out.close();
                    httpResult.setResponseCode(con.getResponseCode());
                    httpResult.setResponseHeader(con.getHeaderFields());
                    httpResult.setResponseBody(joResult.toString());
                    httpResult.setResponseMsg(con.getResponseMessage());
                    return httpResult;
                }
            }

            if (gzip) {
                in = new BufferedReader(
                        new InputStreamReader(new GZIPInputStream(con.getInputStream()), "UTF-8"));
            } else {
                in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            }
        }
        if (in != null) {
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        }

        httpResult.setResponseCode(con.getResponseCode());
        httpResult.setResponseHeader(con.getHeaderFields());
        httpResult.setResponseBody(response.toString());
        httpResult.setResponseMsg(con.getResponseMessage());

    } catch (Exception e) {
        sLog.error("Failed to received HTTP response after timeout", e);

        httpResult.setTimeout(true);
        httpResult.setResponseCode(500);
        httpResult.setResponseMsg("Internal Server Error Timeout");
        return httpResult;
    }

    return httpResult;
}

From source file:com.magicmod.mmweather.engine.WeatherEngine.java

private boolean flushCache(String string) {
    DataOutputStream out = null;
    File file = null;//from  w w  w  .  ja  va 2s.c  o m
    try {
        file = new File(mCacheDir, CACHE_NAME);
        out = new DataOutputStream(new FileOutputStream(file));
        out.write(string.getBytes());
        if (out != null) {
            out.flush();
            out.close();
        }
    } catch (Exception e) {
        // TODO: handle exception
        Log.e(TAG, "Write to Cache fail");
        e.printStackTrace();

        if (file != null) {
            file.delete();
        }
        return false;
    } finally {
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (Exception e2) {
                // TODO: handle exception
                if (file != null) {
                    file.delete();
                }
            }
        }
    }
    return true;
}

From source file:io.dacopancm.socketdcm.net.StreamSocket.java

public String getStreamFile() {
    String list = "false";
    try {// w  w  w. j  a  v a  2 s. co m

        if (ConectType.GET_STREAM.name().equalsIgnoreCase(method)) {
            logger.log(Level.INFO, "get stream socket call");
            sock = new Socket(ip, port);

            DataOutputStream dOut = new DataOutputStream(sock.getOutputStream());
            DataInputStream dIn = new DataInputStream(sock.getInputStream());

            dOut.writeUTF(ConectType.STREAM.name());//send stream type
            dOut.writeUTF("uncompressed");//send comprimido o no

            dOut.writeUTF(ConectType.GET_STREAM.toString()); //send type
            dOut.writeUTF(streamid);
            dOut.flush(); // Send off the data

            String rtspId = dIn.readUTF();
            dOut.close();
            logger.log(Level.INFO, "resp get stream file: {0}", rtspId);
            list = rtspId;

        }
    } catch (IOException ex) {
        HelperUtil.showErrorB("No se pudo establecer conexin");
        logger.log(Level.INFO, "get stream file error no connect:{0}", ex.getMessage());
        try {
            if (sock != null) {
                sock.close();
            }
        } catch (IOException e) {
        }

    }
    return list;

}

From source file:com.mbrlabs.mundus.assets.EditorAssetManager.java

public void saveTerrainAssets() throws IOException {
    for (TerrainAsset terrain : getTerrainAssets()) {

        // save .terra file
        DataOutputStream outputStream = new DataOutputStream(
                new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(terrain.getFile().file()))));
        for (float f : terrain.getData()) {
            outputStream.writeFloat(f);// w w w.j a  v  a 2  s .c om
        }
        outputStream.flush();
        outputStream.close();

        // save splatmap
        PixmapTextureAsset splatmap = terrain.getSplatmap();
        if (splatmap != null) {
            PixmapIO.writePNG(splatmap.getFile(), splatmap.getPixmap());
        }

        // save meta file
        terrain.getMeta().save();
    }
}

From source file:com.wlcg.aroundme.cc.weather.WeatherEngine.java

/**
 * /*from   w  w  w.  ja  va2 s.c  om*/
 * <h1></h1>
 * 2014-3-18
 * @param string 
 * @return
 */

private synchronized boolean flushCache(String string) {
    DataOutputStream out = null;
    File file = null;
    try {
        file = new File(mCacheDir, CACHE_NAME);
        out = new DataOutputStream(new FileOutputStream(file));
        out.write(string.getBytes());
        if (out != null) {
            out.flush();
            out.close();
        }
    } catch (Exception e) {
        // TODO: handle exception
        Log.e(TAG, "Write to Cache fail");
        e.printStackTrace();

        if (file != null) {
            file.delete();
        }
        return false;
    } finally {
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (Exception e2) {
                // TODO: handle exception
                if (file != null) {
                    file.delete();
                }
            }
        }
    }
    return true;
}

From source file:io.dacopancm.socketdcm.net.StreamSocket.java

public ObservableList<StreamFile> getStreamList() {
    ObservableList<StreamFile> list = FXCollections.observableArrayList();
    try {/*from  w  w  w  .  j  av  a 2 s  .co m*/

        if (ConectType.GET_STREAMLIST.name().equalsIgnoreCase(method)) {
            logger.log(Level.INFO, "get stream list call");
            sock = new Socket(ip, port);

            DataOutputStream dOut = new DataOutputStream(sock.getOutputStream());
            DataInputStream dIn = new DataInputStream(sock.getInputStream());

            dOut.writeUTF(ConectType.STREAM.name());//send stream type
            dOut.writeUTF("uncompressed");//send comprimido o no

            dOut.writeUTF(ConectType.GET_STREAMLIST.toString()); //send type
            dOut.writeUTF("mayra");
            dOut.flush(); // Send off the data
            System.out.println("Request list send");
            String resp = dIn.readUTF();
            dOut.close();
            logger.log(Level.INFO, "resp get streamlist: {0}", resp);
            List<StreamFile> files = HelperUtil.fromJSON(resp);
            list.addAll(files);

        }
    } catch (IOException ex) {
        HelperUtil.showErrorB("No se pudo establecer conexin");
        logger.log(Level.INFO, "get streamlist error no connect:{0}", ex.getMessage());
        try {
            if (sock != null) {
                sock.close();
            }
        } catch (IOException e) {
        }

    }
    return list;
}