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.kuali.ole.docstore.common.client.DocstoreRestClient.java

private RestResponse sendPostForAcquisitionSearch(String url, String urlParameters) {

    StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), 200, "OK");
    HttpResponse httpResponse = new BasicHttpResponse(statusLine);
    String postResponse = null;/* ww w.ja  v  a2  s .  c  o m*/
    try {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
        int responseCode = con.getResponseCode();
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        postResponse = response.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }

    RestResponse response = new RestResponse();
    response.setContentType("text/html; charset=utf-8");
    response.setResponseBody(postResponse);
    response.setResponse(httpResponse);
    return response;
}

From source file:org.openestate.is24.restapi.DefaultClient.java

@Override
protected Response sendXmlAttachmentRequest(URL url, RequestMethod method, String xml, InputStream input,
        String fileName, String mimeType) throws IOException, OAuthException {
    if (method == null)
        method = RequestMethod.POST;/*  ww w  .j ava  2 s.  co  m*/
    if (!RequestMethod.POST.equals(method) && !RequestMethod.PUT.equals(method))
        throw new IllegalArgumentException("Invalid request method!");
    xml = (RequestMethod.POST.equals(method) || RequestMethod.PUT.equals(method)) ? StringUtils.trimToNull(xml)
            : null;

    final String twoHyphens = "--";
    final String lineEnd = "\r\n";
    final String boundary = "*****" + RandomStringUtils.random(25, true, true) + "*****";

    HttpURLConnection connection = null;
    DataOutputStream output = null;
    try {
        // create connection
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(method.name());
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        connection.setRequestProperty("Content-Language", "en-US");
        connection.setRequestProperty("Accept", "application/xml");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        getAuthConsumer().sign(connection);

        output = (xml != null || input != null) ? new DataOutputStream(connection.getOutputStream()) : null;

        // send xml part
        if (xml != null && output != null) {
            output.writeBytes(twoHyphens + boundary + lineEnd);
            output.writeBytes("Content-Type: application/xml; name=body.xml" + lineEnd);
            output.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
            output.writeBytes(
                    "Content-Disposition: form-data; name=\"metadata\"; filename=\"body.xml\"" + lineEnd);
            output.writeBytes(lineEnd);
            output.writeBytes(xml);
            output.writeBytes(lineEnd);
            output.flush();
        }

        // send file part
        if (input != null && output != null) {
            mimeType = StringUtils.trimToNull(mimeType);
            if (mimeType != null)
                mimeType = "application/octet-stream";

            fileName = StringUtils.trimToNull(fileName);
            if (fileName == null)
                fileName = "upload.bin";

            output.writeBytes(twoHyphens + boundary + lineEnd);
            output.writeBytes("Content-Type: " + mimeType + "; name=\"" + fileName + "\"" + lineEnd);
            output.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
            output.writeBytes("Content-Disposition: form-data; name=\"attachment\"; filename=\"" + fileName
                    + "\"" + lineEnd);
            output.writeBytes(lineEnd);

            byte[] buffer = new byte[4096];
            int i = input.read(buffer, 0, buffer.length);
            while (i > 0) {
                output.write(buffer, 0, i);
                i = input.read(buffer, 0, buffer.length);
            }
            output.writeBytes(lineEnd);
        }

        if (output != null) {
            output.writeBytes(twoHyphens + boundary + lineEnd);
        }

        if (output != null)
            output.flush();
        connection.connect();

        // read response into string
        return createResponse(connection);
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.close(connection);
    }
}

From source file:com.maverick.ssl.https.HttpsURLConnection.java

