Example usage for java.io DataOutputStream writeBytes

List of usage examples for java.io DataOutputStream writeBytes

Introduction

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

Prototype

public final void writeBytes(String s) throws IOException 

Source Link

Document

Writes out the string to the underlying output stream as a sequence of bytes.

Usage

From source file:org.apache.hadoop.mapred.TestTaskLogsMonitor.java

/**
 * Test logs monitoring with {@link MiniMRCluster}
 * //from   w  ww .ja v a 2  s.c o  m
 * @throws IOException
 */
@Test
public void testLogsMonitoringWithMiniMR() throws IOException {

    MiniMRCluster mr = null;
    try {
        JobConf clusterConf = new JobConf();
        clusterConf.setLong(TaskTracker.MAP_USERLOG_RETAIN_SIZE, 10000L);
        clusterConf.setLong(TaskTracker.REDUCE_USERLOG_RETAIN_SIZE, 10000L);
        mr = new MiniMRCluster(1, "file:///", 3, null, null, clusterConf);

        JobConf conf = mr.createJobConf();

        Path inDir = new Path(TEST_ROOT_DIR + "/input");
        Path outDir = new Path(TEST_ROOT_DIR + "/output");
        FileSystem fs = FileSystem.get(conf);
        if (fs.exists(outDir)) {
            fs.delete(outDir, true);
        }
        if (!fs.exists(inDir)) {
            fs.mkdirs(inDir);
        }
        String input = "The quick brown fox jumped over the lazy dog";
        DataOutputStream file = fs.create(new Path(inDir, "part-0"));
        file.writeBytes(input);
        file.close();

        conf.setInputFormat(TextInputFormat.class);
        conf.setOutputKeyClass(LongWritable.class);
        conf.setOutputValueClass(Text.class);

        FileInputFormat.setInputPaths(conf, inDir);
        FileOutputFormat.setOutputPath(conf, outDir);
        conf.setNumMapTasks(1);
        conf.setNumReduceTasks(0);
        conf.setMapperClass(LoggingMapper.class);

        RunningJob job = JobClient.runJob(conf);
        assertTrue(job.getJobState() == JobStatus.SUCCEEDED);
        for (TaskCompletionEvent tce : job.getTaskCompletionEvents(0)) {
            long length = TaskLog.getTaskLogFile(tce.getTaskAttemptId(), TaskLog.LogName.STDOUT).length();
            assertTrue("STDOUT log file length for " + tce.getTaskAttemptId() + " is " + length
                    + " and not <=10000", length <= 10000);
        }
    } finally {
        if (mr != null) {
            mr.shutdown();
        }
    }
}

From source file:com.bjorsond.android.timeline.sync.ServerUploader.java

protected static void uploadFile(String locationFilename, String saveFilename) {
    System.out.println("saving " + locationFilename + "!! ");
    if (!saveFilename.contains("."))
        saveFilename = saveFilename + Utilities.getExtension(locationFilename);

    if (!fileExistsOnServer(saveFilename)) {

        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;

        String pathToOurFile = locationFilename;
        String urlServer = "http://folk.ntnu.no/bjornava/upload/upload.php";
        //         String urlServer = "http://timelinegamified.appspot.com/upload.php";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024 * 1024;

        try {/* ww w . j a v a 2  s .c o m*/
            FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));

            URL url = new URL(urlServer);
            connection = (HttpURLConnection) url.openConnection();

            // Allow Inputs & Outputs
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            // Enable POST method
            connection.setRequestMethod("POST");

            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                    + saveFilename + "\"" + lineEnd);
            outputStream.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // Read file
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {
                outputStream.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

            fileInputStream.close();
            outputStream.flush();
            outputStream.close();

            System.out.println("Server response: " + serverResponseCode + " Message: " + serverResponseMessage);
        } catch (Exception ex) {
            //Exception handling
        }
    } else {
        System.out.println("image exists on server");
    }
}

From source file:com.kyne.webby.rtk.web.WebServer.java

/**
 * Read a print a static file (js, css, html or png).
 * @param path the path to the file//from  ww  w.j a v  a2  s  .  c o  m
 * @param type the mimetype
 * @param jsStates some javascripts variables that may be initialized in the printed content. Null if not required.
 * @param clientSocket the client-side socket
 */
