Example usage for java.io DataOutputStream writeUTF

List of usage examples for java.io DataOutputStream writeUTF

Introduction

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

Prototype

public final void writeUTF(String str) throws IOException 

Source Link

Document

Writes a string to the underlying output stream using modified UTF-8 encoding in a machine-independent manner.

Usage

From source file:ReadWriteStreams.java

public void writeStream(String[] sData, boolean[] bData, int[] iData) {
    try {//from   w  w w  .j  ava  2s  .com
        // Write data into an internal byte array
        ByteArrayOutputStream strmBytes = new ByteArrayOutputStream();

        // Write Java data types into the above byte array
        DataOutputStream strmDataType = new DataOutputStream(strmBytes);

        byte[] record;

        for (int i = 0; i < sData.length; i++) {
            // Write Java data types      
            strmDataType.writeUTF(sData[i]);
            strmDataType.writeBoolean(bData[i]);
            strmDataType.writeInt(iData[i]);

            // Clear any buffered data
            strmDataType.flush();

            // Get stream data into byte array and write record
            record = strmBytes.toByteArray();
            rs.addRecord(record, 0, record.length);

            // Toss any data in the internal array so writes 
            // starts at beginning (of the internal array)
            strmBytes.reset();
        }

        strmBytes.close();
        strmDataType.close();

    } catch (Exception e) {
        db(e.toString());
    }
}

From source file:com.towerlabs.yildizyemek.ViewPagerDinner.java

public boolean fileIsExist() throws IOException, InterruptedException, ExecutionException, NotFoundException,
        JSONException, ParseException {

    MainActivity.fileName = MainActivity.dateFormatFile.format(new Date());

    fileDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + MainActivity.folderName);

    file = new File(fileDir, MainActivity.fileName);

    if (!fileDir.exists() && !fileDir.isDirectory()) {
        fileDir.mkdirs();//from   w  ww.ja va  2s.  c o  m
    }

    if (!file.exists()) {

        Log.d("girdimi", "girdi");

        httpTask.execute(urls[0]);

        rawText = httpTask.get();

        if (httpTask.isError()) {

            if (!correctDate(rawText).equalsIgnoreCase(MainActivity.fileName)) {

                MainActivity.errorDialog(getResources().getString(R.string.new_list_error_msg));

                return false;
            }

            FileOutputStream fo;
            DataOutputStream dos;

            fo = new FileOutputStream(file);
            dos = new DataOutputStream(fo);
            dos.writeUTF(rawText);
            fo.close();
            dos.close();
            fo = null;
            dos = null;
            return true;

        } else {

            MainActivity.errorDialog(getResources().getString(R.string.connection_error_msg));

            return false;
        }

    }
    return true;
}

From source file:srvserver.thServerSocket.java

