Example usage for java.io DataOutputStream DataOutputStream

List of usage examples for java.io DataOutputStream DataOutputStream

Introduction

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

Prototype

public DataOutputStream(OutputStream out) 

Source Link

Document

Creates a new data output stream to write data to the specified underlying output stream.

Usage

From source file:com.igormaznitsa.jhexed.renders.svg.SVGImage.java

public void write(final OutputStream out, final boolean zipped) throws IOException {
    final DataOutputStream dout = out instanceof DataOutputStream ? (DataOutputStream) out
            : new DataOutputStream(out);
    if (zipped) {
        final byte[] packedImage = Utils.packByteArray(this.originalNonParsedImageData);

        dout.writeInt(packedImage.length);
        dout.write(packedImage);/*from   ww  w.  ja  va 2 s  .co m*/
    } else {
        dout.write(this.originalNonParsedImageData);
    }
    dout.writeBoolean(this.quality);
}

From source file:com.fullhousedev.globalchat.bukkit.PluginMessageManager.java

public static void userConnect(String username, String server, Plugin pl) {
    try {/*from w w  w  . jav  a2s.c o m*/
        ByteArrayOutputStream customData = new ByteArrayOutputStream();
        DataOutputStream outCustom = new DataOutputStream(customData);
        outCustom.writeUTF(username);
        outCustom.writeUTF(server);

        sendRawMessage("userconnect", "ALL", customData.toByteArray(), pl);
    } catch (IOException ex) {
        Logger.getLogger(GlobalChat.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:fr.isen.browser5.Util.UrlLoader.java

private void load(String url, Object... args) {
    String method = null, action = null;
    HashMap<String, String> params = null;
    if (args.length == 3) {
        method = (String) args[0];
        action = (String) args[1];
        params = (HashMap<String, String>) args[2];
    }/*from w w  w  .  j  av a 2 s  .c o m*/
    try {
        url = Str.checkProtocol(url);
        String urlParameters = "";
        if (method != null) {
            url = Str.removeLastSlash(url);
            if (action.startsWith("/")) {
                action = action.substring(1);
            }
            if (action.startsWith("http://") || action.startsWith("https://")) {
                url = action;
            } else {
                url += "/" + action;
            }

            int i = 0;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                urlParameters += entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), "UTF-8");
                if (!(i++ == params.size() - 1)) {
                    urlParameters += "&";
                }
            }

            if (method.equals("GET")) {
                url += "?" + urlParameters;
            }
        } else {
            method = "GET";
        }

        System.out.println();
        System.out.println("Loading url: " + url);

        URL obj = new URL(url);
        connection = (HttpURLConnection) obj.openConnection();
        connection.setReadTimeout(10000);
        connection.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
        connection.addRequestProperty("User-Agent", "Lynx/2.8.8dev.3 libwww-FM/2.14 SSL-MM/1.4.1");
        connection.setRequestMethod(method);

        if (method.equals("POST")) {
            byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8"));
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", "" + Integer.toString(postData.length));
            connection.setRequestProperty("Content-Language", "en-US");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
                wr.write(postData);
            }
        }

        if (handleRedirects())
            return;

        handleConnectionResponse();
    } catch (IOException ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, ex.getMessage(), ex.getClass().getSimpleName(),
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:org.openxdata.server.FormsServer.java

/**
 * Called when a new connection has been received. Failures are not handled
 * in this class as different servers (BT,SMS, etc) may want to handle them
 * differently.//from   w  w w .j a va 2s. co m
 * 
 * @param dis - the stream to read from.
 * @param dos - the stream to write to.
 */
public void processConnection(InputStream disParam, OutputStream dosParam) {

    ZOutputStream gzip = new ZOutputStream(dosParam, JZlib.Z_BEST_COMPRESSION);
    DataOutputStream zdos = new DataOutputStream(gzip);

    byte responseStatus = ResponseStatus.STATUS_ERROR;

    try {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataInputStream dis = new DataInputStream(disParam);

            String name = dis.readUTF();
            String password = dis.readUTF();
            String serializer = dis.readUTF();
            String locale = dis.readUTF();

            byte action = dis.readByte();

            User user = authenticationService.authenticate(name, password);
            if (user == null)
                responseStatus = ResponseStatus.STATUS_ACCESS_DENIED;
            else {
                DataOutputStream dosTemp = new DataOutputStream(baos);

                if (action == ACTION_DOWNLOAD_FORMS)
                    formDownloadService.downloadForms(dosTemp, serializer, locale);
                else if (action == ACTION_UPLOAD_DATA)
                    submitXforms(dis, dosTemp, serializer);
                else if (action == ACTION_DOWNLOAD_USERS)
                    formDownloadService.downloadUsers(dosTemp, serializer);
                else if (action == ACTION_DOWNLOAD_USERS_AND_FORMS)
                    downloadUsersAndForms(dis.readInt(), dosTemp, serializer, locale);
                else if (action == ACTION_DOWNLOAD_STUDY_LIST)
                    formDownloadService.downloadStudies(dosTemp, serializer, locale);
                else if (action == ACTION_DOWNLOAD_LANGUAGES)
                    formDownloadService.downloadLocales(dis, dosTemp, serializer);
                else if (action == ACTION_DOWNLOAD_MENU_TEXT)
                    formDownloadService.downloadMenuText(dis, dosTemp, serializer, locale);
                else if (action == ACTION_DOWNLOAD_STUDY_FORMS)
                    formDownloadService.downloadForms(dis.readInt(), zdos, serializer, locale);
                else if (action == ACTION_DOWNLOAD_USERS_AND_ALL_FORMS)
                    downloadUsersAndAllForms(dosTemp, serializer, locale);

                responseStatus = ResponseStatus.STATUS_SUCCESS;
            }

            zdos.writeByte(responseStatus);

            if (responseStatus == ResponseStatus.STATUS_SUCCESS) {
                zdos.write(baos.toByteArray());
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            zdos.writeByte(responseStatus);
        } finally {
            zdos.flush();
            gzip.finish();
        }
    } catch (IOException e) {
        // this is for exceptions occurring in the catch or finally clauses.
        log.error(e.getMessage(), e);
    }
}

From source file:com.stefanbrenner.droplet.service.impl.ArduinoService.java

@Override
public synchronized boolean connect(final CommPortIdentifier portId, final IDropletContext context) {
    try {//from w  w  w  .  j  a v a 2 s . c  om
        ArduinoService.dropletContext = context;

        ArduinoService.LOGGER.debug("Connect to port: " + portId.getName());

        // try to open a connection to the serial port
        ArduinoService.connSerialPort = (SerialPort) portId.open(this.getClass().getName(),
                ArduinoService.TIME_OUT);

        // set port parameters
        ArduinoService.connSerialPort.setSerialPortParams(ArduinoService.DATA_RATE, SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

        // open the streams
        ArduinoService.input = new DataInputStream(ArduinoService.connSerialPort.getInputStream());
        ArduinoService.output = new DataOutputStream(ArduinoService.connSerialPort.getOutputStream());

        // add event listeners
        ArduinoService.connSerialPort.addEventListener(this);
        ArduinoService.connSerialPort.notifyOnDataAvailable(true);
        ArduinoService.connSerialPort.notifyOnCarrierDetect(true);

        // set connected flag
        setConnected(true);

        ArduinoService.LOGGER.info("Connection to port " + portId.getName() + " successful established");

        return true;

    } catch (PortInUseException e) {
        ArduinoService.LOGGER.error("Error connecting to port {}", portId.getName(), e);
    } catch (UnsupportedCommOperationException e) {
        ArduinoService.LOGGER.error("Error connecting to port {}", portId.getName(), e);
    } catch (IOException e) {
        ArduinoService.LOGGER.error("Error connecting to port {}", portId.getName(), e);
    } catch (TooManyListenersException e) {
        ArduinoService.LOGGER.error("Error connecting to port {}", portId.getName(), e);
    }

    setConnected(false);
    return false;
}

From source file:com.chinamobile.bcbsp.comm.DiskManager.java

/**
 * Save messages of every partition on disk.
 * @param msgList/*from   ww w. ja  va2  s . c om*/
 * @param superStep
 * @param srcPartitionDstBucket
 * @throws IOException e
 */
public void processMessagesSave(ArrayList<IMessage> msgList, int superStep, int srcPartitionDstBucket)
        throws IOException {
    int count = msgList.size();
    int bucket = PartitionRule.getBucket(srcPartitionDstBucket);
    int srcPartition = PartitionRule.getPartition(srcPartitionDstBucket);
    String fileName = "srcPartition-" + srcPartition + "_" + "counter" + "-" + counter[srcPartitionDstBucket]++
            + "_" + "count" + "-" + count;
    String tmpPath = DiskManager.workerDir + "/" + "superstep-" + superStep + "/" + "bucket-" + bucket;
    File tmpFile = new File(tmpPath);
    if (!tmpFile.exists()) {
        tmpFile.mkdirs();
    }
    String url = new File(tmpFile, fileName).toString();
    // SpillingDiskOutputBuffer writeBuffer = new SpillingDiskOutputBuffer(url);
    FileOutputStream fot = new FileOutputStream(new File(url));
    BufferedOutputStream bos = new BufferedOutputStream(fot, MetaDataOfMessage.MESSAGE_IO_BYYES);
    DataOutputStream dos = new DataOutputStream(bos);
    for (int i = 0; i < count; i++) {
        msgList.remove(0).write(dos);
    }
    dos.close();
}

From source file:com.letsgood.synergykitsdkandroid.requestmethods.Patch.java

@Override
public BufferedReader execute() {
    String jSon = null;/*from   www  .j  a v  a2 s.c om*/
    String uri = null;

    //init check
    if (!Synergykit.isInit()) {
        SynergykitLog.print(Errors.MSG_SK_NOT_INITIALIZED);

        statusCode = Errors.SC_SK_NOT_INITIALIZED;
        return null;
    }

    //URI check
    uri = getUri().toString();

    if (uri == null) {
        statusCode = Errors.SC_URI_NOT_VALID;
        return null;
    }

    //session token check
    if (sessionTokenRequired && sessionToken == null) {
        statusCode = Errors.SC_NO_SESSION_TOKEN;
        return null;
    }

    try {
        url = new URL(uri); // init url

        httpURLConnection = (HttpURLConnection) url.openConnection(); //open connection
        httpURLConnection.setConnectTimeout(CONNECT_TIMEOUT); //set connect timeout
        httpURLConnection.setReadTimeout(READ_TIMEOUT); //set read timeout
        httpURLConnection.setRequestMethod(REQUEST_METHOD); //set method
        httpURLConnection.addRequestProperty(PROPERTY_USER_AGENT, PROPERTY_USER_AGENT_VALUE); //set property accept
        httpURLConnection.addRequestProperty(PROPERTY_ACCEPT, ACCEPT_APPLICATION_VALUE); //set property accept
        httpURLConnection.addRequestProperty(PROPERTY_CONTENT_TYPE, ACCEPT_APPLICATION_VALUE);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);

        httpURLConnection.addRequestProperty(PROPERTY_AUTHORIZATION,
                "Basic " + Base64.encodeToString(
                        (Synergykit.getTenant() + ":" + Synergykit.getApplicationKey()).getBytes(),
                        Base64.NO_WRAP)); //set authorization

        if (Synergykit.getSessionToken() != null)
            httpURLConnection.addRequestProperty(PROPERTY_SESSION_TOKEN, Synergykit.getSessionToken());

        httpURLConnection.connect();

        //write data
        if (object != null) {
            jSon = GsonWrapper.getGson().toJson(object);
            dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            dataOutputStream.write(jSon.getBytes(CHARSET));
            dataOutputStream.flush();
            dataOutputStream.close();

        }

        statusCode = httpURLConnection.getResponseCode(); //get status code

        //read stream
        if (statusCode >= HttpURLConnection.HTTP_OK && statusCode < HttpURLConnection.HTTP_MULT_CHOICE) {
            return readStream(httpURLConnection.getInputStream());
        } else {
            return readStream(httpURLConnection.getErrorStream());
        }

    } catch (Exception e) {
        statusCode = HttpStatus.SC_SERVICE_UNAVAILABLE;
        e.printStackTrace();
        return null;
    }

}

From source file:com.connectsdk.device.netcast.NetcastHttpServer.java

public void start() {
    if (running)/*from   ww w  .  j a v a  2s. c  o  m*/
        return;

    running = true;

    try {
        welcomeSocket = new ServerSocket(this.port);
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    while (running) {
        if (welcomeSocket == null || welcomeSocket.isClosed()) {
            stop();
            break;
        }

        Socket connectionSocket = null;
        BufferedReader inFromClient = null;
        DataOutputStream outToClient = null;

        try {
            connectionSocket = welcomeSocket.accept();
        } catch (IOException ex) {
            ex.printStackTrace();
            // this socket may have been closed, so we'll stop
            stop();
            return;
        }

        String str = null;
        int c;
        StringBuilder sb = new StringBuilder();

        try {
            inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

            while ((str = inFromClient.readLine()) != null) {
                if (str.equals("")) {
                    break;
                }
            }

            while ((c = inFromClient.read()) != -1) {
                sb.append((char) c);
                String temp = sb.toString();

                if (temp.endsWith("</envelope>"))
                    break;
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        String body = sb.toString();

        Log.d("Connect SDK", "got message body: " + body);

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = dateFormat.format(calendar.getTime());
        String androidOSVersion = android.os.Build.VERSION.RELEASE;

        PrintWriter out = null;

        try {
            outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            out = new PrintWriter(outToClient);
            out.println("HTTP/1.1 200 OK");
            out.println("Server: Android/" + androidOSVersion + " UDAP/2.0 ConnectSDK/1.2.1");
            out.println("Cache-Control: no-store, no-cache, must-revalidate");
            out.println("Date: " + date);
            out.println("Connection: Close");
            out.println("Content-Length: 0");
            out.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                inFromClient.close();
                out.close();
                outToClient.close();
                connectionSocket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        InputStream stream = null;

        try {
            stream = new ByteArrayInputStream(body.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }

        NetcastPOSTRequestParser handler = new NetcastPOSTRequestParser();

        SAXParser saxParser;
        try {
            saxParser = saxParserFactory.newSAXParser();
            saxParser.parse(stream, handler);
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }

        if (body.contains("ChannelChanged")) {
            ChannelInfo channel = NetcastChannelParser.parseRawChannelData(handler.getJSONObject());

            Log.d("Connect SDK", "Channel Changed: " + channel.getNumber());

            for (URLServiceSubscription<?> sub : subscriptions) {
                if (sub.getTarget().equalsIgnoreCase("ChannelChanged")) {
                    for (int i = 0; i < sub.getListeners().size(); i++) {
                        @SuppressWarnings("unchecked")
                        ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners()
                                .get(i);
                        Util.postSuccess(listener, channel);
                    }
                }
            }
        } else if (body.contains("KeyboardVisible")) {
            boolean focused = false;

            TextInputStatusInfo keyboard = new TextInputStatusInfo();
            keyboard.setRawData(handler.getJSONObject());

            try {
                JSONObject currentWidget = (JSONObject) handler.getJSONObject().get("currentWidget");
                focused = (Boolean) currentWidget.get("focus");
                keyboard.setFocused(focused);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            Log.d("Connect SDK", "KeyboardFocused?: " + focused);

            for (URLServiceSubscription<?> sub : subscriptions) {
                if (sub.getTarget().equalsIgnoreCase("KeyboardVisible")) {
                    for (int i = 0; i < sub.getListeners().size(); i++) {
                        @SuppressWarnings("unchecked")
                        ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners()
                                .get(i);
                        Util.postSuccess(listener, keyboard);
                    }
                }
            }
        } else if (body.contains("TextEdited")) {
            System.out.println("TextEdited");

            String newValue = "";

            try {
                newValue = handler.getJSONObject().getString("value");
            } catch (JSONException ex) {
                ex.printStackTrace();
            }

            Util.postSuccess(textChangedListener, newValue);
        } else if (body.contains("3DMode")) {
            try {
                String enabled = (String) handler.getJSONObject().get("value");
                boolean bEnabled;

                if (enabled.equalsIgnoreCase("true"))
                    bEnabled = true;
                else
                    bEnabled = false;

                for (URLServiceSubscription<?> sub : subscriptions) {
                    if (sub.getTarget().equalsIgnoreCase("3DMode")) {
                        for (int i = 0; i < sub.getListeners().size(); i++) {
                            @SuppressWarnings("unchecked")
                            ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners()
                                    .get(i);
                            Util.postSuccess(listener, bEnabled);
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:TimestreamsTests.java

/**
 * Performs HTTP post for a given URL/*  w w  w.  jav  a  2  s.  c o  m*/
 * 
 * @param url
 *            is the URL to get
 * @param params
 *            is a URL encoded string in the form x=y&a=b...
 * @return a String with the contents of the get
 */
private Map<String, List<String>> doPost(URL url, String params) {
    HttpURLConnection connection;
    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length));

        connection.setDoInput(true);
        connection.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(params);
        wr.flush();
        wr.close();
        Map<String, List<String>> responseHeaderFields = connection.getHeaderFields();
        System.out.println(responseHeaderFields);
        if (responseHeaderFields.get(null).get(0).equals("HTTP/1.1 200 OK")) {
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            System.out.println(response);
        }
        return responseHeaderFields;
    } catch (IOException e1) {
        fail("Post " + url + " failed: " + e1.getLocalizedMessage());
    }

    return null;
}