Example usage for java.io DataInputStream readUTF

List of usage examples for java.io DataInputStream readUTF

Introduction

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

Prototype

public final String readUTF() throws IOException 

Source Link

Document

See the general contract of the readUTF method of DataInput.

Usage

From source file:RMSGameScores.java

public boolean matches(byte[] candidate) throws IllegalArgumentException {
    // If no filter set, nothing can match it.
    if (this.playerNameFilter == null) {
        return false;
    }//w  w w. j  ava  2s. c o m

    ByteArrayInputStream bais = new ByteArrayInputStream(candidate);
    DataInputStream inputStream = new DataInputStream(bais);
    String name = null;

    try {
        int score = inputStream.readInt();
        name = inputStream.readUTF();
    } catch (EOFException eofe) {
        System.out.println(eofe);
        eofe.printStackTrace();
    } catch (IOException eofe) {
        System.out.println(eofe);
        eofe.printStackTrace();
    }
    return (this.playerNameFilter.equals(name));
}

From source file:WriteReadMixedDataTypesExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);/*from  w  w w . j  a  va 2  s  .  co  m*/
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
        } catch (Exception error) {
            alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            byte[] outputRecord;
            String outputString = "First Record";
            int outputInteger = 15;
            boolean outputBoolean = true;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            outputDataStream.writeUTF(outputString);
            outputDataStream.writeBoolean(outputBoolean);
            outputDataStream.writeInt(outputInteger);
            outputDataStream.flush();
            outputRecord = outputStream.toByteArray();
            recordstore.addRecord(outputRecord, 0, outputRecord.length);
            outputStream.reset();
            outputStream.close();
            outputDataStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            String inputString = null;
            int inputInteger = 0;
            boolean inputBoolean = false;
            byte[] byteInputData = new byte[100];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            for (int x = 1; x <= recordstore.getNumRecords(); x++) {
                recordstore.getRecord(x, byteInputData, 0);
                inputString = inputDataStream.readUTF();
                inputBoolean = inputDataStream.readBoolean();
                inputInteger = inputDataStream.readInt();
                inputStream.reset();
            }
            inputStream.close();
            inputDataStream.close();
            alert = new Alert("Reading", inputString + " " + inputInteger + " " + inputBoolean, null,
                    AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        } catch (Exception error) {
            alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            recordstore.closeRecordStore();
        } catch (Exception error) {
            alert = new Alert("Error Closing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        if (RecordStore.listRecordStores() != null) {
            try {
                RecordStore.deleteRecordStore("myRecordStore");
            } catch (Exception error) {
                alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
        }
    }
}

From source file:RMSGameScores.java

/**
 * A helper method for the printScores methods.
 *//*w  w  w .  j  a va  2  s.  c  o  m*/
private void printScoresHelper(RecordEnumeration re) {

    try {
        while (re.hasNextElement()) {
            int id = re.nextRecordId();
            ByteArrayInputStream bais = new ByteArrayInputStream(recordStore.getRecord(id));
            DataInputStream inputStream = new DataInputStream(bais);
            try {
                int score = inputStream.readInt();
                String playerName = inputStream.readUTF();
                System.out.println(playerName + " = " + score);
            } catch (EOFException eofe) {
                System.out.println(eofe);
                eofe.printStackTrace();
            }
        }
    } catch (RecordStoreException rse) {
        System.out.println(rse);
        rse.printStackTrace();
    } catch (IOException ioe) {
        System.out.println(ioe);
        ioe.printStackTrace();
    }
}

From source file:MainClass.java

public void run() {
    try {//from  www.  ja  va 2 s . co  m
        Socket socket = new Socket("127.0.0.1", 2000);

        DataInputStream in = new DataInputStream(socket.getInputStream());
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());

        while (true) {
            System.out.print("Enter response: ");
            String response = console.readLine();
            out.writeUTF(response);

            String message = in.readUTF();
            System.out.println(message);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.cassandra.db.SuperColumn.java

private SuperColumn defreezeSuperColumn(DataInputStream dis) throws IOException {
    String name = dis.readUTF();
    SuperColumn superColumn = new SuperColumn(name);
    superColumn.markForDeleteAt(dis.readInt(), dis.readLong());
    return superColumn;
}

From source file:srvserver.thServerSocket.java

@Override
public void run() {
    try {//from  w  ww. ja va 2  s.  co m
        logger.info("Starting Listener Thread Service Server port: " + gDatos.getServiceInfo().getSrvPort());
        String inputData;
        String outputData;
        String dRequest;
        String dAuth;
        JSONObject jHeader;
        JSONObject jData;

        ServerSocket skServidor = new ServerSocket(gDatos.getServiceInfo().getSrvPort());

        while (isSocketActive) {
            Socket skCliente = skServidor.accept();
            InputStream inpStr = skCliente.getInputStream();
            DataInputStream dataInput = new DataInputStream(inpStr);

            //Recibe Data Input (request)
            //
            //Espera Entrada
            //
            try {
                inputData = dataInput.readUTF();
                //gSub.sysOutln(inputData);

                logger.info("Recibiendo TX: " + inputData);
                jHeader = new JSONObject(inputData);
                jData = jHeader.getJSONObject("data");

                dAuth = jHeader.getString("auth");
                dRequest = jHeader.getString("request");

                if (dAuth.equals(gDatos.getServiceInfo().getAuthKey())) {

                    switch (dRequest) {
                    case "getStatus":
                        outputData = gSub.sendDataKeep("request");
                        break;
                    case "getDate":
                        outputData = gSub.sendDate();
                        break;
                    case "updateAssignedProc":
                        gSub.updateAssignedProcess(jData);
                        outputData = gSub.sendOkTX();
                        break;
                    case "executeProcess":
                        logger.info("Ejecutando ...enqueProcess..: " + inputData);
                        int result = gSub.enqueProcess(jData);
                        if (result == 0) {
                            outputData = gSub.sendOkTX();
                        } else {
                            if (result == 2) {
                                outputData = gSub.sendError(99, "Proceso ya se encuntra encolado...");
                            } else {
                                outputData = gSub.sendError(99, "Error encolando proceso...");
                            }
                        }
                        break;
                    case "getPoolProcess":
                        outputData = gSub.sendPoolProcess();
                        break;
                    case "getList":
                        outputData = ""; //gSub.sendList(jData);
                        break;
                    case "updateVar":
                        outputData = ""; //gSub.updateVar(jData);
                        break;
                    default:
                        outputData = gSub.sendError(99, "Error desconocido..");
                    }
                } else {
                    outputData = gSub.sendError(60);
                }
            } catch (IOException | JSONException e) {
                outputData = gSub.sendError(90);
            }

            //Envia Respuesta
            //
            OutputStream outStr = skCliente.getOutputStream();
            DataOutputStream dataOutput = new DataOutputStream(outStr);

            logger.info("Enviando respuesta: " + outputData);

            if (outputData == null) {
                dataOutput.writeUTF("{}");
            } else {
                dataOutput.writeUTF(outputData);
            }

            //Cierra Todas las conexiones
            //
            inpStr.close();
            dataInput.close();
            skCliente.close();
        }

    } catch (NumberFormatException | IOException e) {
        logger.error(e.getMessage());
    }
}

From source file:org.openxdata.server.servlet.WMDownloadServlet.java

private void downloadForms(HttpServletResponse response, int studyId) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    formDownloadService.downloadForms(studyId, dos, "", "");
    baos.flush();/* w w  w  . ja v  a2s .  c  o  m*/
    dos.flush();
    byte[] data = baos.toByteArray();
    baos.close();
    dos.close();
    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));

    PrintWriter out = response.getWriter();
    out.println("<study>");

    try {
        dis.readByte(); //reads the size of the studies

        while (true) {
            String value = dis.readUTF();
            out.println("<form>" + value + "</form>");
        }
    } catch (EOFException exe) {
        //exe.printStackTrace();
    }

    out.println("</study>");
    out.flush();
    dis.close();
}

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

