Example usage for java.io DataInputStream DataInputStream

List of usage examples for java.io DataInputStream DataInputStream

Introduction

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

Prototype

public DataInputStream(InputStream in) 

Source Link

Document

Creates a DataInputStream that uses the specified underlying InputStream.

Usage

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

public void handle() {
    try {/*w w  w  .  j  av  a2  s  .  com*/

        if (ConectType.GET_STREAMLIST.name().equalsIgnoreCase(method)) {
            DataOutputStream dOut = new DataOutputStream(sock.getOutputStream());
            DataInputStream dIn = new DataInputStream(sock.getInputStream());

            String files = HelperUtil.toJSON(mainApp.getStreamFilesList().toArray());

            dOut.writeUTF(files);
            dOut.flush(); // Send off the data
            dOut.close();
        } else if (ConectType.GET_STREAM.name().equalsIgnoreCase(method)) {
            DataOutputStream dOut = new DataOutputStream(sock.getOutputStream());
            DataInputStream dIn = new DataInputStream(sock.getInputStream());

            boolean player = mainApp.playStream(streamid);

            dOut.writeUTF("" + (player ? HelperUtil.VLC_SRV_PORT : player));
            dOut.flush(); // Send off the data
            dOut.close();

        }
    } catch (IOException ex) {
        HelperUtil.showErrorB("No se pudo establecer conexin");
        try {
            if (sock != null) {
                sock.close();
            }
        } catch (IOException e) {
        }
    }
}

From source file:bankingclient.DNFrame.java

public DNFrame(MainFrame vmain) {

    initComponents();/* w ww.  ja v a  2  s.c  o  m*/

    this.jTextField1.setText("");
    this.jTextField2.setText("");
    this.jTextField_cmt.setText("");
    this.jTextField_sdt.setText("");

    this.main = vmain;
    noAcc = new NewOrOldAccFrame(this);
    this.setVisible(false);
    jL_sdt.setVisible(false);
    jL_cmtnd.setVisible(false);
    jTextField_cmt.setVisible(false);
    jTextField_sdt.setVisible(false);

    jBt_dn.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            if (!jCheck_qmk.isSelected()) {
                try {
                    Socket client = new Socket("113.22.46.207", 6013);
                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(2);
                    dout.writeUTF(jTextField1.getText() + "\n" + jTextField2.getText());
                    dout.flush();
                    while (true) {
                        break;
                    }
                    DataInputStream din = new DataInputStream(client.getInputStream());
                    byte check = din.readByte();
                    if (check == 1) {
                        noAcc.setVisible(true);
                        DNFrame.this.setVisible(false);
                        noAcc.setMainCustomer(jTextField1.getText());

                    } else {
                        JOptionPane.showMessageDialog(new JFrame(),
                                "Tn ?ang Nhp Khng Tn Ti, hoac mat khau sai");
                    }

                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(rootPane, "C Li Kt Ni Mng....");
                }
            } else if ((!jTextField_cmt.getText().equals("")) && (!jTextField_sdt.getText().equals(""))
                    && (NumberUtils.isNumber(jTextField_cmt.getText()))
                    && (NumberUtils.isNumber(jTextField_sdt.getText()))) {
                try {
                    Socket client = new Socket("113.22.46.207", 6013);
                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(9);
                    dout.writeUTF(jTextField1.getText() + "\n" + jTextField_sdt.getText() + "\n"
                            + jTextField_cmt.getText());
                    dout.flush();
                    DataInputStream din = new DataInputStream(client.getInputStream());
                    byte check = din.readByte();
                    if (check == 1) {
                        noAcc.setVisible(true);
                        DNFrame.this.setVisible(false);
                        noAcc.setMainCustomer(jTextField1.getText());
                    } else {
                        JOptionPane.showMessageDialog(new JFrame(), "Khong dang nhap duoc, thong tin sai");
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else {
                JOptionPane.showMessageDialog(new JFrame(), "Can dien day du thong tin va dung mau");
            }
        }
    });
    jBt_ql.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            main.setVisible(true);
            DNFrame.this.setVisible(false);
        }
    });
    jCheck_qmk.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (jCheck_qmk.isSelected()) {
                jL_sdt.setVisible(true);
                jL_cmtnd.setVisible(true);
                jTextField_cmt.setVisible(true);
                jTextField_sdt.setVisible(true);
            } else {
                jL_sdt.setVisible(false);
                jL_cmtnd.setVisible(false);
                jTextField_cmt.setVisible(false);
                jTextField_sdt.setVisible(false);
            }
        }
    });
}

