Example usage for java.io DataOutputStream DataOutputStream

List of usage examples for java.io DataOutputStream DataOutputStream

Introduction

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

Prototype

public DataOutputStream(OutputStream out) 

Source Link

Document

Creates a new data output stream to write data to the specified underlying output stream.

Usage

From source file:com.jkoolcloud.jesl.net.socket.SocketClient.java

/**
 * {@inheritDoc}//from  www.  j  a  v a2  s. co m
 */
@Override
public synchronized void connect() throws IOException {
    if (isConnected())
        return;
    if (secure) {
        SocketFactory socketFactory = SSLSocketFactory.getDefault();
        socket = socketFactory.createSocket(host, port);
    } else {
        socket = new Socket(host, port);
    }
    out = new DataOutputStream(socket.getOutputStream());
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}

From source file:com.nicolacimmino.expensestracker.tracker.expenses_api.ExpensesApiRequest.java

public boolean performRequest() {

    jsonResponseArray = null;/*from   w w w . ja v a2 s. co  m*/
    jsonResponseObject = null;

    HttpURLConnection connection = null;

    try {

        // Get the request JSON document as U*TF-8 encoded bytes, suitable for HTTP.
        mRequestData = ((mRequestData != null) ? mRequestData : new JSONObject());
        byte[] postDataBytes = mRequestData.toString(0).getBytes("UTF-8");

        URL url = new URL(mUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(mRequestMethod == "GET" ? false : true); // No body data for GET
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod(mRequestMethod);
        connection.setUseCaches(false);

        // For all methods except GET we need to include data in the body.
        if (mRequestMethod != "GET") {
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("charset", "utf-8");
            connection.setRequestProperty("Content-Length", "" + Integer.toString(postDataBytes.length));

            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.write(postDataBytes);
            wr.flush();
            wr.close();
        }

        if (connection.getResponseCode() == 200) {
            InputStreamReader in = new InputStreamReader((InputStream) connection.getContent());
            BufferedReader buff = new BufferedReader(in);
            String line = buff.readLine().toString();
            buff.close();
            Object json = new JSONTokener(line).nextValue();
            if (json.getClass() == JSONObject.class) {
                jsonResponseObject = (JSONObject) json;
            } else if (json.getClass() == JSONArray.class) {
                jsonResponseArray = (JSONArray) json;
            } // else members will be left to null indicating no valid response.
            return true;
        }

    } catch (MalformedURLException e) {
        Log.e(TAG, e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
    } catch (JSONException e) {
        Log.e(TAG, e.getMessage());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

    return false;
}

From source file:com.csipsimple.backup.SipProfilesHelper.java

@Override
public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) {
    boolean forceBackup = (oldState == null);

    long fileModified = databaseFile.lastModified();
    try {//from ww w . j av a 2s .com
        if (!forceBackup) {
            FileInputStream instream = new FileInputStream(oldState.getFileDescriptor());
            DataInputStream in = new DataInputStream(instream);
            long lastModified = in.readLong();
            in.close();

            if (lastModified < fileModified) {
                forceBackup = true;
            }
        }
    } catch (IOException e) {
        Log.e(THIS_FILE, "Cannot manage previous local backup state", e);
        forceBackup = true;
    }

    Log.d(THIS_FILE, "Will backup profiles ? " + forceBackup);
    if (forceBackup) {
        JSONArray accountsSaved = SipProfileJson.serializeSipProfiles(mContext);
        try {
            writeData(data, accountsSaved.toString());
        } catch (IOException e) {
            Log.e(THIS_FILE, "Cannot manage remote backup", e);
        }
    }

    try {
        FileOutputStream outstream = new FileOutputStream(newState.getFileDescriptor());
        DataOutputStream out = new DataOutputStream(outstream);
        out.writeLong(fileModified);
        out.close();
    } catch (IOException e) {
        Log.e(THIS_FILE, "Cannot manage final local backup state", e);
    }
}

From source file:com.juhnowski.sanskrvar.Main.java

public Entry checkWord(String word) {
    StringBuilder sb = new StringBuilder();
    sb.append("http://www.sanskrit-lexicon.uni-koeln.de/scans/WILScan/2014/web/webtc/getword.php?key=");
    sb.append(word);//from ww w .java  2 s .  c  o m
    sb.append("&filter=roman&noLit=off&transLit=hk");
    String targetURL = sb.toString();
    String urlParameters = "";

    HttpURLConnection connection = null;

    try {
        //Create connection
        URL url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/xhr");

        connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

        connection.setUseCaches(false);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.close();

        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        String s = response.toString();
        if (!s.contains("<h2>not found:")) {
            return new Entry(word, s);
        } else {
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}

From source file:hudson.plugins.clearcase.cleartool.CTLauncher.java

/**
 * Run a clearcase command without output to the console, the result of the
 * command is returned as a String// ww w. j  a  v a 2s  . c om
 * 
 * @param cmd
 *            the command to launch using the clear tool executable
 * @param filePath
 *            optional, the path where the command should be launched
 * @return the result of the command
 * @throws IOException
 * @throws InterruptedException
 */
public String run(ArgumentListBuilder args, FilePath filePath)
        throws IOException, InterruptedException, ClearToolError {
    FilePath path = filePath;
    if (path == null) {
        path = this.nodeRoot;
    }
    ArgumentListBuilder cmd = new ArgumentListBuilder(this.executable);
    cmd.add(args.toCommandArray());

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    DataOutputStream logStream;

    if (logFile == null) {
        logStream = new DataOutputStream(new NullOutputStream());
    } else {
        logStream = new DataOutputStream(new FileOutputStream(logFile, true /*append*/));
    }

    ForkOutputStream forkStream = new ForkOutputStream(outStream, logStream);

    int code;
    String cleartoolResult;

    try {
        logStream.writeBytes(">>> " + cmd.toStringWithQuote() + "\n");

        ProcStarter starter = launcher.launch();
        starter.cmds(cmd);
        starter.envs(this.env);
        starter.stdout(forkStream);
        starter.pwd(path);

        code = launcher.launch(starter).join();

        cleartoolResult = outStream.toString();
        logStream.writeBytes("\n\n"); // to separate the commands
    } finally {
        forkStream.close();
    }

    if (code != 0 || cleartoolResult.contains("cleartool: Error")) {
        throw new ClearToolError(cmd.toStringWithQuote(), cleartoolResult, code, path);
    }

    return cleartoolResult;
}

From source file:GUI.Starts.java

private void predict() {
    int i, predict_probability = 0;
    svm_parameter param = new svm_parameter();
    param.svm_type = svm_parameter.EPSILON_SVR;
    param.kernel_type = svm_parameter.LINEAR;
    param.coef0 = 0;//from   w ww.j av a2s .  c o  m
    param.degree = 3;
    param.gamma = 0;
    param.nu = 0.5;
    param.cache_size = 40;
    param.eps = 1e-3;
    param.p = 0.1;
    param.shrinking = 1;
    param.probability = 0;
    try {
        BufferedReader input = new BufferedReader(new FileReader("astra.test.data"));
        DataOutputStream output = new DataOutputStream(
                new BufferedOutputStream(new FileOutputStream("astra.out")));
        svm_model model = svm.svm_load_model("astra.model");
        if (predict_probability == 1) {
            if (svm.svm_check_probability_model(model) == 0) {
                System.err.print("Model does not support probabiliy estimates\n");
                System.exit(1);
            }
        } else if (svm.svm_check_probability_model(model) != 0) {
            System.out.print("Model supports probability estimates, but disabled in prediction.\n");
        }
        Predict.predict(input, output, model, predict_probability);

        input.close();
        output.close();
    } catch (FileNotFoundException e) {
        System.out.println("File doesnt exitst");
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("Array out of bounds");
    } catch (IOException e) {
        System.out.println("Something went wrong");
    }
    //        System.out.println(data);
    splitArray = data.split(",");
    for (int j = 0; j < splitArray.length; j++) {
        doubleArray[j] = Double.parseDouble(splitArray[j]);
    }

    splitTarget = targets.replace("null", "").split(",");
    for (int j = 0; j < splitTarget.length; j++) {
        doubleTarget[j] = Double.parseDouble(splitTarget[j]);
    }
    System.out.println(doubleTarget[3]);
}

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

@RequestMapping(Hub.GET_WORLD_SERVICE)
public void getWorld(@PathVariable("session") String session, OutputStream outputStream) throws IOException {
    log.info(Hub.GET_WORLD_SERVICE + " " + session);
    DataOutputStream dos = new DataOutputStream(outputStream);
    PlayerSession playerSession = sessionMap.get(session);
    if (playerSession != null) {
        dos.writeUTF(Hub.SUCCESS);//from   ww  w  . j a  v a2s  .  c  o m
        dos.write(worldHistory.getFrozenWorld().getWorld());
        Iterator<PlayerSession> sessionWalk = sessionMap.values().iterator();
        while (sessionWalk.hasNext()) {
            if (sessionWalk.next().isExpired()) {
                sessionWalk.remove();
            }
        }
    } else {
        dos.writeUTF(Hub.FAILURE);
        dos.writeUTF(Failure.SESSION.toString());
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.commons.student.ViewStudentApplicationDA.java

public ActionForward downloadDocument(final ActionMapping mapping, final ActionForm form,
        final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    final IndividualCandidacyDocumentFile document = getDomainObject(request, "documentOID");
    if (document != null && isAuthorized(document)) {
        response.setContentType(document.getContentType());
        response.addHeader("Content-Disposition", "attachment; filename=\"" + document.getFilename() + "\"");
        response.setContentLength(document.getSize().intValue());
        final DataOutputStream dos = new DataOutputStream(response.getOutputStream());
        dos.write(document.getContent());
        dos.close();// w  w  w.j  a  v  a2s.  c  om
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_BAD_REQUEST));
        response.getWriter().close();
    }
    return null;
}

From source file:com.newatlanta.appengine.vfs.provider.GaeRandomAccessContent.java

GaeRandomAccessContent(GaeFileObject gfo, RandomAccessMode m, boolean append) throws IOException {
    EnumSet<StandardOpenOption> options = EnumSet.of(StandardOpenOption.READ);
    if (m == RandomAccessMode.READWRITE) {
        options.add(StandardOpenOption.WRITE);
        gfo.doSetLastModTime(System.currentTimeMillis());
    }/*from  ww  w  . ja v a 2s.c o m*/
    if (append) {
        options.add(StandardOpenOption.APPEND);
    }
    fileChannel = new GaeFileChannel(gfo, options);
    dataOutput = new DataOutputStream(Channels.newOutputStream(fileChannel));
    dataInput = new GaeDataInputStream(Channels.newInputStream(fileChannel));
}

From source file:com.googlecode.fascinator.portal.quartz.ExternalJob.java

/**
 * The real work happens here/*from w  w w.j av  a2  s  .c  om*/
 *
 */
private void runJob() {
    HttpURLConnection conn = null;
    log.debug("Job firing: '{}'", name);

    try {
        // Open tasks... much simpler
        if (token == null) {
            conn = (HttpURLConnection) url.openConnection();

            // Secure tasks
        } else {
            String param = "token=" + URLEncoder.encode(token, "UTF-8");

            // Prepare our request
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", "" + Integer.toString(param.getBytes().length));
            conn.setUseCaches(false);
            conn.setDoOutput(true);

            // Send request
            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(param);
            wr.flush();
            wr.close();
        }

        // Get Response
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            log.error("Error hitting external script: {}", conn.getResponseMessage());
        }
    } catch (IOException ex) {
        log.error("Error connecting to URL: ", ex);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}