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:net.terryyiu.emailservice.providers.AbstractEmailServiceProvider.java

@Override
public boolean send(Email email) throws IOException {
    HttpURLConnection connection = createConnection();

    // Create a Map from an email object, which can be translated to JSON which
    // the specific email service provider understands.
    Map<String, Object> map = getRequestPostData(email);

    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(map);

    DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
    dos.writeBytes(json);/*  ww w. j  av  a2s. com*/
    dos.flush();
    dos.close();

    int responseCode = connection.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + getServiceUrl());
    System.out.println("JSON: " + json);
    System.out.println("Response Code : " + responseCode);

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

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

    connection.disconnect();
    return false;
}

From source file:com.cbagroup.sit.Transact.java

public String sendPOST() throws IOException, NoSuchAlgorithmException {

    String key = "api_key=cbatest123";
    //String url = "http://developer.cbagroup.com/api/CreditTransfer?api_key=cbatest123";
    String url = "http://developer.cbagroup.com/api/Transact?" + key;
    URL object = new URL(url);
    HttpURLConnection con = (HttpURLConnection) object.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    //con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept", "application/json");

    String urlParameters = "Country=Kenya&" + "TranType=Transact&" + "Reference=COMBAPI&" + "Currency=kes&"
            + "Account=1.2.2013&" + "Amount=10.25&" + "Narration=pay&" + "TransactionDate=1.2.2013&";

    // Send post request
    con.setDoOutput(true);/*from   w ww .j a  v a2s  .  co  m*/
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

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

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

    in.close();

    //print result
    System.out.println(response.toString());

    ////////// start  ////////////////////
    String result = response.toString();

    JSONParser parser = new JSONParser();

    try {

        Object obj = parser.parse(result);

        JSONObject jsonObject = (JSONObject) obj;
        //System.out.println(jsonObject);

        long ResCode = (long) jsonObject.get("Response Code");
        System.out.println();
        System.out.println("Response Code : " + ResCode);
        System.out.println();

        if (ResCode == 1) {

            System.out.println("#########################################################");
            System.out.println("Fred hack Fail");
            System.out.println();

            long ResCode1 = (long) jsonObject.get("Response Code");
            System.out.println();
            System.out.println("Response Code : " + ResCode1);
            System.out.println();

            String Ref = (String) jsonObject.get("Reference");
            System.out.println();
            System.out.println("Reference : " + Ref);
            System.out.println();

            String Des = (String) jsonObject.get("Description");
            System.out.println();
            System.out.println("Description : " + Des);
            System.out.println();

        } else {

            System.out.println("#########################################################");
            System.out.println("Fred hack Success");
            System.out.println();

            long ResCode1 = (long) jsonObject.get("Response Code");
            System.out.println();
            System.out.println("Response Code : " + ResCode1);
            System.out.println();

            String Ref = (String) jsonObject.get("Reference");
            System.out.println();
            System.out.println("Reference : " + Ref);
            System.out.println();

            String Des = (String) jsonObject.get("Description");
            System.out.println();
            System.out.println("Description : " + Des);
            System.out.println();

        }

        //            long age = (Long) jsonObject.get("Description");
        //            System.out.println(age);

        // loop array
        //            JSONArray msg = (JSONArray) jsonObject.get("messages");
        //            Iterator<String> iterator = msg.iterator();
        //            while (iterator.hasNext()) {
        //                System.out.println(iterator.next());
        //}

    } catch (ParseException e) {
        e.printStackTrace();
    }

    return response.toString();
}

From source file:Main.java

public static void RunAsRoot(String string) throws IOException {
    Process P = Runtime.getRuntime().exec("su");
    DataOutputStream os = new DataOutputStream(P.getOutputStream());
    os.writeBytes(string + "\n");
    os.writeBytes("exit\n");
    os.flush();//ww w  .  j av a2s .co  m
}

From source file:com.amalto.workbench.models.TreeObjectTransfer.java

