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:org.darwinathome.server.controller.HubController.java

@RequestMapping(Hub.AUTHENTICATE_SERVICE)
public void authenticate(@RequestParam(Hub.PARAM_BODY_NAME) String bodyName,
        @RequestParam(Hub.PARAM_PASSWORD) String password, OutputStream outputStream) throws IOException {
    log.info(Hub.AUTHENTICATE_SERVICE);/*w ww  .  j  a v  a  2 s .  c om*/
    DataOutputStream dos = new DataOutputStream(outputStream);
    Player player = storage.authenticate(bodyName, password);
    if (player != null) {
        PlayerSession session = new PlayerSession(player);
        sessionMap.put(session.getToken(), session);
        dos.writeUTF(Hub.SUCCESS);
        dos.writeUTF(session.getToken());
    } else {
        dos.writeUTF(Hub.FAILURE);
        dos.writeUTF(Failure.AUTHENTICATION.toString());
    }
    dos.close();
}

From source file:org.darwinathome.server.controller.HubController.java

@RequestMapping(Hub.DOCUMENTATION_SERVICE)
@ResponseBody/*from w  w w  .  jav  a2 s  . c o  m*/
public void getDocumentation(@RequestParam(Hub.PARAM_TITLE) String title, OutputStream outputStream) {
    log.info(Hub.DOCUMENTATION_SERVICE);
    DataOutputStream dos = new DataOutputStream(outputStream);
    File docsDirectory = new File(servletContext.getRealPath(DOC_DIR));
    try {
        if (!docsDirectory.isDirectory()) {
            log.fatal("Docs directory not found!");
            dos.writeUTF(Hub.FAILURE);
            dos.writeUTF(Failure.SYSTEM.toString());
            return;
        }
        if (title.isEmpty()) {
            File[] textFiles = docsDirectory.listFiles(new TextFilter());
            dos.writeUTF(Hub.SUCCESS);
            dos.writeUTF(title);
            dos.writeShort(textFiles.length);
            for (File docFile : textFiles) {
                dos.writeUTF(
                        docFile.getName().substring(0, docFile.getName().length() - DOC_FILE_SUFFIX.length()));
            }
        } else {
            File docFile = new File(docsDirectory, title + DOC_FILE_SUFFIX);
            if (!docFile.exists()) {
                dos.writeUTF(Hub.FAILURE);
                dos.writeUTF(Failure.SYSTEM.toString());
                return;
            }
            List<String> lines = getLines(docFile);
            dos.writeUTF(Hub.SUCCESS);
            dos.writeUTF(title);
            dos.writeShort(lines.size());
            for (String line : lines) {
                dos.writeUTF(line);
            }
        }
    } catch (IOException e) {
        log.error("Problem delivering documentation", e);
    }
}

From source file:org.efaps.webdav4vfs.test.ramvfs.RamFileRandomAccessContent.java

/**
 * {@inheritDoc}// www  .  ja va  2  s .c o m
 */
public void writeUTF(final String _str) throws IOException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream(_str.length());
    final DataOutputStream dataOut = new DataOutputStream(out);
    dataOut.writeUTF(_str);
    dataOut.flush();
    dataOut.close();
    final byte[] b = out.toByteArray();
    write(b);
}

From source file:BugTracker.java

