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.ramadda.repository.database.DatabaseManager.java

/**
 * _more_/*from   w  w  w  . ja v  a  2  s .  co m*/
 *
 * @param dos _more_
 * @param s _more_
 *
 * @throws Exception _more_
 */
private void writeString(DataOutputStream dos, String s) throws Exception {
    if (s == null) {
        dos.writeInt(-1);
    } else {
        dos.writeInt(s.length());
        dos.writeBytes(s);
    }
}

From source file:com.benefit.buy.library.http.query.callback.AbstractAjaxCallback.java

private void httpMulti(String url, Map<String, String> headers, Map<String, Object> params, AjaxStatus status)
        throws IOException {
    AQUtility.debug("multipart", url);
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    URL u = new URL(url);
    conn = (HttpURLConnection) u.openConnection();
    conn.setInstanceFollowRedirects(false);
    conn.setConnectTimeout(NET_TIMEOUT * 4);
    conn.setDoInput(true);/*from   w w  w. j av a  2 s  .  c  o m*/
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data;charset=utf-8;boundary=" + boundary);
    if (headers != null) {
        for (String name : headers.keySet()) {
            conn.setRequestProperty(name, headers.get(name));
        }
    }
    String cookie = makeCookie();
    if (cookie != null) {
        conn.setRequestProperty("Cookie", cookie);
    }
    if (ah != null) {
        ah.applyToken(this, conn);
    }
    dos = new DataOutputStream(conn.getOutputStream());
    Object o = null;
    if (progress != null) {
        o = progress.get();
    }
    Progress p = null;
    if (o != null) {
        p = new Progress(o);
    }
    for (Map.Entry<String, Object> entry : params.entrySet()) {
        writeObject(dos, entry.getKey(), entry.getValue(), p);
    }
    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    dos.flush();
    dos.close();
    conn.connect();
    int code = conn.getResponseCode();
    String message = conn.getResponseMessage();
    byte[] data = null;
    String encoding = conn.getContentEncoding();
    String error = null;
    if ((code < 200) || (code >= 300)) {
        error = new String(toData(encoding, conn.getErrorStream()), "UTF-8");
        AQUtility.debug("error", error);
    } else {
        data = toData(encoding, conn.getInputStream());
    }
    AQUtility.debug("response", code);
    if (data != null) {
        AQUtility.debug(data.length, url);
    }
    status.code(code).message(message).redirect(url).time(new Date()).data(data).error(error).client(null);
}

From source file:com.adobe.aem.demomachine.communities.Loader.java

private static void postAnalytics(String analytics, String body) {

    if (analytics != null && body != null) {

        URLConnection urlConn = null;
        DataOutputStream printout = null;
        BufferedReader input = null;
        String tmp = null;//  w w  w .j a  v a2s .c  o m
        try {

            logger.debug("New Analytics Event: " + body);

            URL sitecaturl = new URL("http://" + analytics);

            urlConn = sitecaturl.openConnection();
            urlConn.setDoInput(true);
            urlConn.setDoOutput(true);
            urlConn.setUseCaches(false);
            urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            printout = new DataOutputStream(urlConn.getOutputStream());

            printout.writeBytes(body);
            printout.flush();
            printout.close();

            input = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

            while (null != ((tmp = input.readLine()))) {
                logger.debug(tmp);
            }
            printout.close();
            input.close();

        } catch (Exception ex) {

            logger.warn("Connectivity error: " + ex.getMessage());

        } finally {

            try {
                input.close();
                printout.close();
            } catch (Exception e) {
                // Omitted
            }

        }

    }

}

From source file:com.appbase.androidquery.callback.AbstractAjaxCallback.java