public void javaToNative(Object object, TransferData transferData) {
    if (!checkType(object) || !isSupportedType(transferData)) {
        DND.error(DND.ERROR_INVALID_DATA);
    }//from  ww w  . j  av  a 2  s . co m

    treeObjs = (TreeObject[]) object;
    ByteArrayOutputStream byteS = new ByteArrayOutputStream();
    DataOutputStream writeOut = new DataOutputStream(byteS);

    try {
        for (TreeObject treeData : treeObjs) {
            writeOut.writeInt(treeData.getType());
        }
        byte[] buffer = byteS.toByteArray();
        super.javaToNative(buffer, transferData);
        writeOut.close();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }

}

From source file:backtype.storm.multilang.JsonSerializer.java

public void initialize(OutputStream processIn, InputStream processOut) {
    this.processIn = new DataOutputStream(processIn);
    this.processOut = new BufferedReader(new InputStreamReader(processOut));
}

From source file:epn.edu.ec.bibliotecadigital.cliente.Client.java

@Override
public void run() {
    try {//from  w  w  w.j  a v a 2  s .  c om
        clientSocketBalancer = new Socket(InetAddress.getByName(serverIP), portBalancer);
        DataInputStream dataInBalancer = new DataInputStream(clientSocketBalancer.getInputStream());
        DataOutputStream dataOut = new DataOutputStream(clientSocketBalancer.getOutputStream());
        dataOut.writeUTF((String) params[0]);//nombre de usuario
        String ipServer = dataInBalancer.readUTF();
        int portServer = dataInBalancer.readInt();
        clientSocketBalancer.close();
        Socket clientSocket = new Socket(ipServer, portServer);
        dataOut = new DataOutputStream(clientSocket.getOutputStream());
        dataOut.writeUTF(accion);
        dataOut.writeUTF((String) params[0]);//nombre de usuario
        InputStream in;
        DataInputStream dataIn;
        switch (accion) {
        case "bajar":

            dataOut = new DataOutputStream(clientSocket.getOutputStream());
            dataOut.writeUTF((String) params[1]);
            dataIn = new DataInputStream(clientSocket.getInputStream());
            boolean encontrado = dataIn.readBoolean();
            if (!encontrado) {
                System.out.println("Libro con el cdigo: " + params[1] + " no encontrado");
                break;
            }
            String fileName = dataIn.readUTF();
            System.out.println(
                    "Descargando libro " + fileName + " con cdigo " + params[1] + " en la carpeta Donwloads");
            String home = System.getProperty("user.home");

            in = clientSocket.getInputStream();
            try {
                FileOutputStream out = new FileOutputStream(new File(home + "\\Downloads\\" + fileName));
                byte[] bytes = new byte[64 * 1024];

                int count;
                while ((count = in.read(bytes)) > 0) {
                    out.write(bytes, 0, count);
                }
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(in);
            }
            break;
        case "subir":
            dataOut = new DataOutputStream(clientSocket.getOutputStream());
            dataOut.writeUTF(((File) params[1]).getName());
            OutputStream out = clientSocket.getOutputStream();
            try {
                byte[] bytes = new byte[64 * 1024];
                in = new FileInputStream((File) params[1]);

                int count;
                while ((count = in.read(bytes)) > 0) {
                    out.write(bytes, 0, count);
                }
                in.close();
            } finally {
                IOUtils.closeQuietly(out);
            }
            break;
        case "obtenerLista":
            ObjectInputStream inFromClient = new ObjectInputStream(clientSocket.getInputStream());
            System.out.println("Libros disponibles: \n");
            List<Libro> libros = (List<Libro>) inFromClient.readObject();
            System.out.println("\tCdigo\tNommbre\n");
            for (Libro lbr : libros) {
                System.out.println("\t" + lbr.getCodigolibro() + "\t" + lbr.getNombre());
            }
            inFromClient.close();
            break;
        case "verificar":

            break;
        }
        dataOut.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:javaphpmysql.JavaPHPMySQL.java

public static void sendPost() {
    //Creamos un objeto JSON
    JSONObject jsonObj = new JSONObject();
    //Aadimos el nombre, apellidos y email del usuario
    jsonObj.put("nombre", nombre);
    jsonObj.put("apellidos", apellidos);
    jsonObj.put("email", email);
    //Creamos una lista para almacenar el JSON
    List l = new LinkedList();
    l.addAll(Arrays.asList(jsonObj));
    //Generamos el String JSON
    String jsonString = JSONValue.toJSONString(l);
    System.out.println("JSON GENERADO:");
    System.out.println(jsonString);
    System.out.println("");

    try {//from  www  .  java  2 s . c o m
        //Codificar el json a URL
        jsonString = URLEncoder.encode(jsonString, "UTF-8");
        //Generar la URL
        String url = SERVER_PATH + "listenPost.php";
        //Creamos un nuevo objeto URL con la url donde queremos enviar el JSON
        URL obj = new URL(url);
        //Creamos un objeto de conexin
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        //Aadimos la cabecera
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        //Creamos los parametros para enviar
        String urlParameters = "json=" + jsonString;
        // Enviamos los datos por POST
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
        //Capturamos la respuesta del servidor
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

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

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        //Mostramos la respuesta del servidor por consola
        System.out.println(response);
        //cerramos la conexin
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

public static void syncUsers(Plugin pl, String serverName) {
    try {//  ww w  .  ja v a 2  s. c om
        ByteArrayOutputStream customData = new ByteArrayOutputStream();
        DataOutputStream outCustom = new DataOutputStream(customData);
        outCustom.writeUTF(serverName);
        sendRawMessage("UserSync", "ALL", customData.toByteArray(), pl);
    } catch (IOException ex) {
        Logger.getLogger(GlobalChat.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.eclipse.swt.examples.clipboard.MyTypeTransfer.java

@Override
public void javaToNative(Object object, TransferData transferData) {
    if (!checkMyType(object) || !isSupportedType(transferData)) {
        DND.error(DND.ERROR_INVALID_DATA);
    }//from  ww w. j  ava  2  s. c  o m
    MyType[] myTypes = (MyType[]) object;
    try {
        // write data to a byte array and then ask super to convert to pMedium
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try (DataOutputStream writeOut = new DataOutputStream(out)) {
            for (MyType myType : myTypes) {
                byte[] buffer = myType.firstName.getBytes();
                writeOut.writeInt(buffer.length);
                writeOut.write(buffer);
                buffer = myType.firstName.getBytes();
                writeOut.writeInt(buffer.length);
                writeOut.write(buffer);
            }
            byte[] buffer = out.toByteArray();
            super.javaToNative(buffer, transferData);
        }
    } catch (IOException e) {
    }
}

From source file:bankingclient.DKFrame.java

public DKFrame(MainFrame vmain) {
    initComponents();//w w w . j  a v  a2  s .  c  om
    this.main = vmain;
    this.jTextField1.setText("");
    this.jTextField2.setText("");
    this.jTextField3.setText("");
    this.jTextField4.setText("");
    this.jTextField5.setText("");
    this.setVisible(false);
    jButton1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (jTextField2.getText().equals(jTextField3.getText())
                    && NumberUtils.isNumber(jTextField4.getText())
                    && NumberUtils.isNumber(jTextField5.getText())) {
                try {
                    Socket client = new Socket("113.22.46.207", 6013);
                    String cusName = jTextField1.getText();
                    String pass = jTextField2.getText();
                    String sdt = jTextField4.getText();
                    String cmt = jTextField5.getText();
                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(1);
                    dout.writeUTF(cusName + "\n" + pass + "\n" + sdt + "\n" + cmt);
                    dout.flush();
                    DataInputStream din = new DataInputStream(client.getInputStream());
                    byte check = din.readByte();
                    if (check == 1) {
                        JOptionPane.showMessageDialog(rootPane, "da dang ki tai khoan thanh cong");
                    } else {
                        JOptionPane.showMessageDialog(rootPane, "dang ki tai khoan khong thanh cong");

                    }
                    client.close();
                } catch (Exception ee) {
                    ee.printStackTrace();
                }
                main.setVisible(true);
                DKFrame.this.setVisible(false);

            } else {
                JOptionPane.showMessageDialog(rootPane, "Nhap thong tin sai, moi nhap lai");
            }
        }
    });
    jButton2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            main.setVisible(true);
            DKFrame.this.setVisible(false);
        }
    });
}