From source file:cqels_shim.SocketStream.java

/**
 * start listening on the socket and forwarding to cqels
 */// www  . j ava2  s  . c  o  m
public void run() {
    ServerSocket ssock = null;
    Socket sock = null;
    try {
        ssock = new ServerSocket(this.port);
        sock = ssock.accept();

        DataInputStream is = new DataInputStream(sock.getInputStream());

        JSONParser parser = new JSONParser();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;

        while ((line = reader.readLine()) != null && !stop) {
            try {
                Object obj = parser.parse(line);
                JSONArray array = (JSONArray) obj;

                //stream the triple
                stream(n((String) array.get(0)), n((String) array.get(1)), n((String) array.get(2)));
            } catch (ParseException pe) {
                System.err.println("Error when parsing input, incorrect JSON.");
            }

            if (sleep > 0) {
                try {
                    Thread.sleep(sleep);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:ImageTransfer.java

public Object nativeToJava(TransferData transferData) {
    if (!isSupportedType(transferData))
        return null;

    byte[] buffer = (byte[]) super.nativeToJava(transferData);
    if (buffer == null)
        return null;

    ImageData imdata;//  w w w .  j  a v a 2  s  . co m
    try {
        ByteArrayInputStream in = new ByteArrayInputStream(buffer);
        DataInputStream readIn = new DataInputStream(in);
        imdata = new ImageData(readIn);
        readIn.close();
    } catch (IOException ex) {
        return null;
    }
    return imdata;
}

From source file:com.cyc.tool.distributedrepresentations.Word2VecSpaceFromFile.java

/**
 * Create a W2V space in a DB.//from  w  w w.  java2 s.  c  o  m
 * 
 * @param w2vZipFile
 * @throws FileNotFoundException
 * @throws IOException
 */
protected final void createW2VinDB(String w2vZipFile) throws FileNotFoundException, IOException {
    try (DataInputStream data_in = new DataInputStream(
            new GZIPInputStream(new FileInputStream(new File(w2vZipFile))))) {
        getWordsAndSize(data_in);
        if (vectors.size() == words) {
            System.out.println("Word2Vec is in DB");
        } else {
            System.out.println("DB Size:" + vectors.size());

            System.out.println("Want to read Word Count: " + words);
            System.out.println("Size:" + getSize());
            for (int w = 0; w < words; w++) {
                float[] v = new float[getSize()];
                String key = getVocabString(data_in);
                System.out.println(w + ":\t" + key);

                IntStream.range(0, getSize()).forEach(i -> v[i] = getFloat(data_in));
                vectors.put(key, normVector(v));
                if (w % 100000 == 1) {
                    db.commit();
                }
            }
            db.commit();
            db.compact();
        }
    }
}

From source file:csparql_shim.SocketStream.java

/**
 * start listening on a socket and forwarding to csparql
 * stream in defined windows to allow comparison with cqels
 *//*from ww  w . j  a va 2  s.  c om*/
@Override
public void run() {
    ServerSocket ssock = null;
    Socket sock = null;
    try {
        ssock = new ServerSocket(this.port);
        sock = ssock.accept();

        DataInputStream is = new DataInputStream(sock.getInputStream());
        JSONParser parser = new JSONParser();

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;

        int windowcount = 1;

        //loop for streaming in data
        while ((line = reader.readLine()) != null && !stop) {

            try {
                Object obj = parser.parse(line);
                JSONArray array = (JSONArray) obj;

                //stream the triple
                final RdfQuadruple q = new RdfQuadruple((String) array.get(0), (String) array.get(1),
                        (String) array.get(2), System.currentTimeMillis());
                this.put(q);
                System.out.println("triple sent at: " + System.currentTimeMillis());
            } catch (ParseException pe) {
                System.err.println("Error when parsing input, incorrect JSON.");
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:epn.edu.ec.bibliotecadigital.servidor.ServerRunnable.java

@Override
public void run() {
    try {/* w  w w  .j  a v a 2s.c  o  m*/
        DataInputStream dataIn = new DataInputStream(clientSocket.getInputStream());
        DataOutputStream dataOut = new DataOutputStream(clientSocket.getOutputStream());
        OutputStream out;
        String accion = dataIn.readUTF();
        Libro lbr;
        String nombreUsuario = dataIn.readUTF();
        System.out.println("nombreUsuario" + nombreUsuario);
        switch (accion) {
        case "bajar":

            String codArchivo = dataIn.readUTF();
            dataOut = new DataOutputStream(clientSocket.getOutputStream());

            lbr = new LibroJpaController(emf).findLibro(Integer.parseInt(codArchivo));
            if (lbr == null) {
                dataOut.writeBoolean(false);
                break;
            }
            dataOut.writeBoolean(true);

            //File file = new File("C:\\Computacion Distribuida\\" + lbr.getNombre());
            dataOut.writeUTF(lbr.getNombre());
            out = clientSocket.getOutputStream();
            try {
                byte[] bytes = new byte[64 * 1024];
                InputStream in = new ByteArrayInputStream(lbr.getArchivo());

                int count;
                while ((count = in.read(bytes)) > 0) {
                    out.write(bytes, 0, count);
                }
                Usuariolibros usrLbr = new Usuariolibros();
                usrLbr.setFecha(Calendar.getInstance().getTime());
                usrLbr.setAccion('B');
                usrLbr.setCodigolibro(lbr);
                usrLbr.setNombrecuenta(new Usuario(nombreUsuario));
                new UsuariolibrosJpaController(emf).create(usrLbr);
                in.close();
            } finally {
                IOUtils.closeQuietly(out);
            }
            break;
        case "subir":
            dataIn = new DataInputStream(clientSocket.getInputStream());
            String fileName = dataIn.readUTF();
            InputStream in = clientSocket.getInputStream();
            try {
                out = new FileOutputStream("C:\\Computacion Distribuida\\" + fileName);
                byte[] bytes = new byte[64 * 1024];

                int count;
                while ((count = in.read(bytes)) > 0) {
                    out.write(bytes, 0, count);
                }
                out.close();
                lbr = new Libro();
                lbr.setNombre(fileName);
                lbr.setArchivo(
                        IOUtils.toByteArray(new FileInputStream("C:\\Computacion Distribuida\\" + fileName)));

                new LibroJpaController(emf).create(lbr);
                Usuariolibros usrLbr = new Usuariolibros();
                usrLbr.setFecha(Calendar.getInstance().getTime());
                usrLbr.setAccion('S');
                usrLbr.setCodigolibro(lbr);
                usrLbr.setNombrecuenta(new Usuario(nombreUsuario));
                new UsuariolibrosJpaController(emf).create(usrLbr);
                actualizarLibrosEnServidores(fileName);
            } finally {
                IOUtils.closeQuietly(in);
            }
            break;
        case "obtenerLista":
            ObjectOutputStream outToServer = new ObjectOutputStream(clientSocket.getOutputStream());
            outToServer.writeObject(new LibroJpaController(emf).findLibroEntities());
            outToServer.close();
            break;
        case "verificarEstado":
            dataOut.writeUTF(String.valueOf(server.isDisponible()));
            break;
        case "actualizar":
            dataIn = new DataInputStream(clientSocket.getInputStream());
            String fileNameFromServer = dataIn.readUTF();
            in = clientSocket.getInputStream();
            try {
                out = new FileOutputStream("C:\\Computacion Distribuida\\" + fileNameFromServer);
                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);
            }

        }
        dataIn.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.netflix.aegisthus.io.sstable.SSTableColumnScanner.java

public SSTableColumnScanner(InputStream is, long start, long end, Descriptor.Version version)
        throws IOException {
    this.version = version;
    this.start = start;
    this.end = end;
    this.input = new DataInputStream(is);
    if (this.start > 0) {
        LOG.info("skipping to start: {}", start);
        skipUnsafe(start);/*from ww  w  .  j a  v  a2s.  c om*/
    }
    this.pos = start;
}

From source file:com.lenovo.h2000.services.LicenseServiceImpl.java

@Override
public String upload(String filePath, Map<String, String> headers) throws Exception {
    _logger.info("calling LicenseServiceImpl.upload function");
    Map<String, String> params = new HashMap<String, String>();

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(
            HttpConfig.parseBaseUrl(headers) + "license/import" + "?" + TypeUtil.mapToString(params));// new HttpPost("http://localhost:3002/license/import");

    String responseBody = "";
    DataInputStream in = null;/*from   w w  w  .j  a  v  a2 s.  c  om*/
    try {
        _logger.info("filePath" + filePath);
        File file = new File(filePath);
        in = new DataInputStream(new FileInputStream(filePath));
        byte[] bufferOut = new byte[(int) file.length()];

        int bytes = 0;
        int i = 0;
        int len = (int) (1024 > file.length() ? file.length() : 1024);
        while ((bytes = in.read(bufferOut, i, len)) > 0) {
            if (bytes < 1024)
                break;
            else {
                len = (int) (file.length() - bytes);
                i += bytes;
            }
        }

        ByteArrayEntity requestEntity = new ByteArrayEntity(bufferOut);
        requestEntity.setContentEncoding("UTF-8");
        requestEntity.setContentType("application/octet-stream");
        httpPost.setEntity(requestEntity);
        HttpResponse response = httpClient.execute(httpPost);
        response.setHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
        HttpEntity responseEntity = response.getEntity();
        responseBody = EntityUtils.toString(responseEntity);

        if (file.isFile() && file.exists()) {
            file.delete();
        }

    } catch (ClientProtocolException e) {
        e.printStackTrace();
        _logger.error("throwing HttpClientUtil.doPost ClientProtocolException with " + e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        _logger.error("throwing HttpClientUtil.doPost IOException with " + e.getMessage());
    } finally {
        httpClient.close();
        if (in != null) {
            in.close();
        }
    }
    return responseBody;
}

From source file:com.mbrlabs.mundus.utils.TerrainIO.java

public static Terrain importTerrain(ProjectContext projectContext, Terrain terrain) {
    FloatArray floatArray = new FloatArray();

    String terraPath = FilenameUtils.concat(projectContext.path, terrain.terraPath);
    try (DataInputStream is = new DataInputStream(
            new BufferedInputStream(new GZIPInputStream(new FileInputStream(terraPath))))) {
        while (is.available() > 0) {
            floatArray.add(is.readFloat());
        }//w w  w  .j  av  a  2 s. c o  m
    } catch (EOFException e) {
        //e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //Log.debug("Terrain import. floats: " + floatArray.size);

    terrain.heightData = floatArray.toArray();
    terrain.init();
    terrain.update();

    // set default terrain base texture if none is present
    TerrainTexture terrainTexture = terrain.getTerrainTexture();
    if (terrainTexture.getTexture(SplatTexture.Channel.BASE) == null) {
        MTexture base = new MTexture();
        base.setId(-1);
        base.texture = TextureUtils.loadMipmapTexture(Gdx.files.internal("textures/terrain/chess.png"), true);
        terrainTexture.setSplatTexture(new SplatTexture(SplatTexture.Channel.BASE, base));
    }

    // load splat map if available
    SplatMap splatmap = terrainTexture.getSplatmap();
    if (splatmap != null) {
        String splatPath = FilenameUtils.concat(projectContext.path, splatmap.getPath());
        splatmap.loadPNG(Gdx.files.absolute(splatPath));
    }

    return terrain;
}