private void saveBugs() {
    // Save bugs to a file.
    DataOutputStream out = null;
    try {/*w w  w. j a  v a  2  s  . co m*/
        File file = new File("bugs.dat");

        out = new DataOutputStream(new FileOutputStream(file));

        for (int i = 0; i < table.getItemCount(); i++) {
            TableItem item = table.getItem(i);
            out.writeUTF(item.getText(0));
            out.writeUTF(item.getText(1));
            out.writeUTF(item.getText(2));
            out.writeBoolean(item.getText(3).equalsIgnoreCase("YES"));
        }
    } catch (IOException ioe) {
        // Ignore.
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:hudson.remoting.Engine.java

@SuppressWarnings({ "ThrowableInstanceNeverThrown" })
@Override//w w  w.  j  av  a2s  .co  m
public void run() {
    try {
        boolean first = true;
        while (true) {
            if (first) {
                first = false;
            } else {
                if (noReconnect)
                    return; // exit
            }

            listener.status("Locating server among " + candidateUrls);
            Throwable firstError = null;
            String port = null;

            for (URL url : candidateUrls) {
                String s = url.toExternalForm();
                if (!s.endsWith("/"))
                    s += '/';
                URL salURL = new URL(s + "tcpSlaveAgentListener/");

                // find out the TCP port
                HttpURLConnection con = (HttpURLConnection) salURL.openConnection();
                if (con instanceof HttpURLConnection && credentials != null) {
                    String encoding = new String(Base64.encodeBase64(credentials.getBytes()));
                    con.setRequestProperty("Authorization", "Basic " + encoding);
                }
                try {
                    try {
                        con.setConnectTimeout(30000);
                        con.setReadTimeout(60000);
                        con.connect();
                    } catch (IOException x) {
                        if (firstError == null) {
                            firstError = new IOException(
                                    "Failed to connect to " + salURL + ": " + x.getMessage()).initCause(x);
                        }
                        continue;
                    }
                    port = con.getHeaderField("X-Hudson-JNLP-Port");
                    if (con.getResponseCode() != 200) {
                        if (firstError == null)
                            firstError = new Exception(salURL + " is invalid: " + con.getResponseCode() + " "
                                    + con.getResponseMessage());
                        continue;
                    }
                    if (port == null) {
                        if (firstError == null)
                            firstError = new Exception(url + " is not Hudson");
                        continue;
                    }
                } finally {
                    con.disconnect();
                }

                // this URL works. From now on, only try this URL
                hudsonUrl = url;
                firstError = null;
                candidateUrls = Collections.singletonList(hudsonUrl);
                break;
            }

            if (firstError != null) {
                listener.error(firstError);
                return;
            }

            Socket s = connect(port);

            listener.status("Handshaking");

            DataOutputStream dos = new DataOutputStream(s.getOutputStream());
            BufferedInputStream in = new BufferedInputStream(s.getInputStream());

            dos.writeUTF("Protocol:JNLP2-connect");
            Properties props = new Properties();
            props.put("Secret-Key", secretKey);
            props.put("Node-Name", slaveName);
            if (cookie != null)
                props.put("Cookie", cookie);
            ByteArrayOutputStream o = new ByteArrayOutputStream();
            props.store(o, null);
            dos.writeUTF(o.toString("UTF-8"));

            String greeting = readLine(in);
            if (greeting.startsWith("Unknown protocol")) {
                LOGGER.info("The server didn't understand the v2 handshake. Falling back to v1 handshake");
                s.close();
                s = connect(port);
                in = new BufferedInputStream(s.getInputStream());
                dos = new DataOutputStream(s.getOutputStream());

                dos.writeUTF("Protocol:JNLP-connect");
                dos.writeUTF(secretKey);
                dos.writeUTF(slaveName);

                greeting = readLine(in); // why, oh why didn't I use DataOutputStream when writing to the network?
                if (!greeting.equals(GREETING_SUCCESS)) {
                    onConnectionRejected(greeting);
                    continue;
                }
            } else {
                if (greeting.equals(GREETING_SUCCESS)) {
                    Properties responses = readResponseHeaders(in);
                    cookie = responses.getProperty("Cookie");
                } else {
                    onConnectionRejected(greeting);
                    continue;
                }
            }

            final Socket socket = s;
            final Channel channel = new Channel("channel", executor, in,
                    new BufferedOutputStream(s.getOutputStream()));
            PingThread t = new PingThread(channel) {
                protected void onDead() {
                    try {
                        if (!channel.isInClosed()) {
                            LOGGER.info("Ping failed. Terminating the socket.");
                            socket.close();
                        }
                    } catch (IOException e) {
                        LOGGER.log(SEVERE, "Failed to terminate the socket", e);
                    }
                }
            };
            t.start();
            listener.status("Connected");
            channel.join();
            listener.status("Terminated");
            t.interrupt(); // make sure the ping thread is terminated
            listener.onDisconnect();

            if (noReconnect)
                return; // exit
            // try to connect back to the server every 10 secs.
            waitForServerToBack();
        }
    } catch (Throwable e) {
        listener.error(e);
    }
}

From source file:BugTrackerJFace.java

private void saveBugs(Vector v) {
    // Save bugs to a file.
    DataOutputStream out = null;
    try {//from   w ww. ja v  a 2s .  c  om
        File file = new File("bugs.dat");

        out = new DataOutputStream(new FileOutputStream(file));

        for (int i = 0; i < v.size(); i++) {
            Bug bug = (Bug) v.elementAt(i);
            out.writeUTF(bug.id);
            out.writeUTF(bug.summary);
            out.writeUTF(bug.assignedTo);
            out.writeBoolean(bug.isSolved);
        }
    } catch (IOException ioe) {
        // Ignore.
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.rdfhdt.hdt.impl.BufferedCompressedStreamingNoDictionary.java

@Override
public void startProcessing() {
    // initial tasks

    // WRITE IF SOME CONF!=DEFAULT

    try {//from www  .  j a v a2  s  .  com
        CRCOutputStream outCRC = new CRCOutputStream(this.out, new CRC16());
        IOUtil.writeString(outCRC, "$CNF");

        outCRC.setCRC(new CRC8());
        VByte.encode(outCRC, 3); // write length of properties to write(to date just 3)
        outCRC.writeCRC();

        outCRC.setCRC(new CRC32());
        DataOutputStream outData = new DataOutputStream(outCRC);

        outData.writeUTF(CSVocabulary.STORE_SUBJ_DICTIONARY + "=" + store_subj_dictionary);

        outData.writeUTF(CSVocabulary.STORE_OBJ_DICTIONARY + "=" + store_obj_dictionary);

        outData.writeUTF(CSVocabulary.DISABLE_CONSISTENT_PREDICATES + "=" + disable_consistent_predicates);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:org.rdfhdt.hdt.impl.BufferedCompressedStreaming.java

@Override
public void startProcessing() {
    // initial tasks

    // WRITE CONF!=DEFAULT

    try {//from   w w  w  .j a v  a 2 s .com
        CRCOutputStream outCRC = new CRCOutputStream(this.out, new CRC16());
        IOUtil.writeString(outCRC, "$CNF");

        outCRC.setCRC(new CRC8());
        VByte.encode(outCRC, 3); // write length of properties to write(to date just 3)
        outCRC.writeCRC();

        outCRC.setCRC(new CRC32());
        DataOutputStream outData = new DataOutputStream(outCRC);

        outData.writeUTF(CSVocabulary.STORE_SUBJ_DICTIONARY + "=" + store_subj_dictionary);
        outData.writeUTF(CSVocabulary.STORE_OBJ_DICTIONARY + "=" + true);
        outData.writeUTF(CSVocabulary.DISABLE_CONSISTENT_PREDICATES + "=" + disable_consistent_predicates);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.project.qrypto.keymanagement.KeyManager.java

/**
 * Saves the Keystore. Uses either internal or external memory depending on settings.
 * @param context the context to use/*from  www .  j a va 2  s.c  o m*/
 * 
 * @throws IOException if the outstream is somehow bad or interrupted
 * @throws InvalidCipherTextException if the key is bad or the data is bad
 */
public void commit(Context context) throws IOException, InvalidCipherTextException {
    //Commit Preferences
    Editor edit = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE).edit();
    edit.putBoolean(USE_INTERNAL_STORAGE, internalStorage);
    edit.putBoolean(PASSWORD_PROTECTED, passwordProtected);
    edit.putBoolean(SETUP_COMPLETE, true);
    edit.commit();

    //Commit Key Data
    DataOutputStream writer = null;
    ByteArrayOutputStream output = null;

    //Create the proper streams
    if (passwordProtected) {
        output = new ByteArrayOutputStream();
        writer = new DataOutputStream(output);
    } else {
        writer = new DataOutputStream(getAssociatedOutFileStream(context));
    }

    //Write everything out to the stream
    writer.writeUTF("RCYTHR1"); //Special indicator to determine if we decrypt properly
    writer.writeInt(lookup.size());
    for (Entry<String, Key> entry : lookup.entrySet()) {
        writer.writeUTF(entry.getKey());
        entry.getValue().writeData(writer);
    }
    writer.writeByte(1); //Prevent null padding from causing too much truncation.

    writer.flush();

    //If we're password protecting we still need to encrypt and output to file
    if (passwordProtected) {
        OutputStream finalOut = getAssociatedOutFileStream(context);
        finalOut.write(AES.handle(true, output.toByteArray(), keyStoreKey));
        finalOut.close();
    }

    writer.close();
}

From source file:org.openxdata.server.serializer.JavaRosaXformSerializer.java

@SuppressWarnings("unchecked")
public void serializeStudies(OutputStream os, Object data) {
    List<Object[]> studies = (List<Object[]>) data;
    DataOutputStream dos = new DataOutputStream(os);

    String xml = "<?xml version='1.0'?><forms> ";

    for (Object[] study : studies) {

        int studyId = (Integer) study[0];
        String studyName = (String) study[1];
        xml += "<form url='http://localhost:8888/formdownloadservlet?action=downloadforms&amp;uname=Mark&amp;pw=daniel123&amp;formser=JRXformSerializer&amp;studyId="
                + studyId + "'>" + escapeXml(studyName) + "</form>";
    }//w  ww.j ava 2s .  c  om
    xml += "</forms>";
    try {
        dos.writeUTF(xml.trim());
        dos.flush();
    } catch (IOException e) {
        throw new UnexpectedException(e);
    }

}