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:dj.comprobantes.offline.service.CPanelServiceImp.java

@Override
public boolean guardarComprobanteNube(Comprobante comprobante) throws GenericException {
    boolean guardo = true;
    UtilitarioCeo utilitario = new UtilitarioCeo();
    Map<String, Object> params = new LinkedHashMap<>();
    params.put("NOMBRE_USUARIO", comprobante.getCliente().getNombreCliente());
    params.put("IDENTIFICACION_USUARIO", comprobante.getCliente().getIdentificacion());
    params.put("CORREO_USUARIO", comprobante.getCliente().getCorreo());
    params.put("CODIGO_ESTADO", EstadoUsuarioEnum.NUEVO.getCodigo());
    params.put("DIRECCION_USUARIO", comprobante.getCliente().getDireccion());
    params.put("PK_CODIGO_COMP", comprobante.getCodigocomprobante());
    params.put("CODIGO_DOCUMENTO", comprobante.getCoddoc());
    params.put("ESTADO", EstadoComprobanteEnum.AUTORIZADO.getDescripcion());
    params.put("CLAVE_ACCESO", comprobante.getClaveacceso());
    params.put("SECUENCIAL", comprobante.getSecuencial());
    params.put("FECHA_EMISION", utilitario.getFormatoFecha(comprobante.getFechaemision()));
    params.put("NUM_AUTORIZACION", comprobante.getNumAutorizacion());
    params.put("FECHA_AUTORIZACION", utilitario.getFormatoFecha(comprobante.getFechaautoriza()));
    params.put("ESTABLECIM", comprobante.getEstab());
    params.put("PTO_EMISION", comprobante.getPtoemi());
    params.put("TOTAL", comprobante.getImportetotal());
    params.put("CODIGO_EMPR", ParametrosSistemaEnum.CODIGO_EMPR.getCodigo());
    params.put("CORREO_DOCUMENTO", comprobante.getCorreo()); //Para guardar el correo que se envio el comprobante
    byte[] bxml = archivoService.getXml(comprobante);
    StringBuilder postData = new StringBuilder();
    postData.append("{");
    for (Map.Entry<String, Object> param : params.entrySet()) {
        if (postData.length() != 1) {
            postData.append(',');
        }/*from  ww w .  j a va  2  s  . c  om*/
        postData.append("\"").append(param.getKey()).append("\"");
        postData.append(":\"");
        postData.append(String.valueOf(param.getValue())).append("\"");
    }
    String encodedfileXML = new String(Base64.encodeBase64(bxml));
    params.put("ARCHIVO_XML", encodedfileXML);

    //guarda en la nuebe el comprobante AUTORIZADO
    String filefield = "pdf";
    String fileMimeType = "application/pdf";
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    InputStream inputStream = null;
    String twoHyphens = "--";
    String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
    String lineEnd = "\r\n";
    String result = "";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    String fileName = comprobante.getClaveacceso() + ".pdf";
    try {
        byte[] bpdf = archivoService.getPdf(comprobante);
        File file = File.createTempFile(comprobante.getClaveacceso(), ".tmp");
        file.deleteOnExit();
        try (FileOutputStream outputStream1 = new FileOutputStream(file);) {
            outputStream1.write(bpdf); //write the bytes and your done. 
            outputStream1.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        FileInputStream fileInputStream = new FileInputStream(file);
        URL url = new URL(ParametrosSistemaEnum.CPANEL_WEB_COMPROBANTE.getCodigo());
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        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=\"" + filefield + "\"; filename=\""
                + fileName + "\"" + lineEnd);
        outputStream.writeBytes("Content-Type: " + fileMimeType + lineEnd);
        outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
        outputStream.writeBytes(lineEnd);

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

        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);
        // Upload POST Data
        Iterator<String> keys = params.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next();
            String value = String.valueOf(params.get(key));
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
            outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(value);
            outputStream.writeBytes(lineEnd);
        }
        outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        if (200 != connection.getResponseCode()) {
            throw new Exception("Failed to upload code:" + connection.getResponseCode() + " "
                    + connection.getResponseMessage());
        }

        inputStream = connection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader((inputStream)));

        String output;
        while ((output = br.readLine()) != null) {
            result += output;
        }
        System.out.println(result);
        fileInputStream.close();
        inputStream.close();
        outputStream.flush();
        outputStream.close();
        //CAMBIA DE ESTADO A GUARDDADO EN LA NUBE
        comprobante.setEnNube(true);
        comprobanteDAO.actualizar(comprobante);

    } catch (Exception e) {
        guardo = false;
        throw new GenericException(e);
    }
    if (guardo) {
        //Guarda el detalle de la factura
        if (comprobante.getCoddoc().equals(TipoComprobanteEnum.FACTURA.getCodigo())) {
            for (DetalleComprobante detActual : comprobante.getDetalle()) {
                guardarDetalleComprobanteNube(detActual);
            }
        }
    }
    return guardo;
}