@Override
public void run() {
    try {/*  w ww.j a  v  a2  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:Main.java

public InputStream getWWWPageStream(String host, String file) throws IOException, UnknownHostException {

    InetAddress webServer = InetAddress.getByName(host);

    Socket httpPipe = new Socket(webServer, 80);
    if (httpPipe == null) {
        System.out.println("Socket to Web server creation failed.");
        return null;
    }/*from  w ww  . j  a  v a2s.  c  om*/

    InputStream inn = httpPipe.getInputStream(); // get raw streams
    OutputStream outt = httpPipe.getOutputStream();

    DataInputStream in = new DataInputStream(inn); // turn into higher-level ones
    PrintStream out = new PrintStream(outt);

    if (inn == null || outt == null) {
        System.out.println("Failed to open streams to socket.");
        return null;
    }
    out.println("GET " + file + " HTTP/1.0\n");

    String response;
    while ((response = in.readUTF()).length() > 0) {
        System.out.println(response);
    }

    return in;
}

From source file:Bookmark.java

protected Object nativeToJava(TransferData transferData) {
    if (isSupportedType(transferData)) {
        byte[] raw = (byte[]) super.nativeToJava(transferData);
        if (raw == null)
            return null;
        Bookmark bookmark = new Bookmark();

        try {/*from ww  w  .  j a  v a  2s . c o m*/
            ByteArrayInputStream stream = new ByteArrayInputStream(raw);
            DataInputStream in = new DataInputStream(stream);
            bookmark.name = in.readUTF();
            bookmark.href = in.readUTF();
            bookmark.addDate = in.readUTF();
            bookmark.lastVisited = in.readUTF();
            bookmark.lastModified = in.readUTF();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        return bookmark;
    } else {
        return null;
    }
}