private void httpMulti(String url, Map<String, String> headers, Map<String, Object> params, AjaxStatus status)
        throws IOException {

    AQUtility.debug("multipart", url);

    HttpURLConnection conn = null;
    DataOutputStream dos = null;

    URL u = new URL(url);
    conn = (HttpURLConnection) u.openConnection();

    conn.setInstanceFollowRedirects(false);

    conn.setConnectTimeout(NET_TIMEOUT * 4);

    conn.setDoInput(true);//w ww .  j  a  v  a 2  s . co  m
    conn.setDoOutput(true);
    conn.setUseCaches(false);

    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data;charset=utf-8;boundary=" + boundary);

    if (headers != null) {
        for (String name : headers.keySet()) {
            conn.setRequestProperty(name, headers.get(name));
        }
    }

    String cookie = makeCookie();
    if (cookie != null) {
        conn.setRequestProperty("Cookie", cookie);
    }

    if (ah != null) {
        ah.applyToken(this, conn);
    }

    dos = new DataOutputStream(conn.getOutputStream());

    for (Map.Entry<String, Object> entry : params.entrySet()) {

        writeObject(dos, entry.getKey(), entry.getValue());

    }

    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    dos.flush();
    dos.close();

    conn.connect();

    int code = conn.getResponseCode();
    String message = conn.getResponseMessage();

    byte[] data = null;

    String encoding = conn.getContentEncoding();
    String error = null;

    if (code < 200 || code >= 300) {

        error = new String(toData(encoding, conn.getErrorStream()), "UTF-8");

        AQUtility.debug("error", error);
    } else {

        data = toData(encoding, conn.getInputStream());
    }

    AQUtility.debug("response", code);

    if (data != null) {
        AQUtility.debug(data.length, url);
    }

    status.code(code).message(message).redirect(url).time(new Date()).data(data).error(error).client(null);

}

From source file:com.curso.listadapter.net.RESTClient.java

/**
 * upload multipart//from w w  w.  ja va2 s .  c om
 * this method receive the file to be uploaded
 * */
@SuppressWarnings("deprecation")
public String uploadMultiPart(Map<String, File> files) throws Exception {
    disableSSLCertificateChecking();
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    DataInputStream inStream = null;
    try {
        URL endpoint = new URL(url);
        conn = (HttpURLConnection) endpoint.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

        dos = new DataOutputStream(conn.getOutputStream());
        String post = "";

        //WRITE ALL THE PARAMS
        for (NameValuePair p : params)
            post += writeMultipartParam(p);
        dos.flush();
        //END WRITE ALL THE PARAMS

        //BEGIN THE UPLOAD
        ArrayList<FileInputStream> inputStreams = new ArrayList<FileInputStream>();
        for (Entry<String, File> entry : files.entrySet()) {
            post += lineEnd;
            post += twoHyphens + boundary + lineEnd;
            String NameParamImage = entry.getKey();
            File file = entry.getValue();
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;
            FileInputStream fileInputStream = new FileInputStream(file);

            post += "Content-Disposition: attachment; name=\"" + NameParamImage + "\"; filename=\""
                    + file.getName() + "\"" + lineEnd;
            String mimetype = getMimeType(file.getName());
            post += "Content-Type: " + mimetype + lineEnd;
            post += "Content-Transfer-Encoding: binary" + lineEnd + lineEnd;

            dos.write(post.toString().getBytes("UTF-8"));

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                inputStreams.add(fileInputStream);
            }

            Log.d("Test", post);
            dos.flush();
            post = "";
        }

        //END THE UPLOAD

        dos.writeBytes(lineEnd);

        dos.writeBytes(twoHyphens + boundary + twoHyphens);
        //            for(FileInputStream inputStream: inputStreams){
        //               inputStream.close();
        //            }
        dos.flush();
        dos.close();
        conn.connect();
        Log.d("upload", "finish flush:" + conn.getResponseCode());
    } catch (MalformedURLException ex) {
        Log.e("Debug", "error: " + ex.getMessage(), ex);
    } catch (IOException ioe) {
        Log.e("Debug", "error: " + ioe.getMessage(), ioe);
    }
    try {
        String response_data = "";
        inStream = new DataInputStream(conn.getInputStream());
        String str;
        while ((str = inStream.readLine()) != null) {
            response_data += str;
        }
        inStream.close();
        return response_data;
    } catch (IOException ioex) {
        Log.e("Debug", "error: " + ioex.getMessage(), ioex);
    }
    return null;
}

From source file:com.gotraveling.external.androidquery.callback.AbstractAjaxCallback.java