From source file:com.att.android.arodatacollector.main.AROCollectorService.java

/**
 * This method creates a SU enabled shell Sets the execute permission for
 * tcpdump and key.db Starts the tcpdump on Completion or abnormal
 * termination of tcpdump Shell is destroyed
 * //from w ww.  j a va2s. co m
 * @throws IOException
 * @throws InterruptedException
 */

private void startTcpDump() throws IOException, InterruptedException {
    Log.d(TAG, "inside startTcpDump at timestamp " + System.currentTimeMillis());
    Process sh = null;
    DataOutputStream os = null;
    int shExitValue = 0;
    try {
        startCalTime = Calendar.getInstance();

        if (!AROCollectorUtils.isTcpDumpRunning()) {
            //only start tcpdump if it's not already running, to handle the case where the background
            //service was stopped and now restarting

            Log.i(TAG, "tcpdump is not running. Starting tcpdump in the shell now");

            sh = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(sh.getOutputStream());
            String Command = "chmod 777 " + ARODataCollector.INTERNAL_DATA_PATH + TCPDUMPFILENAME + "\n";
            os.writeBytes(Command);
            Command = "chmod 777 " + ARODataCollector.INTERNAL_DATA_PATH + "key.db" + "\n";
            os.writeBytes(Command);

            //flurry timed event duration
            mApp.writeToFlurryAndLogEvent(flurryTimedEvent, "Flurry trace start",
                    startCalTime.getTime().toString(), "Trace Duration", true);

            /*Command = "." + ARODataCollector.INTERNAL_DATA_PATH + TCPDUMPFILENAME + " -w "
                  + TRACE_FOLDERNAME + "\n";*/

            Command = "." + ARODataCollector.INTERNAL_DATA_PATH + TCPDUMPFILENAME + " -i any -w "
                    + TRACE_FOLDERNAME + "\n";

            os.writeBytes(Command);
            Command = "exit\n";
            os.writeBytes(Command);
            os.flush();

            StreamClearer stdoutClearer = new StreamClearer(sh.getInputStream(), "stdout", true);
            new Thread(stdoutClearer).start();
            StreamClearer stderrClearer = new StreamClearer(sh.getErrorStream(), "stderr", true);
            new Thread(stderrClearer).start();

            shExitValue = sh.waitFor();
            if (DEBUG) {
                Log.i(TAG, "tcpdump waitFor returns exit value: " + shExitValue + " at "
                        + System.currentTimeMillis());
            }
        } else {
            Log.i(TAG, "timestamp " + System.currentTimeMillis() + ": tcpdump is already running");
        }

        //We will continue and block the thread untill we see valid instance of tcpdump running in shell
        //waitFor() does not seems to be working on ICS firmware 
        while (AROCollectorUtils.isTcpDumpRunning()) {
            continue;
        }
        if (DEBUG) {
            Log.d(TAG, "tcpdump process exit value: " + shExitValue);
            Log.i(TAG, "Coming out of startTcpDump at " + System.currentTimeMillis());
            logTcpdumpPid();
        }
        // Stopping the Video capture right after tcpdump coming out of
        // shell
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (mVideoRecording && mApp.getAROVideoCaptureRunningFlag()) {
                    stopScreenVideoCapture();
                    stopDmesg();
                }
            }
        }).start();

        final Calendar endCalTime = Calendar.getInstance();

        FlurryAgent.endTimedEvent("Trace Duration");
        mApp.writeToFlurry(flurryTimedEvent, "Flurry trace end", endCalTime.getTime().toString(),
                "flurryTimedEvent", AROCollectorUtils.NOT_APPLICABLE, AROCollectorUtils.EMPTY_STRING);
        mApp.writeToFlurry(flurryTimedEvent, "calculated Flurry trace duration", getUpTime(endCalTime),
                "flurryTimedEvent", AROCollectorUtils.NOT_APPLICABLE, AROCollectorUtils.EMPTY_STRING);
        logFlurryEvents();
        DataCollectorTraceStop();
    } finally {
        try {
            mApp.setTcpDumpStartFlag(false);
            if (os != null) {
                os.close();
            }
            if (sh != null) {
                sh.destroy();
            }
        } catch (Exception e) {
            Log.e(TAG, "exception in startTcpDump DataOutputStream close", e);
        }
    }
}