void writeRequest(OutputStream out) throws IOException {
    DataOutputStream data = new DataOutputStream(new BufferedOutputStream(out));
    if ((doOutput) && (output == null)) {
        throw new IOException(Messages.getString("HttpsURLConnection.noPOSTData")); //$NON-NLS-1$
    }/*w  w  w  .  j a va2  s  . c o m*/
    if (ifModifiedSince != 0) {
        Date date = new Date(ifModifiedSince);
        SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy hh:mm:ss z"); //$NON-NLS-1$
        formatter.setTimeZone(TimeZone.getTimeZone("GMT")); //$NON-NLS-1$
        setRequestProperty("If-Modified-Since", formatter.format(date)); //$NON-NLS-1$
    }
    if (doOutput) {
        setRequestProperty("Content-length", "" + output.size()); //$NON-NLS-1$ //$NON-NLS-2$
    }

    data.writeBytes((doOutput ? "POST" : "GET") + " " + (url.getFile().equals("") ? "/" : url.getFile()) //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$//$NON-NLS-5$
            + " HTTP/1.0\r\n"); //$NON-NLS-1$

    for (int i = 0; i < requestKeys.size(); ++i) {
        String key = (String) requestKeys.elementAt(i);
        if (!key.startsWith("Proxy-")) { //$NON-NLS-1$
            data.writeBytes(key + ": " + requestValues.elementAt(i) + "\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }
    data.writeBytes("\r\n"); //$NON-NLS-1$
    data.flush();
    if (doOutput) {
        output.writeTo(out);
    }
    out.flush();
}

From source file:net.demilich.metastone.bahaviour.ModifiedMCTS.MCTSCritique.java

public void sendCaffeData(double[][] data2, double[][] labels2, double[][] weights, String name,
        boolean ordered, boolean file) {
    double[][] data = new double[data2.length][];
    double[][] labels = new double[data2.length][];
    if (!ordered) {
        for (int i = 0; i < data2.length; i++) {
            data[i] = data2[i].clone();/*from w  w  w  . j  av  a2 s. c o  m*/
            labels[i] = labels2[i].clone();
        }
    } else {
        data = data2;
        labels = labels2;
    }
    try {
        String sentence;
        String modifiedSentence;
        Random generator = new Random();
        //set up our socket server

        BufferedReader inFromServer = null;
        DataOutputStream outToServer = null;
        Socket clientSocket = null;

        //add in data in a random order
        if (!file) {
            System.err.println("starting to send on socket");
            clientSocket = new Socket("localhost", 5004);
            clientSocket.setTcpNoDelay(false);
            outToServer = new DataOutputStream(clientSocket.getOutputStream());
            inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            outToServer.writeBytes(name + "\n");

            outToServer.writeBytes((data.length + " " + data[0].length + " " + labels[0].length) + "\n");
            try {
                Thread.sleep(10000);
            } catch (Exception e) {
            }
        } else {
            outToServer = new DataOutputStream((OutputStream) new FileOutputStream(name));
        }
        StringBuffer wholeMessage = new StringBuffer();
        for (int i = 0; i < data.length; i++) {
            if (i % 1000 == 0) {
                System.err.println("(constructed) i is " + i);
            }
            String features = "";
            int randomIndex = generator.nextInt(data.length - i);

            if (!ordered) {
                swap(data, i, i + randomIndex);
                swap(labels, i, i + randomIndex);
            }
            for (int a = 0; a < data[i].length; a++) {
                wholeMessage.append(data[i][a] + " ");
            }
            wholeMessage.append("\n");
            String myLabels = "";
            for (int a = 0; a < labels[i].length; a++) {
                wholeMessage.append(labels[i][a] + " ");
            }
            wholeMessage.append("\n");
            wholeMessage.append(weights[i][0] + "");
            wholeMessage.append("\n");
            outToServer.writeBytes(wholeMessage.toString());
            wholeMessage = new StringBuffer();

        }
        System.err.println("total message size is " + wholeMessage.toString().length());

        //outToServer.writeBytes(wholeMessage.toString());
        if (!file) {
            System.err.println("sending done");
            outToServer.writeBytes("done\n");
            System.err.println("waiting for ack...");
            inFromServer.readLine();
            System.err.println("got the ack!");
            clientSocket.close();
        }

    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("server wasn't waiting");
    }
    System.err.println("hey i sent somethin!");

}

From source file:csic.ceab.movelab.beepath.Util.java

public static boolean uploadFile(byte[] bytes, String filename, String uploadurl) {

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    // DataInputStream inStream = null;

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 64 * 1024; // old value 1024*1024
    ByteArrayInputStream byteArrayInputStream = null;
    boolean isSuccess = true;
    try {//from   w w  w  . j a  va 2  s.c  o  m
        // ------------------ CLIENT REQUEST

        byteArrayInputStream = new ByteArrayInputStream(bytes);

        // open a URL connection to the Servlet
        URL url = new URL(uploadurl);
        // Open a HTTP connection to the URL
        conn = (HttpURLConnection) url.openConnection();
        // Allow Inputs
        conn.setDoInput(true);
        // Allow Outputs
        conn.setDoOutput(true);
        // Don't use a cached copy.
        conn.setUseCaches(false);
        // set timeout
        conn.setConnectTimeout(60000);
        conn.setReadTimeout(60000);
        // Use a post method.
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

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

        // create a buffer of maximum size
        bytesAvailable = byteArrayInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = byteArrayInputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = byteArrayInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = byteArrayInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // close streams
        // Log.e(TAG,"UploadService Runnable:File is written");
        // fileInputStream.close();
        // dos.flush();
        // dos.close();
    } catch (Exception e) {
        // Log.e(TAG, "UploadService Runnable:Client Request error", e);
        isSuccess = false;
    } finally {
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
                // Log.e(TAG, "exception" + e);

            }
        }
        if (byteArrayInputStream != null) {
            try {
                byteArrayInputStream.close();
            } catch (IOException e) {
                // Log.e(TAG, "exception" + e);

            }
        }

    }

    // ------------------ read the SERVER RESPONSE
    try {

        if (conn.getResponseCode() != 200) {
            isSuccess = false;
        }
    } catch (IOException e) {
        // Log.e(TAG, "Connection error", e);
        isSuccess = false;
    }

    return isSuccess;
}

From source file:ca.farrelltonsolar.classic.PVOutputUploader.java

private boolean doUpload(ChargeController controller) throws InterruptedException, IOException {
    String uploadDateString = controller.uploadDate();
    String SID = controller.getSID();
    String fName = controller.getPVOutputLogFilename();
    if (fName != null && fName.length() > 0 && SID != null && SID.length() > 0) {
        DateTime logDate = PVOutputService.LogDate();
        int numberOfDays = Constants.PVOUTPUT_RECORD_LIMIT;
        if (uploadDateString.length() > 0) {
            DateTime uploadDate = DateTime.parse(uploadDateString, DateTimeFormat.forPattern("yyyy-MM-dd"));
            numberOfDays = Days.daysBetween(uploadDate, logDate).getDays();
        }// w  ww  . jav  a 2s  . com
        numberOfDays = numberOfDays > Constants.PVOUTPUT_RECORD_LIMIT ? Constants.PVOUTPUT_RECORD_LIMIT
                : numberOfDays; // limit to 20 days as per pvOutput limits
        if (numberOfDays > 0) {
            Log.d(getClass().getName(), String.format("PVOutput uploading: %s for %d days on thread: %s", fName,
                    numberOfDays, Thread.currentThread().getName()));
            DateTime now = DateTime.now();
            String UploadDate = DateTimeFormat.forPattern("yyyy-MM-dd").print(now);
            Bundle logs = load(fName);
            float[] mData = logs.getFloatArray(String.valueOf(Constants.CLASSIC_KWHOUR_DAILY_CATEGORY)); // kWh/day
            boolean uploadDateRecorded = false;
            for (int i = 0; i < numberOfDays; i++) {
                logDate = logDate.minusDays(1); // latest log entry is for yesterday
                Socket pvOutputSocket = Connect(pvOutput);
                DataOutputStream outputStream = new DataOutputStream(
                        new BufferedOutputStream(pvOutputSocket.getOutputStream()));
                String dateStamp = DateTimeFormat.forPattern("yyyyMMdd").print(logDate);
                StringBuilder feed = new StringBuilder("GET /service/r2/addoutput.jsp");
                feed.append("?key=");
                feed.append(APIKey);
                feed.append("&sid=");
                feed.append(SID);
                feed.append("&d=");
                feed.append(dateStamp);
                feed.append("&g=");
                String wh = String.valueOf(mData[i] * 100);
                feed.append(wh);
                feed.append("\r\n");
                feed.append("Host: ");
                feed.append(pvOutput);
                feed.append("\r\n");
                feed.append("\r\n");
                String resp = feed.toString();
                outputStream.writeBytes(resp);
                outputStream.flush();
                pvOutputSocket.close();
                if (uploadDateRecorded == false) {
                    controller.setUploadDate(UploadDate);
                    uploadDateRecorded = true;
                }
                Thread.sleep(Constants.PVOUTPUT_RATE_LIMIT); // rate limit
            }
            return true;
        }
    }
    return false;
}

From source file:org.lyricue.android.LyricueDisplay.java

public String runCommand(Integer hostnum, String command, String option1, String option2) {
    String result = "";
    if ((hosts == null) || (hosts.length == 0) || (hosts[hostnum] == null)
            || (hosts[hostnum].hostname.equals("#demo"))) {
        return result;
    }//from   w w w  .j  a  v  a2  s.co m
    Socket sc = null;
    DataOutputStream os = null;
    HostItem host = hosts[hostnum];
    try {
        sc = new Socket(host.hostname, host.port);
    } catch (UnknownHostException e) {
        logError("Don't know about host: " + host.hostname);
    } catch (IOException e) {
        logError("Couldn't get I/O socket for the connection to: " + host.hostname);
    }
    if (sc != null) {
        try {
            os = new DataOutputStream(sc.getOutputStream());
        } catch (UnknownHostException e) {
            logError("Don't know about host: " + host.hostname);
        } catch (IOException e) {
            logError("Couldn't get I/O output for the connection to: " + host.hostname);
        }
    }
    if (sc != null && os != null) {
        try {
            option1 = option1.replace("\n", "#BREAK#").replace(":", "#SEMI#");
            option2 = option2.replace("\n", "#BREAK#").replace(":", "#SEMI#");
            os.writeBytes(command + ":" + option1 + ":" + option2 + "\n");
            os.flush();
            InputStream is = sc.getInputStream();
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 128);
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            is.close();
            result = sb.toString();
            try {
                os.close();
                sc.close();
            } catch (IOException ignored) {
            }
        } catch (UnknownHostException e) {
            logError("Trying to connect to unknown host: " + e);
        } catch (IOException e) {
            logError("IOException:  " + e);
        }
    } else {
        if (sc != null) {
            try {
                sc.close();
            } catch (IOException e) {
                logError("IOException:  " + e);
            }
        }
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                logError("IOException:  " + e);
            }
        }
    }
    return result;
}