private void httpMulti(String url, Map<String, String> headers, Map<String, Object> params, AjaxStatus status)
        throws IOException {

    AQUtility.debug("multipart", url);

    HttpURLConnection conn = null;
    DataOutputStream dos = null;

    URL u = new URL(url);
    conn = (HttpURLConnection) u.openConnection();

    conn.setInstanceFollowRedirects(false);

    conn.setConnectTimeout(NET_TIMEOUT * 4);

    conn.setDoInput(true);/* w  ww .  j  a v a2  s .co  m*/
    conn.setDoOutput(true);
    conn.setUseCaches(false);

    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data;charset=utf-8;boundary=" + boundary);

    if (headers != null) {
        for (String name : headers.keySet()) {
            conn.setRequestProperty(name, headers.get(name));
        }
    }

    String cookie = makeCookie();
    if (cookie != null) {
        conn.setRequestProperty("Cookie", cookie);
    }

    if (ah != null) {
        ah.applyToken(this, conn);
    }

    dos = new DataOutputStream(conn.getOutputStream());

    Object o = null;

    if (progress != null) {
        o = progress.get();
    }

    Progress p = null;

    if (o != null) {
        p = new Progress(o);
    }

    for (Map.Entry<String, Object> entry : params.entrySet()) {

        writeObject(dos, entry.getKey(), entry.getValue(), p);

    }

    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    dos.flush();
    dos.close();

    conn.connect();

    int code = conn.getResponseCode();
    String message = conn.getResponseMessage();

    byte[] data = null;

    String encoding = conn.getContentEncoding();
    String error = null;

    if (code < 200 || code >= 300) {

        error = new String(toData(encoding, conn.getErrorStream()), "UTF-8");

        AQUtility.debug("error", error);
    } else {

        data = toData(encoding, conn.getInputStream());
    }

    AQUtility.debug("response", code);

    if (data != null) {
        AQUtility.debug(data.length, url);
    }

    status.code(code).message(message).redirect(url).time(new Date()).data(data).error(error).client(null);

}

From source file:edu.vu.isis.ammo.dash.provider.IncidentSyncAdaptor.java