From source file:com.att.android.arodatacollector.main.AROCollectorService.java

/**
 * Stops collecting kernel log// w ww. j  a  va  2 s  .  co m
 *
 * Requires root permission.
 *
 * pre: there is only one "cat" process running
 */
private void stopDmesg() {
    Process sh = null;
    DataOutputStream os = null;
    int pid = 0;
    try {
        pid = mAroUtils.getProcessID("cat");
    } catch (IOException e1) {
        Log.e(TAG, "IOException in stopDmesg", e1);
    } catch (IndexOutOfBoundsException e1) {
        Log.e(TAG, "IndexOutOfBoundsException in stopDmesg", e1);
    } catch (InterruptedException e1) {
        Log.e(TAG, "exception in stopDmesg", e1);
    }
    if (DEBUG) {
        Log.d(TAG, "stopDmesg=" + pid);
    }
    if (pid != 0) {
        try {
            sh = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(sh.getOutputStream());
            final String Command = "kill -15 " + pid + "\n";
            os.writeBytes(Command);
            os.flush();
            sh.waitFor();
        } catch (IOException e) {
            Log.e(TAG, "exception in stopDmesg", e);
        } catch (InterruptedException e) {
            Log.e(TAG, "exception in stopDmesg", e);
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                Log.e(TAG, "exception in stopDmesg DataOutputStream close", e);
            }
            if (DEBUG) {
                Log.d(TAG, "Stopped stopDmesg");
            }
            sh.destroy();
        }
    }
}

From source file:my.swingconnect.SwingConnectUI.java