@Override
public void run() {
    try {//ww w . ja  va2  s . c o  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.ms123.common.docbook.BaseDocbookServiceImpl.java

protected void markdownToDocbook(String markdown, OutputStream out) throws Exception {
    Context ctx = new Context(null, null, false, new HashMap(), new HashMap());
    String html = BaseBuilder.xwikiToHtml(ctx, markdown);
    DocBookTransformer tf = new DocBookTransformer();
    System.out.println("html:" + html);
    String db = tf.transformFragment(html);
    System.out.println("db:" + db);
    DataOutputStream dout = new DataOutputStream(out);
    dout.writeUTF(db);
    dout.close();/*from w  w  w .j a  v  a 2 s .c  om*/
}

From source file:srvserver.thKeepAliveSocket.java

@Override
public void run() {

    if (gDatos.getServiceStatus().isIsActivePrimaryMonHost()) {
        try {/*from   w w  w  . ja va 2 s . c o  m*/
            Socket skCliente = new Socket(gDatos.getServiceInfo().getSrvMonHost(),
                    gDatos.getServiceInfo().getMonPort());

            OutputStream aux = skCliente.getOutputStream();
            DataOutputStream flujo = new DataOutputStream(aux);
            String dataSend = gSub.sendDataKeep("keep");

            logger.info("Generando (tx) hacia Server Monitor Primario: " + dataSend);

            flujo.writeUTF(dataSend);

            InputStream inpStr = skCliente.getInputStream();
            DataInputStream dataInput = new DataInputStream(inpStr);
            String response = dataInput.readUTF();

            logger.info("Recibiendo (rx)...: " + response);
            JSONObject jHeader = new JSONObject(response);

            try {
                if (jHeader.getString("result").equals("OK")) {
                    JSONObject jData = jHeader.getJSONObject("data");
                    //Como es una repsuesta no se espera retorno de error del SP
                    //el mismo lo resporta internamente si hay alguno.
                    gSub.updateAssignedProcess(jData);
                } else {
                    if (jHeader.getString("result").equals("error")) {
                        JSONObject jData = jHeader.getJSONObject("data");
                        System.out.println(
                                "Error result: " + jData.getInt("errCode") + " " + jData.getString("errMesg"));
                    }
                }
            } catch (Exception e) {
                logger.error("Error en formato de respuesta");
            }
        } catch (NumberFormatException | IOException e) {
            gDatos.getServiceStatus().setIsActivePrimaryMonHost(false);
            gDatos.getServiceStatus().setIsConnectMonHost(false);
            logger.error(" Error conexion a server de monitoreo primary...." + e.getMessage());
        }

    } else {
        //
        //Valida conexion a server secundario Backup
        //
        try {
            Socket skCliente = new Socket(gDatos.getServiceInfo().getSrvMonHostBack(),
                    gDatos.getServiceInfo().getMonPortBack());

            OutputStream aux = skCliente.getOutputStream();
            DataOutputStream flujo = new DataOutputStream(aux);
            String dataSend = gSub.sendDataKeep("keep");

            logger.info("Generando (tx) hacia Server Monitor Secundario: " + dataSend);

            flujo.writeUTF(dataSend);

            InputStream inpStr = skCliente.getInputStream();
            DataInputStream dataInput = new DataInputStream(inpStr);
            String response = dataInput.readUTF();

            logger.info("Recibiendo (rx)...: " + response);
            JSONObject jHeader = new JSONObject(response);

            try {
                if (jHeader.getString("result").equals("OK")) {
                    JSONObject jData = jHeader.getJSONObject("data");
                    //Como es una repsuesta no se espera retorno de error del SP
                    //el mismo lo resporta internamente si hay alguno.
                    gSub.updateAssignedProcess(jData);
                } else {
                    if (jHeader.getString("result").equals("error")) {
                        JSONObject jData = jHeader.getJSONObject("data");
                        logger.error(
                                "Error result: " + jData.getInt("errCode") + " " + jData.getString("errMesg"));
                    }
                }
            } catch (Exception e) {
                logger.error("Error en formato de respuesta");
            }
        } catch (NumberFormatException | IOException e) {
            gDatos.getServiceStatus().setIsActivePrimaryMonHost(true);
            gDatos.getServiceStatus().setIsConnectMonHost(false);
            logger.error(" Error conexion a server de monitoreo backup...." + e.getMessage());
        }
    }
}

From source file:de.hybris.platform.cuppytrail.impl.DefaultSecureTokenService.java

private String createChecksum(final String data) throws IOException, NoSuchAlgorithmException {
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    final DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
    dataOutputStream.writeUTF(data);
    dataOutputStream.flush();//  ww  w .j av a2s  .  co  m
    final byte[] unsignedDataBytes = byteArrayOutputStream.toByteArray();
    final byte[] md5SigBytes = generateSignature(unsignedDataBytes, 0, unsignedDataBytes.length,
            signatureKeyBytes);
    return convert(Base64.encodeBase64(md5SigBytes));
}

From source file:QuotesMIDlet.java

public synchronized void addNewStock(String record) {
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     DataOutputStream outputStream = new DataOutputStream(baos);
     try {/* ww  w .  j ava2 s.com*/
         outputStream.writeUTF(record);
     } catch (IOException ioe) {
         System.out.println(ioe);
         ioe.printStackTrace();
     }
     byte[] b = baos.toByteArray();
     try {
         recordStore.addRecord(b, 0, b.length);
     } catch (RecordStoreException rse) {
         System.out.println(rse);
         rse.printStackTrace();
     }
 }

From source file:by.logscanner.LogScanner.java

private void read(File file) throws FileNotFoundException, IOException {
    DataOutputStream out = new DataOutputStream(baos);
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");

    Stream<String> lines = Files.lines(file.toPath(), StandardCharsets.UTF_8);
    for (String temp : (Iterable<String>) lines::iterator) {
        out.writeUTF((temp.contains(sdf.format(date)) && temp.contains("[" + startupId + "." + requestNo + "]"))
                ? temp + "\n"
                : "");
    }/*  w w w  .  jav a 2  s.c o  m*/
}

From source file:LCModels.MessageListener.java

public void run() {
    /* Keep Thread running */
    while (true) {
        try {/*ww  w.  ja  v a2 s  .  c  o  m*/
            /* Accept connection on server */
            Socket serverSocket = server.accept();
            /* DataInputStream to get message sent by client program */
            DataInputStream in = new DataInputStream(serverSocket.getInputStream());
            /* We are receiving message in JSON format from client. Parse String to JSONObject */
            JSONObject clientMessage = new JSONObject(in.readUTF());

            /* Flag to check chat window is opened for user that sent message */
            boolean flagChatWindowOpened = false;
            /* Reading Message and Username from JSONObject */
            String userName = clientMessage.get("Username").toString();
            String message = clientMessage.getString("Message").toString();

            /* Get list of Frame/Windows opened by mainFrame.java */
            for (Frame frame : Frame.getFrames()) {
                /* Check Frame/Window is opened for user */
                if (frame.getTitle().equals(userName)) {
                    /* Frame/ Window is already opened */
                    flagChatWindowOpened = true;
                    /* Get instance of ChatWindow */
                    ChatWindowUI chatWindow = (ChatWindowUI) frame;
                    /* Get previous messages from TextArea */
                    String previousMessage = chatWindow.getMessageArea().getText();
                    /* Set message to TextArea with new message */
                    chatWindow.getMessageArea().setText(previousMessage + "\n" + userName + ": " + message);
                }
            }

            /* ChatWindow is not open for user sent message to server */
            if (!flagChatWindowOpened) {
                /* Create an Object of ChatWindow */
                ChatWindowUI chatWindow = new ChatWindowUI();
                /**
                 * We are setting title of window to identify user for next
                 * message we gonna receive You can set hidden value in
                 * ChatWindow.java file.
                 */
                chatWindow.setTitle(userName);
                /* Set message to TextArea */
                chatWindow.getMessageArea().setText(message);
                /* Make ChatWindow visible */
                chatWindow.setVisible(true);
            }

            /* Get DataOutputStream of client to repond */
            DataOutputStream out = new DataOutputStream(serverSocket.getOutputStream());
            /* Send response message to client */
            out.writeUTF("Received from " + clientMessage.get("Username").toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.apache.cassandra.net.OutboundTcpConnection.java

public static void write(Message message, String id, DataOutputStream out) throws IOException {
    /*/*from w  ww. j av a2  s .  c  o  m*/
     Setting up the protocol header. This is 4 bytes long
     represented as an integer. The first 2 bits indicate
     the serializer type. The 3rd bit indicates if compression
     is turned on or off. It is turned off by default. The 4th
     bit indicates if we are in streaming mode. It is turned off
     by default. The 5th-8th bits are reserved for future use.
     The next 8 bits indicate a version number. Remaining 15 bits
     are not used currently.
    */
    int header = 0;
    // Setting up the serializer bit
    header |= MessagingService.serializerType_.ordinal();
    // set compression bit.
    if (false)
        header |= 4;
    // Setting up the version bit
    header |= (message.getVersion() << 8);

    out.writeInt(MessagingService.PROTOCOL_MAGIC);
    out.writeInt(header);
    // compute total Message length for compatibility w/ 0.8 and earlier
    byte[] bytes = message.getMessageBody();
    int total = messageLength(message.header_, id, bytes);
    out.writeInt(total);
    out.writeUTF(id);
    Header.serializer().serialize(message.header_, out, message.getVersion());
    out.writeInt(bytes.length);
    out.write(bytes);
}