public void printStaticFile(final String path, final String type, final Socket clientSocket,
        final Map<String, String> jsStates) {
    try {
        final File htmlPage = new File(path);
        if (htmlPage.exists()) {
            final DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
            out.writeBytes("HTTP/1.1 200 OK\r\n");
            out.writeBytes("Content-Type: " + type + "; charset=utf-8\r\n");
            out.writeBytes("Cache-Control: no-cache \r\n");
            out.writeBytes("Server: Bukkit Webby\r\n");
            out.writeBytes("Connection: Close\r\n\r\n");
            if (jsStates != null) {
                out.writeBytes("<script type='text/javascript'>");
                for (final String var : jsStates.keySet()) {
                    out.writeBytes("var " + var + " = '" + jsStates.get(var) + "';");
                }
                out.writeBytes("</script>");
            }
            if (!this.htmlCache.containsKey(path)) { //Pages are static, so we can "pre-read" them. Dynamic content will be rendered with javascript
                final FileInputStream fis = new FileInputStream(htmlPage);
                final byte fileContent[] = new byte[(int) htmlPage.length()];
                fis.read(fileContent);
                fis.close();
                this.htmlCache.put(path, fileContent);
            } else {
                LogHelper.debug("File will be added in Webby's cache");
            }
            out.write(this.htmlCache.get(path));
            out.flush();
            out.close();
        } else {
            LogHelper.warn("Requested file " + path + " can't be found");
        }
    } catch (final SocketException e) {
        /* Or not ! */
    } catch (final Exception e) {
        LogHelper.error(e.getMessage(), e);
    }
}

From source file:com.cypress.cysmart.RDKEmulatorView.MicrophoneEmulatorFragment.java