public int uploadFile(String User, String Pass) {
    int set = 0;//w ww . j a  v  a  2  s.c om
    String upLoadServerUri = null;
    upLoadServerUri = "http://photo-drop.com/clientlogin.php";
    final String USER_AGENT = "Mozilla/5.0";
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;

    if (User.isEmpty() && Pass.isEmpty()) {

        System.out.println("Please enter the valid User and Pass :");

        return set;
    } else {

        try {
            //String upLoadServerUri = null;
            int serverResponseCode = 0;

            URL url = new URL(upLoadServerUri); //Passing the server complete URL

            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent", USER_AGENT);
            conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
            //conn.setRequestProperty("Cookie", "Username=Mavericks;");
            String urlParameters = "Username=" + User + "&Password=" + Pass + "&submit=Login";
            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(urlParameters);
            dos.flush();
            dos.close();

            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post parameters : " + urlParameters);
            serverResponseCode = conn.getResponseCode();

            String serverResponseMessage = conn.getResponseMessage();

            System.out.println("HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);

            if (serverResponseCode == 200) {

                System.out.println("Posted success");
                set = 1;
            } else if (serverResponseCode == 401) {
                System.out.println("Invalid Login");

            } else {
                System.out.println("Error check");
            }

        } catch (MalformedURLException ex) {

            ex.printStackTrace();
            System.out.println("Error");

        } catch (Exception e) {

            e.printStackTrace();
            System.out.println("Error");

        }

        return set;

    }

}

From source file:com.salesmanager.core.module.impl.integration.payment.PaypalTransactionImpl.java

public Map httpcall(IntegrationProperties keys, CoreModuleService cms, String methodName, String nvpStr)
        throws Exception {

    // return null;

    boolean bSandbox = false;
    if (keys.getProperties5().equals("2")) {// sandbox
        bSandbox = true;/*from ww w . jav a  2 s.  c o  m*/
    }

    String gv_APIEndpoint = "";
    String PAYPAL_URL = "";
    String gv_Version = "3.3";

    if (bSandbox == true) {
        gv_APIEndpoint = "https://api-3t.sandbox.paypal.com/nvp";
        PAYPAL_URL = new StringBuffer().append(cms.getCoreModuleServiceDevProtocol()).append("://")
                .append(cms.getCoreModuleServiceDevDomain()).append(cms.getCoreModuleServiceDevEnv())
                .append("?cmd=_express-checkout&token=").toString();
        // PAYPAL_URL =
        // "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=";
    } else {
        gv_APIEndpoint = "https://api-3t.paypal.com/nvp";
        PAYPAL_URL = new StringBuffer().append(cms.getCoreModuleServiceProdProtocol()).append("://")
                .append(cms.getCoreModuleServiceProdDomain()).append(cms.getCoreModuleServiceProdEnv())
                .append("?cmd=_express-checkout&token=").toString();
        // PAYPAL_URL =
        // "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";
    }

    String agent = "Mozilla/4.0";
    String respText = "";
    Map nvp = null;

    // deformatNVP( nvpStr );
    String encodedData = "METHOD=" + methodName + "&VERSION=" + gv_Version + "&PWD=" + keys.getProperties2()
            + "&USER=" + keys.getProperties1() + "&SIGNATURE=" + keys.getProperties3() + nvpStr
            + "&BUTTONSOURCE=" + "PP-ECWizard";
    log.debug("REQUEST SENT TO PAYPAL -> " + encodedData);

    HttpURLConnection conn = null;
    DataOutputStream output = null;
    DataInputStream in = null;
    BufferedReader is = null;
    try {
        URL postURL = new URL(gv_APIEndpoint);
        conn = (HttpURLConnection) postURL.openConnection();

        // Set connection parameters. We need to perform input and output,
        // so set both as true.
        conn.setDoInput(true);
        conn.setDoOutput(true);

        // Set the content type we are POSTing. We impersonate it as
        // encoded form data
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("User-Agent", agent);

        // conn.setRequestProperty( "Content-Type", type );
        conn.setRequestProperty("Content-Length", String.valueOf(encodedData.length()));
        conn.setRequestMethod("POST");

        // get the output stream to POST to.
        output = new DataOutputStream(conn.getOutputStream());
        output.writeBytes(encodedData);
        output.flush();
        // output.close ();

        // Read input from the input stream.
        in = new DataInputStream(conn.getInputStream());
        int rc = conn.getResponseCode();
        if (rc != -1) {
            is = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String _line = null;
            while (((_line = is.readLine()) != null)) {
                log.debug("Response line from Paypal -> " + _line);
                respText = respText + _line;
            }
            nvp = StringUtil.deformatUrlResponse(respText);
        } else {
            throw new Exception("Invalid response from paypal, return code is " + rc);
        }

        nvp.put("PAYPAL_URL", PAYPAL_URL);
        nvp.put("NVP_URL", gv_APIEndpoint);

        return nvp;

    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Exception ignore) {
                // TODO: handle exception
            }
        }

        if (in != null) {
            try {
                in.close();
            } catch (Exception ignore) {
                // TODO: handle exception
            }
        }

        if (output != null) {
            try {
                output.close();
            } catch (Exception ignore) {
                // TODO: handle exception
            }
        }

        if (conn != null) {
            try {
                conn.disconnect();
            } catch (Exception ignore) {
                // TODO: handle exception
            }
        }
    }
}

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

private static void doAnalytics(String analytics, String event, String pageURL, String resourcePath,
        String resourceType) {//  ww w.  j ava 2s.com

    if (analytics != null && pageURL != null && resourcePath != null && resourceType != null && event != null) {

        URLConnection urlConn = null;
        DataOutputStream printout = null;
        BufferedReader input = null;
        String tmp = null;
        try {

            URL pageurl = new URL(pageURL);
            StringBuffer sb = new StringBuffer(
                    "<?xml version=1.0 encoding=UTF-8?><request><sc_xml_ver>1.0</sc_xml_ver>");
            sb.append("<events>" + event + "</events>");
            sb.append("<pageURL>" + pageURL + "</pageURL>");
            sb.append("<pageName>"
                    + pageurl.getPath().substring(1, pageurl.getPath().indexOf(".")).replaceAll("/", ":")
                    + "</pageName>");
            sb.append("<evar1>" + resourcePath + "</evar1>");
            sb.append("<evar2>" + resourceType + "</evar2>");
            sb.append("<visitorID>demomachine</visitorID>");
            sb.append("<reportSuiteID>" + analytics.substring(0, analytics.indexOf(".")) + "</reportSuiteID>");
            sb.append("</request>");

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

            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(sb.toString());
            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.error(ex.getMessage());

        }

    }

}