From source file:org.wso2.carbon.identity.authenticator.mobileconnect.MobileConnectAuthenticator.java

/**
 * msisdn based Discovery (Developer app uses Discovery API to send msisdn).
 *///from  ww w  .  j a  v  a 2s.  c om
private HttpURLConnection discoveryProcess(String authorizationHeader, String msisdn,
        Map<String, String> authenticationProperties) throws IOException {

    //prepare query parameters
    String queryParameters = MobileConnectAuthenticatorConstants.MOBILE_CONNECT_DISCOVERY_REDIRECT_URL + "="
            + getCallbackUrl(authenticationProperties);

    //create url to make the API call
    String url = MobileConnectAuthenticatorConstants.DISCOVERY_API_URL + "?" + queryParameters;

    //body parameters for the API call
    String data = "MSISDN=" + msisdn;

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

    connection.setRequestMethod(MobileConnectAuthenticatorConstants.POST_METHOD);
    connection.setRequestProperty(MobileConnectAuthenticatorConstants.MOBILE_CONNECT_DISCOVERY_AUTHORIZATION,
            authorizationHeader);
    connection.setRequestProperty(MobileConnectAuthenticatorConstants.MOBILE_CONNECT_DISCOVERY_ACCEPT,
            MobileConnectAuthenticatorConstants.MOBILE_CONNECT_DISCOVERY_ACCEPT_VALUE);
    connection.setDoOutput(true);

    //write data to the body of the connection
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.writeBytes(data);
    outputStream.close();

    return connection;
}