public ArrayList<File> eventSerialize(Cursor cursor) {
    logger.debug("::eventSerialize");
    ArrayList<File> paths = new ArrayList<File>();
    if (1 > cursor.getCount())
        return paths;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream eos = new DataOutputStream(baos);

    for (boolean more = cursor.moveToFirst(); more; more = cursor.moveToNext()) {
        EventWrapper iw = new EventWrapper();
        iw.setUuid(cursor.getString(cursor.getColumnIndex(EventTableSchemaBase.UUID)));
        iw.setMediaCount(cursor.getInt(cursor.getColumnIndex(EventTableSchemaBase.MEDIA_COUNT)));
        iw.setOriginator(cursor.getString(cursor.getColumnIndex(EventTableSchemaBase.ORIGINATOR)));
        iw.setDisplayName(cursor.getString(cursor.getColumnIndex(EventTableSchemaBase.DISPLAY_NAME)));
        iw.setCategoryId(cursor.getString(cursor.getColumnIndex(EventTableSchemaBase.CATEGORY_ID)));
        iw.setTitle(cursor.getString(cursor.getColumnIndex(EventTableSchemaBase.TITLE)));
        iw.setDescription(cursor.getString(cursor.getColumnIndex(EventTableSchemaBase.DESCRIPTION)));
        iw.setLongitude(//  w  w w .  ja v a 2  s  .co  m
                Util.scaleIntCoordinate(cursor.getInt(cursor.getColumnIndex(EventTableSchemaBase.LONGITUDE))));
        iw.setLatitude(
                Util.scaleIntCoordinate(cursor.getInt(cursor.getColumnIndex(EventTableSchemaBase.LATITUDE))));
        iw.setCreatedDate(cursor.getLong(cursor.getColumnIndex(EventTableSchemaBase.CREATED_DATE)));
        iw.setModifiedDate(cursor.getLong(cursor.getColumnIndex(EventTableSchemaBase.MODIFIED_DATE)));
        iw.setCid(cursor.getString(cursor.getColumnIndex(EventTableSchemaBase.CID)));
        iw.setCategory(cursor.getString(cursor.getColumnIndex(EventTableSchemaBase.CATEGORY)));
        iw.setUnit(cursor.getString(cursor.getColumnIndex(EventTableSchemaBase.UNIT)));
        iw.setSize(cursor.getLong(cursor.getColumnIndex(EventTableSchemaBase.SIZE)));
        iw.setDestGroupType(cursor.getString(cursor.getColumnIndex(EventTableSchemaBase.DEST_GROUP_TYPE)));
        iw.setDestGroupName(cursor.getString(cursor.getColumnIndex(EventTableSchemaBase.DEST_GROUP_NAME)));
        iw.setStatus(cursor.getInt(cursor.getColumnIndex(EventTableSchemaBase.STATUS)));
        iw.set_ReceivedDate(cursor.getLong(cursor.getColumnIndex(EventTableSchemaBase._RECEIVED_DATE)));
        iw.set_Disposition(cursor.getInt(cursor.getColumnIndex(EventTableSchemaBase._DISPOSITION)));

        Gson gson = new Gson();

        try {
            eos.writeBytes(gson.toJson(iw));
            eos.writeByte(0);
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        // not a reference field name :uuid uuid uuid\n 
        // not a reference field name :media count mediaCount media_count\n 
        // not a reference field name :originator originator originator\n 
        // not a reference field name :display name displayName display_name\n 
        // not a reference field name :category id categoryId category_id\n 
        // not a reference field name :title title title\n 
        // not a reference field name :description description description\n 
        // not a reference field name :longitude longitude longitude\n 
        // not a reference field name :latitude latitude latitude\n 
        // not a reference field name :created date createdDate created_date\n 
        // not a reference field name :modified date modifiedDate modified_date\n 
        // not a reference field name :cid cid cid\n 
        // not a reference field name :category category category\n 
        // not a reference field name :unit unit unit\n 
        // not a reference field name :size size size\n 
        // not a reference field name :dest group type destGroupType dest_group_type\n 
        // not a reference field name :dest group name destGroupName dest_group_name\n 
        // not a reference field name :STATUS status status\n 
        // EventTableSchemaBase._DISPOSITION;

        //           try {
        // TODO write to content provider using openFile
        // if (!applCacheEventDir.exists() ) applCacheEventDir.mkdirs();

        // File outfile = new File(applCacheEventDir, Integer.toHexString((int) System.currentTimeMillis())); 
        //              BufferedOutputStream bufferedOutput = 
        //                    new BufferedOutputStream(new FileOutputStream(outfile), 8192);
        //              bufferedOutput.write(baos.toByteArray());
        //              bufferedOutput.flush();
        //              bufferedOutput.close();

        // paths.add(outfile);
        //           } catch (FileNotFoundException e) {
        //              e.printStackTrace();
        //           } catch (IOException e) {
        //              e.printStackTrace();
        //           }
    }
    return paths;
}

From source file:org.apache.hadoop.hive.ql.exec.DDLTask.java

public static void dumpLockInfo(DataOutputStream os, ShowLocksResponse rsp) throws IOException {
    // Write a header
    os.writeBytes("Lock ID");
    os.write(separator);//from   w  w  w  .  j a va2 s . c o  m
    os.writeBytes("Database");
    os.write(separator);
    os.writeBytes("Table");
    os.write(separator);
    os.writeBytes("Partition");
    os.write(separator);
    os.writeBytes("State");
    os.write(separator);
    os.writeBytes("Blocked By");
    os.write(separator);
    os.writeBytes("Type");
    os.write(separator);
    os.writeBytes("Transaction ID");
    os.write(separator);
    os.writeBytes("Last Heartbeat");
    os.write(separator);
    os.writeBytes("Acquired At");
    os.write(separator);
    os.writeBytes("User");
    os.write(separator);
    os.writeBytes("Hostname");
    os.write(separator);
    os.writeBytes("Agent Info");
    os.write(terminator);

    List<ShowLocksResponseElement> locks = rsp.getLocks();
    if (locks != null) {
        for (ShowLocksResponseElement lock : locks) {
            if (lock.isSetLockIdInternal()) {
                os.writeBytes(Long.toString(lock.getLockid()) + "." + Long.toString(lock.getLockIdInternal()));
            } else {
                os.writeBytes(Long.toString(lock.getLockid()));
            }
            os.write(separator);
            os.writeBytes(lock.getDbname());
            os.write(separator);
            os.writeBytes((lock.getTablename() == null) ? "NULL" : lock.getTablename());
            os.write(separator);
            os.writeBytes((lock.getPartname() == null) ? "NULL" : lock.getPartname());
            os.write(separator);
            os.writeBytes(lock.getState().toString());
            os.write(separator);
            if (lock.isSetBlockedByExtId()) {//both "blockedby" are either there or not
                os.writeBytes(Long.toString(lock.getBlockedByExtId()) + "."
                        + Long.toString(lock.getBlockedByIntId()));
            } else {
                os.writeBytes("            ");//12 chars - try to keep cols aligned
            }
            os.write(separator);
            os.writeBytes(lock.getType().toString());
            os.write(separator);
            os.writeBytes((lock.getTxnid() == 0) ? "NULL" : Long.toString(lock.getTxnid()));
            os.write(separator);
            os.writeBytes(Long.toString(lock.getLastheartbeat()));
            os.write(separator);
            os.writeBytes((lock.getAcquiredat() == 0) ? "NULL" : Long.toString(lock.getAcquiredat()));
            os.write(separator);
            os.writeBytes(lock.getUser());
            os.write(separator);
            os.writeBytes(lock.getHostname());
            os.write(separator);
            os.writeBytes(lock.getAgentInfo() == null ? "NULL" : lock.getAgentInfo());
            os.write(separator);
            os.write(terminator);
        }
    }
}

From source file:com.acc.android.network.operator.base.BaseHttpOperator.java

private static void addUploadDataContent(List<UploadFile> uploadFiles, DataOutputStream dataOutputStream
// , String tagString
) {// ww w .j a  v a  2 s. c om
    if (uploadFiles == null || uploadFiles.size() == 0) {
        return;
    }
    for (UploadFile uploadFile : uploadFiles) {
        // StringBuilder fileEntity = new StringBuilder();
        // fileEntity.append("--");
        // fileEntity.append(BOUNDARY);
        // fileEntity.append("\r\n");
        // fileEntity.append("Content-Disposition: form-data;name=\""
        // + uploadFile.getParameterName() + "\";filename=\""
        // + uploadFile.getFilname() + "\"\r\n");
        // fileEntity.append("Content-Type: " + uploadFile.getContentType()
        // + "\r\n\r\n");
        // outStream.write(fileEntity.toString().getBytes());

        // sb.append(UploadConstant.TWOHYPHENS + UploadConstant.BOUNDARY
        // + UploadConstant.LINEEND);
        // sb.append("Content-Disposition: form-data; name=\""
        // + param.getKey() + "\"" + UploadConstant.LINEEND);
        // sb.append(UploadConstant.LINEEND);
        // sb.append(param.getValue() + UploadConstant.LINEEND);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(UploadConstant.TWOHYPHENS + UploadConstant.BOUNDARY + UploadConstant.LINEEND);
        stringBuilder.append("Content-Disposition: form-data;")
                // + tagString
                .append("name=\"" + uploadFile.getName() + "\";")
                // + tagString
                .append("filename=\"" + FileUtil.getFileRealName(uploadFile.getFilePath())
                // uploadFile.getFilePath()
                // .substring(
                // uploadFile.getFilePath()
                // .lastIndexOf("/") + 1,
                // uploadFile.getFilePath().length())
                        + "\";")
                .append(UploadConstant.LINEEND).append("Content-Type:\"" + uploadFile.getContentType() + "\"")
                .append(UploadConstant.LINEEND).append(UploadConstant.LINEEND);
        // + tagString
        // + "ContentType=\""
        // + uploadFile.getFilePath().substring(
        // uploadFile.getFilePath().lastIndexOf(".") + 1,
        // uploadFile.getFilePath().length()) + "\";"
        // + UploadConstant.LINEEND)
        // // + tagString
        // // + "Content-Type:\""
        // // + uploadFile.getFilePath().substring(
        // // uploadFile.getFilePath().lastIndexOf(".") + 1,
        // // uploadFile.getFilePath().length()) + "\";"
        // + "Content-Type:\"image/jpg\"" + UploadConstant.LINEEND);
        // stringBuilder.append(UploadConstant.LINEEND);
        // stringBuilder.append(UploadConstant.LINEEND).append(
        // UploadConstant.LINEEND);
        // LogUtil.systemOut(stringBuilder.toString());
        FileInputStream fileInputStream = null;
        try {
            dataOutputStream.writeBytes(stringBuilder.toString());
            fileInputStream = new FileInputStream(uploadFile.getFilePath());
            // fileInputStream.available();
            // ??
            byte[] buffer = new byte[102400]; // 8k
            int count = 0;
            while ((count = fileInputStream.read(buffer)) != -1) {
                // LogUtil.systemOut("count:" + count);
                dataOutputStream.write(buffer, 0, count);
            }
            dataOutputStream.writeBytes(UploadConstant.LINEEND);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}