From source file:ClassFile.java

public void write(DataOutputStream dos, ConstantPoolInfo pool[]) throws IOException, Exception {
    dos.write(type);/*from ww w . j a  va  2 s.com*/
    switch (type) {
    case CLASS:
    case STRING:
        dos.writeShort(indexOf(arg1, pool));
        break;
    case FIELDREF:
    case METHODREF:
    case INTERFACE:
    case NAMEANDTYPE:
        dos.writeShort(indexOf(arg1, pool));
        dos.writeShort(indexOf(arg2, pool));
        break;
    case INTEGER:
        dos.writeInt(intValue);
        break;
    case FLOAT:
        dos.writeFloat(floatValue);
        break;
    case LONG:
        dos.writeLong(longValue);
        break;
    case DOUBLE:
        dos.writeDouble(doubleValue);
        break;
    case ASCIZ:
    case UNICODE:
        dos.writeShort(strValue.length());
        dos.writeBytes(strValue);
        break;
    default:
        throw new Exception("ConstantPoolInfo::write() - bad type.");
    }
}

From source file:com.example.rartonne.appftur.HomeActivity.java

public int uploadFile(String sourceFileUri) {

    String fileName = sourceFileUri;

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);

    if (!sourceFile.isFile()) {

        //dialog.dismiss();

        Log.e("uploadFile", "Source File not exist");

        runOnUiThread(new Runnable() {
            public void run() {
                //messageText.setText("Source File not exist :"+uploadFilePath + "" + uploadFileName);
            }//from  w  ww . j  a  va  2  s. c  o m
        });

        return 0;

    } else {
        try {

            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(upLoadServerUri);

            // Open a HTTP  connection to  the URL
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("uploaded_file", fileName);

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

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName
                    + "\"" + lineEnd);

            dos.writeBytes(lineEnd);

            // create a buffer of  maximum size
            bytesAvailable = fileInputStream.available();

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

            // read file and write it into form...
            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);

            }

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

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

            Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);

            if (serverResponseCode == 200) {

                runOnUiThread(new Runnable() {
                    public void run() {

                        /*String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                            +" http://www.androidexample.com/media/uploads/"
                            +uploadFileName;*/

                        //messageText.setText(msg);
                        /*Toast.makeText(getApplicationContext(), "File Upload Complete.",
                            Toast.LENGTH_SHORT).show();*/
                    }
                });
            }

            //close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {

            //dialog.dismiss();
            ex.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    //messageText.setText("MalformedURLException Exception : check script url.");
                    /*Toast.makeText(getApplicationContext(), "MalformedURLException",
                        Toast.LENGTH_SHORT).show();*/
                }
            });

            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {

            //dialog.dismiss();
            e.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    //messageText.setText("Got Exception : see logcat ");
                    /*Toast.makeText(getApplicationContext(), "Got Exception : see logcat ",
                        Toast.LENGTH_SHORT).show();*/
                }
            });
            Log.e("Upload file to server", "Exception : " + e.getMessage(), e);
        }
        // dialog.dismiss();
        return serverResponseCode;

    } // End else block
}

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