private void createWavFile(File fileToConvert, String wavFilePath) {
    try {/*from   ww w  .  ja v  a2 s  .c  o m*/
        long mySubChunk1Size = 16;
        int myBitsPerSample = 16;
        int myFormat = 1;
        long myChannels = 1;
        long mySampleRate = 16000;
        long myByteRate = mySampleRate * myChannels * myBitsPerSample / 8;
        int myBlockAlign = (int) (myChannels * myBitsPerSample / 8);

        byte[] clipData = getBytesFromFile(fileToConvert);

        long myDataSize = clipData.length;
        long myChunk2Size = myDataSize * myChannels * myBitsPerSample / 8;
        long myChunkSize = 36 + myChunk2Size;

        OutputStream os;
        os = new FileOutputStream(new File(wavFilePath));
        BufferedOutputStream bos = new BufferedOutputStream(os);
        DataOutputStream outFile = new DataOutputStream(bos);

        outFile.writeBytes("RIFF"); // 00 - RIFF
        outFile.write(intToByteArray((int) myChunkSize), 0, 4); // 04 - how big is the rest of this file?
        outFile.writeBytes("WAVE"); // 08 - WAVE
        outFile.writeBytes("fmt "); // 12 - fmt
        outFile.write(intToByteArray((int) mySubChunk1Size), 0, 4); // 16 - size of this chunk
        outFile.write(shortToByteArray((short) myFormat), 0, 2); // 20 - what is the audio format? 1 for PCM = Pulse Code Modulation
        outFile.write(shortToByteArray((short) myChannels), 0, 2); // 22 - mono or stereo? 1 or 2?  (or 5 or ???)
        outFile.write(intToByteArray((int) mySampleRate), 0, 4); // 24 - samples per second (numbers per second)
        outFile.write(intToByteArray((int) myByteRate), 0, 4); // 28 - bytes per second
        outFile.write(shortToByteArray((short) myBlockAlign), 0, 2); // 32 - # of bytes in one sample, for all channels
        outFile.write(shortToByteArray((short) myBitsPerSample), 0, 2); // 34 - how many bits in a sample(number)?  usually 16 or 24
        outFile.writeBytes("data"); // 36 - data
        outFile.write(intToByteArray((int) myDataSize), 0, 4); // 40 - how big is this data chunk
        outFile.write(clipData); // 44 - the actual data itself - just a long string of numbers

        outFile.flush();
        outFile.close();

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

From source file:com.docd.purefm.tasks.SearchCommandLineTask.java

@Override
protected Void doInBackground(String... params) {
    final CommandFind command = new CommandFind(mStartDirectory.getAbsolutePath(), params);
    // NOTE this doesn't use Shell because we can't create a new CommandLineFile from
    // CommandOutput because executing readlink (which is done in CommandLineFile constructor)
    // will freeze the whole Shell
    DataOutputStream os = null;
    BufferedReader is = null;/*from w  w w .j  av  a2  s .co m*/
    BufferedReader err = null;
    Process process = null;
    try {
        process = Runtime.getRuntime().exec(mSettings.isSuEnabled() ? "su" : "sh");
        os = new DataOutputStream(process.getOutputStream());
        is = new BufferedReader(new InputStreamReader(process.getInputStream()));
        err = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        os.writeBytes(command.toString());
        os.writeBytes("exit\n");
        os.flush();

        String line;
        try {
            while (!isCancelled() && (line = is.readLine()) != null) {
                this.publishProgress(CommandLineFile.fromLSL(null, line));
            }
        } catch (EOFException e) {
            //ignore
        }

        try {
            while (!isCancelled() && (line = err.readLine()) != null) {
                final Matcher denied = DENIED.matcher(line);
                if (denied.matches()) {
                    this.mDenied.add(denied.group(1));
                }
            }
        } catch (EOFException e) {
            //ignore
        }
        process.waitFor();
    } catch (Exception e) {
        Log.w("Exception while searching", e.toString());
    } finally {
        IOUtils.closeQuietly(os);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(err);
        if (process != null) {
            try {
                process.destroy();
            } catch (Exception e) {
                //ignored
            }
        }
    }
    return null;
}

From source file:org.apache.hadoop.mapred.TestTaskLogsMonitor.java

/**
 * Test the truncation of DEBUGOUT file by {@link TaskLogsMonitor}
 * @throws IOException /* www  .  j  a  va  2 s  . c om*/
 */
@Test
public void testDebugLogsTruncationWithMiniMR() throws IOException {

    MiniMRCluster mr = null;
    try {
        JobConf clusterConf = new JobConf();
        clusterConf.setLong(TaskTracker.MAP_USERLOG_RETAIN_SIZE, 10000L);
        clusterConf.setLong(TaskTracker.REDUCE_USERLOG_RETAIN_SIZE, 10000L);
        mr = new MiniMRCluster(1, "file:///", 3, null, null, clusterConf);

        JobConf conf = mr.createJobConf();

        Path inDir = new Path(TEST_ROOT_DIR + "/input");
        Path outDir = new Path(TEST_ROOT_DIR + "/output");
        FileSystem fs = FileSystem.get(conf);
        if (fs.exists(outDir)) {
            fs.delete(outDir, true);
        }
        if (!fs.exists(inDir)) {
            fs.mkdirs(inDir);
        }
        String input = "The quick brown fox jumped over the lazy dog";
        DataOutputStream file = fs.create(new Path(inDir, "part-0"));
        file.writeBytes(input);
        file.close();

        conf.setInputFormat(TextInputFormat.class);
        conf.setOutputKeyClass(LongWritable.class);
        conf.setOutputValueClass(Text.class);

        FileInputFormat.setInputPaths(conf, inDir);
        FileOutputFormat.setOutputPath(conf, outDir);
        conf.setNumMapTasks(1);
        conf.setMaxMapAttempts(1);
        conf.setNumReduceTasks(0);
        conf.setMapperClass(TestMiniMRMapRedDebugScript.MapClass.class);

        // copy debug script to cache from local file system.
        Path scriptPath = new Path(TEST_ROOT_DIR, "debug-script.txt");
        String debugScriptContent = "for ((i=0;i<1000;i++)); " + "do " + "echo \"Lots of logs! Lots of logs! "
                + "Waiting to be truncated! Lots of logs!\";" + "done";
        DataOutputStream scriptFile = fs.create(scriptPath);
        scriptFile.writeBytes(debugScriptContent);
        scriptFile.close();
        new File(scriptPath.toUri().getPath()).setExecutable(true);

        URI uri = scriptPath.toUri();
        DistributedCache.createSymlink(conf);
        DistributedCache.addCacheFile(uri, conf);
        conf.setMapDebugScript(scriptPath.toUri().getPath());

        RunningJob job = null;
        try {
            JobClient jc = new JobClient(conf);
            job = jc.submitJob(conf);
            try {
                jc.monitorAndPrintJob(conf, job);
            } catch (InterruptedException e) {
                //
            }
        } catch (IOException ioe) {
        } finally {
            for (TaskCompletionEvent tce : job.getTaskCompletionEvents(0)) {
                File debugOutFile = TaskLog.getTaskLogFile(tce.getTaskAttemptId(), TaskLog.LogName.DEBUGOUT);
                if (debugOutFile.exists()) {
                    long length = debugOutFile.length();
                    assertTrue("DEBUGOUT log file length for " + tce.getTaskAttemptId() + " is " + length
                            + " and not =10000", length == 10000);
                }
            }
        }
    } finally {
        if (mr != null) {
            mr.shutdown();
        }
    }
}

From source file:org.wso2.carbon.automation.extensions.servers.webserver.SimpleWebServer.java

private void httpHandler(BufferedReader input, DataOutputStream output)
        throws IOException, InterruptedException {
    String contentType;//from   w ww. j  a  v  a 2s  .  c  o m
    String tmp;
    try {
        tmp = input.readLine(); //read from the stream
        contentType = input.readLine();
        log.info(tmp);
        assert tmp != null;
        String sampleReturnResponse = "<testResponse>\n" + "   <message>" + tmp.toUpperCase()
                + "Success</message>\n" + " </testResponse>";
        output.writeBytes(constructHttpHeader(expectedResponseCode, contentType));
        output.write(sampleReturnResponse.getBytes(Charset.defaultCharset()));
    } catch (Exception e) {
        log.error("error" + e.getMessage());
    } finally {
        output.flush();
        Thread.sleep(1000);
        input.close();
        output.close();
    }
}

From source file:org.apache.jmeter.protocol.amf.proxy.AmfProxy.java

/**
 * Write an error message to the client. The message should be the full HTTP
 * response./*from w  w  w  .j a  va2s.  c  om*/
 *
 * @param message
 *            the message to write
 */
private void writeErrorToClient(String message) {
    try {
        OutputStream sockOut = clientSocket.getOutputStream();
        DataOutputStream out = new DataOutputStream(sockOut);
        out.writeBytes(message);
        out.flush();
    } catch (Exception e) {
        log.warn("Exception while writing error", e);
    }
}

From source file:org.apache.hadoop.mapred.TestTaskKilling.java

private void createInput(Path inDir, Configuration conf) throws IOException {
    String input = "Hadoop is framework for data intensive distributed " + "applications.\n"
            + "Hadoop enables applications to work with thousands of nodes.";
    FileSystem fs = inDir.getFileSystem(conf);
    if (!fs.mkdirs(inDir)) {
        throw new IOException("Failed to create the input directory:" + inDir.toString());
    }/*from  w  w w .  j a  v  a 2  s  . c o  m*/
    fs.setPermission(inDir, new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.ALL));
    DataOutputStream file = fs.create(new Path(inDir, "data.txt"));
    int i = 0;
    while (i < 1000 * 3000) {
        file.writeBytes(input);
        i++;
    }
    file.close();
}

From source file:org.maikelwever.droidpile.backend.ApiConnecter.java

public String postData(ArrayList<NameValuePair> payload, String... data) throws IOException {
    if (data.length < 1) {
        throw new IllegalArgumentException("More than 1 argument is required.");
    }/*from  w ww  .  j  a va2  s  .c om*/

    String url = this.baseUrl;
    String suffix = "";
    for (String arg : data) {
        suffix += "/" + arg;
    }

    suffix += "/";

    Log.d("droidpile", "URL we will call: " + url + suffix);

    url += suffix;
    URL uri = new URL(url);
    InputStreamReader is;
    HttpURLConnection con;

    if (url.startsWith("https")) {
        con = (HttpsURLConnection) uri.openConnection();
    } else {
        con = (HttpURLConnection) uri.openConnection();
    }

    String urlParameters = URLEncodedUtils.format(payload, ENCODING);

    con.setDoInput(true);
    con.setDoOutput(true);
    con.setInstanceFollowRedirects(false);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    con.setRequestProperty("charset", ENCODING);
    con.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes(ENCODING).length));
    con.setUseCaches(false);

    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();
    is = new InputStreamReader(con.getInputStream(), ENCODING);

    StringBuilder sb = new StringBuilder();
    BufferedReader br = new BufferedReader(is);
    String read = br.readLine();

    while (read != null) {
        sb.append(read);
        read = br.readLine();
    }
    String stringData = sb.toString();
    con.disconnect();
    return stringData;
}