From source file:br.org.indt.ndg.servlets.PostSurveys.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    InputStreamReader dis = new InputStreamReader(request.getInputStream(), "UTF-8");
    DataOutputStream dos = new DataOutputStream(response.getOutputStream());

    if (dis != null) {
        BufferedReader reader = new BufferedReader(dis);
        StringBuffer tempBuffer = new StringBuffer();
        String line = null;/*from  ww  w . j  ava 2s. c o  m*/

        if (validateUser(request.getParameter("user"), request.getParameter("psw"))) {
            while ((line = reader.readLine()) != null) {
                tempBuffer.append(line + '\n');
            }

            try {
                msmBD.postSurvey(request.getParameter("user"), tempBuffer, createTransactionLogVO(request),
                        false);
                dos.writeBytes(SUCCESS);
            } catch (MSMApplicationException e) {
                dos.writeBytes(FAILURE);
                e.printStackTrace();
            } catch (MSMSystemException e) {
                dos.writeBytes(FAILURE);
                e.printStackTrace();
            }
        } else {
            dos.writeBytes(USERINVALID);
        }

        reader.close();
        dos.close();
    } else {
        dos.writeBytes(FAILURE);
        log.info("Failed processing stream from " + request.getRemoteAddr());
    }
}

From source file:org.openestate.is24.restapi.DefaultClient.java

@Override
protected Response sendXmlRequest(URL url, RequestMethod method, String xml)
        throws IOException, OAuthException {
    if (method == null)
        method = RequestMethod.GET;//w w w  .j  a va 2s .c  om
    xml = (RequestMethod.POST.equals(method) || RequestMethod.PUT.equals(method)) ? StringUtils.trimToNull(xml)
            : null;

    HttpURLConnection connection = null;
    DataOutputStream output = null;
    try {
        // create connection
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(method.name());
        if (xml != null) {
            connection.setRequestProperty("Content-Type",
                    "application/xml; charset=" + getEncoding().toLowerCase());
            connection.setRequestProperty("Content-Length", String.valueOf(xml.getBytes(getEncoding()).length));
            connection.setRequestProperty("Content-Language", "en-US");
        }
        connection.setRequestProperty("Accept", "application/xml");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        getAuthConsumer().sign(connection);

        // send request
        if (xml != null) {
            output = new DataOutputStream(connection.getOutputStream());
            output.writeBytes(xml);
            output.flush();
        }
        connection.connect();

        // read response into string
        return createResponse(connection);
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.close(connection);
    }
}