public ArrayList<File> mediaSerialize(Cursor cursor) {
    logger.debug("::mediaSerialize");
    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()) {
        MediaWrapper iw = new MediaWrapper();
        iw.setEventId(cursor.getString(cursor.getColumnIndex(MediaTableSchemaBase.EVENT_ID)));
        iw.setDataType(cursor.getString(cursor.getColumnIndex(MediaTableSchemaBase.DATA_TYPE)));
        iw.setData(cursor.getString(cursor.getColumnIndex(MediaTableSchemaBase.DATA)));
        iw.setCreatedDate(cursor.getLong(cursor.getColumnIndex(MediaTableSchemaBase.CREATED_DATE)));
        iw.setModifiedDate(cursor.getLong(cursor.getColumnIndex(MediaTableSchemaBase.MODIFIED_DATE)));
        iw.set_ReceivedDate(cursor.getLong(cursor.getColumnIndex(MediaTableSchemaBase._RECEIVED_DATE)));
        iw.set_Disposition(cursor.getInt(cursor.getColumnIndex(MediaTableSchemaBase._DISPOSITION)));

        Gson gson = new Gson();

        try {//from   ww  w .  j  av a 2 s  . c  om
            eos.writeBytes(gson.toJson(iw));
            eos.writeByte(0);
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        // not a reference field name :event id eventId event_id\n 
        try {
            String fileName = iw.getData();
            File dataFile = new File(fileName);
            int dataSize = (int) dataFile.length();
            byte[] buffData = new byte[dataSize];
            FileInputStream fileStream = new FileInputStream(dataFile);
            int ret = 0;
            for (int position = 0; (ret > -1 && dataSize > position); position += ret) {
                ret = fileStream.read(buffData, position, dataSize - position);
            }
            fileStream.close();

            eos.writeBytes("data");
            eos.writeByte(0);

            ByteBuffer dataSizeBuf = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE);
            dataSizeBuf.order(ByteOrder.LITTLE_ENDIAN);
            dataSizeBuf.putInt(dataSize);

            // write the media back out
            eos.write(dataSizeBuf.array());
            eos.write(buffData);
            eos.write(dataSizeBuf.array());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // not a reference field name :created date createdDate created_date\n 
        // not a reference field name :modified date modifiedDate modified_date\n 
        // MediaTableSchemaBase._DISPOSITION;

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

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

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

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

public ArrayList<File> categorySerialize(Cursor cursor) {
    logger.debug("::categorySerialize");
    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()) {
        CategoryWrapper iw = new CategoryWrapper();
        iw.setMainCategory(cursor.getString(cursor.getColumnIndex(CategoryTableSchemaBase.MAIN_CATEGORY)));
        iw.setSubCategory(cursor.getString(cursor.getColumnIndex(CategoryTableSchemaBase.SUB_CATEGORY)));
        iw.setTigrId(cursor.getString(cursor.getColumnIndex(CategoryTableSchemaBase.TIGR_ID)));
        iw.setIconType(cursor.getString(cursor.getColumnIndex(CategoryTableSchemaBase.ICON_TYPE)));
        iw.setIcon(cursor.getString(cursor.getColumnIndex(CategoryTableSchemaBase.ICON)));
        iw.set_ReceivedDate(cursor.getLong(cursor.getColumnIndex(CategoryTableSchemaBase._RECEIVED_DATE)));
        iw.set_Disposition(cursor.getInt(cursor.getColumnIndex(CategoryTableSchemaBase._DISPOSITION)));

        Gson gson = new Gson();

        try {/*from   w w  w  .  ja v a  2 s  .c o  m*/
            eos.writeBytes(gson.toJson(iw));
            eos.writeByte(0);
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        // not a reference field name :main category mainCategory main_category\n 
        // not a reference field name :sub category subCategory sub_category\n 
        // not a reference field name :tigr id tigrId tigr_id\n 
        try {
            String fileName = iw.getIcon();
            File dataFile = new File(fileName);
            int dataSize = (int) dataFile.length();
            byte[] buffData = new byte[dataSize];
            FileInputStream fileStream = new FileInputStream(dataFile);
            int ret = 0;
            for (int position = 0; (ret > -1 && dataSize > position); position += ret) {
                ret = fileStream.read(buffData, position, dataSize - position);
            }
            fileStream.close();

            eos.writeBytes("icon");
            eos.writeByte(0);

            ByteBuffer dataSizeBuf = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE);
            dataSizeBuf.order(ByteOrder.LITTLE_ENDIAN);
            dataSizeBuf.putInt(dataSize);

            // write the category back out
            eos.write(dataSizeBuf.array());
            eos.write(buffData);
            eos.write(dataSizeBuf.array());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // CategoryTableSchemaBase._DISPOSITION;

        //           try {
        //              if (!applCacheCategoryDir.exists() ) applCacheCategoryDir.mkdirs();
        //              
        //              File outfile = new File(applCacheCategoryDir, 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;
}