Example usage for java.io FileInputStream available

List of usage examples for java.io FileInputStream available

Introduction

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

Prototype

public int available() throws IOException 

Source Link

Document

Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

Usage

From source file:com.inter.trade.ui.fragment.agent.AgentApplyFragmentNew.java

private void doPhoto(int requestCode, Intent data) {
    if (requestCode == SELECT_PIC_BY_PICK_PHOTO) // ??
    {//  w ww.  j  a  va  2s . co m
        if (data == null) {
            Toast.makeText(getActivity(), "", Toast.LENGTH_LONG).show();
            return;
        }
        photoUri = data.getData();
        if (photoUri == null) {
            Toast.makeText(getActivity(), "", Toast.LENGTH_LONG).show();
            return;
        }
    }
    String[] pojo = { MediaStore.Images.Media.DATA };
    mCursor = getActivity().managedQuery(photoUri, pojo, null, null, null);
    if (mCursor != null) {
        int columnIndex = mCursor.getColumnIndexOrThrow(pojo[0]);
        mCursor.moveToFirst();
        picPath = mCursor.getString(columnIndex);
        // cursor.close();
    }
    if (picPath != null && (picPath.endsWith(".png") || picPath.endsWith(".PNG") || picPath.endsWith(".jpg")
            || picPath.endsWith(".JPG"))) {
        try {
            File file = new File(picPath);
            FileInputStream inputStream = new FileInputStream(file);
            Logger.d("file", "length " + inputStream.available());
            //            inputStream.close();

            //         BitmapFactory.Options options = new BitmapFactory.Options();
            //         options.inSampleSize = 4;
            //         Bitmap bm = BitmapFactory.decodeFile(picPath, options);
            Bitmap bm = decodeSampledBitmapFromDescriptor(inputStream.getFD(), 300, 300, null);
            if (pos == 0) {
                agent_applying_license_photo_img.setBackgroundDrawable(null);
                agent_applying_license_photo_img.setImageBitmap(bm);
                identityBitmap1 = Bitmap.createScaledBitmap(bm, 200, 300, true);
                path[0] = picPath;
                mInfoList.get(agentType).infoDataList.get(pos).putValue("selectpic", "1");
                //            agent_applying_license_photo_done_img.setVisibility(View.VISIBLE);
            } else if (pos == 1) {
                agent_applying_organization_photo_img.setBackgroundDrawable(null);
                agent_applying_organization_photo_img.setImageBitmap(bm);
                identityBitmap2 = Bitmap.createScaledBitmap(bm, 200, 300, true);
                path[1] = picPath;
                mInfoList.get(agentType).infoDataList.get(pos).putValue("selectpic", "1");
                //            agent_applying_organization_photo_done_img.setVisibility(View.VISIBLE);
            } else if (pos == 2) {
                agent_applying_tax_photo_img.setBackgroundDrawable(null);
                agent_applying_tax_photo_img.setImageBitmap(bm);
                identityBitmap3 = Bitmap.createScaledBitmap(bm, 200, 300, true);
                path[2] = picPath;
                mInfoList.get(agentType).infoDataList.get(pos).putValue("selectpic", "1");
                //            agent_applying_tax_photo_done_img.setVisibility(View.VISIBLE);
            } else if (pos == 3) {
                agent_applying_id_card_photo_img.setBackgroundDrawable(null);
                agent_applying_id_card_photo_img.setImageBitmap(bm);
                identityBitmap4 = Bitmap.createScaledBitmap(bm, 200, 300, true);
                path[3] = picPath;
                mInfoList.get(agentType).infoDataList.get(pos).putValue("selectpic", "1");
                //            agent_applying_id_card_photo_done_img.setVisibility(View.VISIBLE);
            }
            isPicChange = true;
            //         agent_applying_license_photo_done_img.setVisibility(View.VISIBLE);
        } catch (Exception e) {
            // TODO: handle exception
        }
    } else {
        Toast.makeText(getActivity(), "?", Toast.LENGTH_LONG).show();
    }
}

From source file:org.talend.mdm.engines.client.ui.wizards.DeployOnMDMExportWizardPage.java

/**
 * copy all the files of this folder to another
 *///from   w ww .  j  av a 2s. co m

private void copy(File[] s, File d) {
    if (!d.exists()) {
        d.mkdir();
    }
    for (File element : s) {
        if (element.isFile()) {
            try {
                FileInputStream fis = new FileInputStream(element);
                FileOutputStream out = new FileOutputStream(
                        new File(d.getPath() + File.separator + element.getName()));
                int count = fis.available();
                byte[] data = new byte[count];
                if ((fis.read(data)) != -1) {
                    out.write(data);
                }
                out.close();
                fis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (element.isDirectory()) {
            File des = new File(d.getPath() + File.separator + element.getName());
            des.mkdir();
            copy(element.listFiles(), des);
        }
    }
}

From source file:com.orange.labs.sdk.RestUtils.java

public void uploadRequest(URL url, File file, String folderIdentifier, final Map<String, String> headers,
        final OrangeListener.Success<JSONObject> success, final OrangeListener.Progress progress,
        final OrangeListener.Error failure) {

    // open a URL connection to the Server
    FileInputStream fileInputStream = null;
    try {//  w w  w. ja  va  2s.c o m
        fileInputStream = new FileInputStream(file);

        // Open a HTTP connection to the URL
        HttpURLConnection conn = (HttpsURLConnection) url.openConnection();

        // Allow Inputs & Outputs
        conn.setDoInput(true);
        conn.setDoOutput(true);

        // Don't use a Cached Copy
        conn.setUseCaches(false);

        conn.setRequestMethod("POST");

        //
        // Define headers
        //

        // Create an unique boundary
        String boundary = "UploadBoundary";

        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        for (String key : headers.keySet()) {
            conn.setRequestProperty(key.toString(), headers.get(key));
        }

        //
        // Write body part
        //
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

        int bytesAvailable = fileInputStream.available();

        String marker = "\r\n--" + boundary + "\r\n";

        dos.writeBytes(marker);
        dos.writeBytes("Content-Disposition: form-data; name=\"description\"\r\n\r\n");

        // Create JSonObject :
        JSONObject params = new JSONObject();
        params.put("name", file.getName());
        params.put("size", String.valueOf(bytesAvailable));
        params.put("folder", folderIdentifier);

        dos.writeBytes(params.toString());

        dos.writeBytes(marker);
        dos.writeBytes(
                "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n");
        dos.writeBytes("Content-Type: image/jpeg\r\n\r\n");

        int progressValue = 0;
        int bytesRead = 0;
        byte buf[] = new byte[1024];
        BufferedInputStream bufInput = new BufferedInputStream(fileInputStream);
        while ((bytesRead = bufInput.read(buf)) != -1) {
            // write output
            dos.write(buf, 0, bytesRead);
            dos.flush();
            progressValue += bytesRead;
            // update progress bar
            progress.onProgress((float) progressValue / bytesAvailable);
        }

        dos.writeBytes(marker);

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

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

        if (serverResponseCode == 200 || serverResponseCode == 201) {
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String response = "";
            String line;
            while ((line = rd.readLine()) != null) {
                Log.i("FileUpload", "Response: " + line);
                response += line;
            }
            rd.close();
            JSONObject object = new JSONObject(response);
            success.onResponse(object);
        } else {
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            String response = "";
            String line;
            while ((line = rd.readLine()) != null) {
                Log.i("FileUpload", "Error: " + line);
                response += line;
            }
            rd.close();
            JSONObject errorResponse = new JSONObject(response);
            failure.onErrorResponse(new CloudAPIException(serverResponseCode, errorResponse));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:fyp.project.uploadFile.UploadFile.java

public int upLoad2Server(String sourceFileUri) {
    String upLoadServerUri = "http://vbacdu.ddns.net:8080/WBS/newjsp.jsp";
    // String [] string = sourceFileUri;
    String fileName = sourceFileUri;
    int serverResponseCode = 0;

    HttpURLConnection conn = null;
    DataOutputStream dos = null;/*from   w  w w  .  jav a  2  s  .  c  om*/
    DataInputStream inStream = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    String responseFromServer = "";

    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {

        return 0;
    }
    try { // open a URL connection to the Servlet
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        URL url = new URL(upLoadServerUri);
        conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
        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("file", fileName);
        dos = new DataOutputStream(conn.getOutputStream());

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

        m_log.log(Level.INFO, "Content-Disposition: form-data; name=\"file\";filename=\"{0}\"{1}",
                new Object[] { fileName.substring(fileName.lastIndexOf("/")), lineEnd });
        dos.writeBytes(lineEnd);

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

        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();

        m_log.log(Level.INFO, "Upload file to server" + "HTTP Response is : {0}: {1}",
                new Object[] { serverResponseMessage, serverResponseCode });

        // close streams
        m_log.log(Level.INFO, "Upload file to server{0} File is written", fileName);
        fileInputStream.close();
        dos.flush();
        dos.close();
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        m_log.log(Level.ALL, "Upload file to server" + "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        e.printStackTrace();
    }
    //this block will give the response of upload link

    return serverResponseCode; // like 200 (Ok)

}

From source file:im.vector.util.VectorRoomMediasSender.java

/**
 * Offer to resize the image before sending it.
 * @param aThumbnailURL the thumbnail url
 * @param anImageUrl the image url.//from   www  .j  av a  2  s  .c  o  m
 * @param anImageFilename the image filename
 * @param anImageMimeType the image mimetype
 * @param aListener the listener
 */
private void sendImageMessage(final String aThumbnailURL, final String anImageUrl, final String anImageFilename,
        final String anImageMimeType, final OnImageUploadListener aListener) {
    // sanity check
    if ((null == anImageUrl) || (null == aListener)) {
        return;
    }

    boolean isManaged = false;

    // check if the media could be resized
    if ((null != aThumbnailURL) && (CommonActivityUtils.MIME_TYPE_JPEG.equals(anImageMimeType)
            || CommonActivityUtils.MIME_TYPE_JPG.equals(anImageMimeType)
            || CommonActivityUtils.MIME_TYPE_IMAGE_ALL.equals(anImageMimeType))) {
        System.gc();
        FileInputStream imageStream;

        try {
            Uri uri = Uri.parse(anImageUrl);
            final String filename = uri.getPath();

            final int rotationAngle = ImageUtils.getRotationAngleForBitmap(mVectorRoomActivity, uri);

            imageStream = new FileInputStream(new File(filename));

            int fileSize = imageStream.available();

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            options.outWidth = -1;
            options.outHeight = -1;

            // retrieve the image size
            try {
                BitmapFactory.decodeStream(imageStream, null, options);
            } catch (OutOfMemoryError e) {
                Log.e(LOG_TAG, "sendImageMessage out of memory error : " + e.getMessage());
            }

            final ImageCompressionSizes imageSizes = computeImageSizes(options.outWidth, options.outHeight);

            imageStream.close();

            // the user already selects a compression
            if (null != mImageCompressionDescription) {
                isManaged = true;

                final ImageSize expectedSize = imageSizes.getImageSize(mVectorRoomActivity,
                        mImageCompressionDescription);
                final String fImageUrl = resizeImage(anImageUrl, filename, imageSizes.mFullImageSize,
                        expectedSize, rotationAngle);

                mVectorRoomActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mVectorMessageListFragment.uploadImageContent(aThumbnailURL, fImageUrl, anImageFilename,
                                anImageMimeType);
                        aListener.onDone();
                    }
                });
            }
            // can be rescaled ?
            else if (null != imageSizes.mSmallImageSize) {
                isManaged = true;

                FragmentManager fm = mVectorRoomActivity.getSupportFragmentManager();
                ImageSizeSelectionDialogFragment fragment = (ImageSizeSelectionDialogFragment) fm
                        .findFragmentByTag(TAG_FRAGMENT_IMAGE_SIZE_DIALOG);

                if (fragment != null) {
                    fragment.dismissAllowingStateLoss();
                }

                String[] stringsArray = getImagesCompressionTextsList(mVectorRoomActivity, imageSizes,
                        fileSize);

                final AlertDialog.Builder alert = new AlertDialog.Builder(mVectorRoomActivity);
                alert.setTitle(mVectorRoomActivity.getString(im.vector.R.string.compression_options));
                alert.setSingleChoiceItems(stringsArray, -1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        final int fPos = which;

                        mImageSizesListDialog.dismiss();

                        mVectorRoomActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mVectorRoomActivity.setProgressVisibility(View.VISIBLE);

                                Thread thread = new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ImageSize expectedSize = null;

                                        // full size
                                        if (0 != fPos) {
                                            expectedSize = imageSizes.getImageSizesList().get(fPos);
                                        }

                                        // stored the compression selected by the user
                                        mImageCompressionDescription = imageSizes
                                                .getImageSizesDescription(mVectorRoomActivity).get(fPos);

                                        final String fImageUrl = resizeImage(anImageUrl, filename,
                                                imageSizes.mFullImageSize, expectedSize, rotationAngle);

                                        mVectorRoomActivity.runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                mVectorMessageListFragment.uploadImageContent(aThumbnailURL,
                                                        fImageUrl, anImageFilename, anImageMimeType);
                                                aListener.onDone();
                                            }
                                        });
                                    }
                                });

                                thread.setPriority(Thread.MIN_PRIORITY);
                                thread.start();
                            }
                        });
                    }
                });

                mImageSizesListDialog = alert.show();
                mImageSizesListDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        mImageSizesListDialog = null;
                        if (null != aListener) {
                            aListener.onCancel();
                        }
                    }
                });
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "sendImageMessage failed " + e.getMessage());
        }
    }

    // cannot resize, let assumes that it has been done
    if (!isManaged) {
        mVectorRoomActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mVectorMessageListFragment.uploadImageContent(aThumbnailURL, anImageUrl, anImageFilename,
                        anImageMimeType);
                if (null != aListener) {
                    aListener.onDone();
                }
            }
        });
    }
}

From source file:im.neon.util.VectorRoomMediasSender.java

/**
 * Offer to resize the image before sending it.
 * @param aThumbnailURL the thumbnail url
 * @param anImageUrl the image url.//  www. j a v  a2  s  .c  o m
 * @param anImageFilename the image filename
 * @param anImageMimeType the image mimetype
 * @param aListener the listener
 */
private void sendImageMessage(final String aThumbnailURL, final String anImageUrl, final String anImageFilename,
        final String anImageMimeType, final OnImageUploadListener aListener) {
    // sanity check
    if ((null == anImageUrl) || (null == aListener)) {
        return;
    }

    boolean isManaged = false;

    // check if the media could be resized
    if ((null != aThumbnailURL) && (CommonActivityUtils.MIME_TYPE_JPEG.equals(anImageMimeType)
            || CommonActivityUtils.MIME_TYPE_JPG.equals(anImageMimeType)
            || CommonActivityUtils.MIME_TYPE_IMAGE_ALL.equals(anImageMimeType))) {
        System.gc();
        FileInputStream imageStream;

        try {
            Uri uri = Uri.parse(anImageUrl);
            final String filename = uri.getPath();

            final int rotationAngle = ImageUtils.getRotationAngleForBitmap(mVectorRoomActivity, uri);

            imageStream = new FileInputStream(new File(filename));

            int fileSize = imageStream.available();

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            options.outWidth = -1;
            options.outHeight = -1;

            // retrieve the image size
            try {
                BitmapFactory.decodeStream(imageStream, null, options);
            } catch (OutOfMemoryError e) {
                Log.e(LOG_TAG, "sendImageMessage out of memory error : " + e.getMessage());
            }

            final ImageCompressionSizes imageSizes = computeImageSizes(options.outWidth, options.outHeight);

            imageStream.close();

            // the user already selects a compression
            if (null != mImageCompressionDescription) {
                isManaged = true;

                final ImageSize expectedSize = imageSizes.getImageSize(mVectorRoomActivity,
                        mImageCompressionDescription);
                final String fImageUrl = resizeImage(anImageUrl, filename, imageSizes.mFullImageSize,
                        expectedSize, rotationAngle);

                mVectorRoomActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mVectorMessageListFragment.uploadImageContent(null, null, aThumbnailURL, fImageUrl,
                                anImageFilename, anImageMimeType);
                        aListener.onDone();
                    }
                });
            }
            // can be rescaled ?
            else if (null != imageSizes.mSmallImageSize) {
                isManaged = true;

                FragmentManager fm = mVectorRoomActivity.getSupportFragmentManager();
                ImageSizeSelectionDialogFragment fragment = (ImageSizeSelectionDialogFragment) fm
                        .findFragmentByTag(TAG_FRAGMENT_IMAGE_SIZE_DIALOG);

                if (fragment != null) {
                    fragment.dismissAllowingStateLoss();
                }

                String[] stringsArray = getImagesCompressionTextsList(mVectorRoomActivity, imageSizes,
                        fileSize);

                final AlertDialog.Builder alert = new AlertDialog.Builder(mVectorRoomActivity);
                alert.setTitle(mVectorRoomActivity.getString(im.neon.R.string.compression_options));
                alert.setSingleChoiceItems(stringsArray, -1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        final int fPos = which;

                        mImageSizesListDialog.dismiss();

                        mVectorRoomActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mVectorRoomActivity.setProgressVisibility(View.VISIBLE);

                                Thread thread = new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ImageSize expectedSize = null;

                                        // full size
                                        if (0 != fPos) {
                                            expectedSize = imageSizes.getImageSizesList().get(fPos);
                                        }

                                        // stored the compression selected by the user
                                        mImageCompressionDescription = imageSizes
                                                .getImageSizesDescription(mVectorRoomActivity).get(fPos);

                                        final String fImageUrl = resizeImage(anImageUrl, filename,
                                                imageSizes.mFullImageSize, expectedSize, rotationAngle);

                                        mVectorRoomActivity.runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                mVectorMessageListFragment.uploadImageContent(null, null,
                                                        aThumbnailURL, fImageUrl, anImageFilename,
                                                        anImageMimeType);
                                                aListener.onDone();
                                            }
                                        });
                                    }
                                });

                                thread.setPriority(Thread.MIN_PRIORITY);
                                thread.start();
                            }
                        });
                    }
                });

                mImageSizesListDialog = alert.show();
                mImageSizesListDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        mImageSizesListDialog = null;
                        if (null != aListener) {
                            aListener.onCancel();
                        }
                    }
                });
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "sendImageMessage failed " + e.getMessage());
        }
    }

    // cannot resize, let assumes that it has been done
    if (!isManaged) {
        mVectorRoomActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mVectorMessageListFragment.uploadImageContent(null, null, aThumbnailURL, anImageUrl,
                        anImageFilename, anImageMimeType);
                if (null != aListener) {
                    aListener.onDone();
                }
            }
        });
    }
}

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(',');
        }// w w w  .ja  v  a  2 s . c  o m
        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.sandklef.coachapp.http.HttpAccess.java

public void uploadTrainingPhaseVideo(String clubUri, String videoUuid, String fileName)
        throws HttpAccessException, IOException {

    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    DataInputStream inputStream = null;

    String pathToOurFile = fileName;
    String urlServer = urlBase + HttpSettings.API_VERSION + HttpSettings.PATH_SEPARATOR
            + HttpSettings.VIDEO_URL_PATH + HttpSettings.UUID_PATH + videoUuid + HttpSettings.PATH_SEPARATOR
            + HttpSettings.UPLOAD_PATH;/*from  www . jav a  2  s .c om*/

    Log.d(LOG_TAG, "Upload server url: " + urlServer);
    Log.d(LOG_TAG, "Upload file:       " + fileName);

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;

    FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));

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

    Log.d(LOG_TAG, "connection: " + connection + "  uploading data to video: " + videoUuid);

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

    //
    int timeout = LocalStorage.getInstance().getnetworkTimeout();
    Log.d(LOG_TAG, "timeout: " + timeout);
    connection.setConnectTimeout(timeout);
    connection.setReadTimeout(timeout);

    connection.setRequestProperty("X-Token", LocalStorage.getInstance().getLatestUserToken());
    connection.addRequestProperty("X-Instance", LocalStorage.getInstance().getCurrentClub());
    connection.setRequestProperty("Connection", "close");

    Log.d(LOG_TAG, " upload propoerties: " + connection.getRequestProperties());

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

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

    while (bytesRead > 0) {
        Log.d(LOG_TAG, " writing data to stream  (" + bytesRead + " / " + bytesAvailable + ")");
        outputStream.write(buffer, 0, bufferSize);
        Log.d(LOG_TAG, " writing data to stream  -");
        bytesAvailable = fileInputStream.available();
        Log.d(LOG_TAG, " writing data to stream  -");
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }
    outputStream.flush();
    outputStream.close();

    // Responses from the server (code and message)
    fileInputStream.close();

    int serverResponseCode = 0;

    long before = System.currentTimeMillis();
    try {
        Log.d(LOG_TAG, " ... writing done, getting response code");
        serverResponseCode = connection.getResponseCode();
        Log.d(LOG_TAG, " ... writing done, getting response message");
        String serverResponseMessage = connection.getResponseMessage();
        Log.d(LOG_TAG, "ServerCode:" + serverResponseCode);
        Log.d(LOG_TAG, "serverResponseMessage:" + serverResponseMessage);
    } catch (java.net.SocketTimeoutException e) {
        Log.d(LOG_TAG, " ... getting response code, got an exception, print stacktrace");
        e.printStackTrace();
        throw new HttpAccessException("Network timeout reached", e, HttpAccessException.NETWORK_SLOW);
    }
    long after = System.currentTimeMillis();
    long diff = after - before;
    Log.d(LOG_TAG, "diff: " + diff + "ms   " + diff / 1000 + "s");

    if (diff > LocalStorage.getInstance().getnetworkTimeout()) {
        throw new HttpAccessException("Network timeout reached", HttpAccessException.NETWORK_SLOW);
    }

    if (serverResponseCode >= 409) {
        throw new HttpAccessException("Failed uploading trainingphase video, access denied",
                HttpAccessException.CONFLICT_ERROR);
    }

    if (serverResponseCode < 500 && serverResponseCode >= 400) {
        throw new HttpAccessException("Failed uploading trainingphase video, access denied",
                HttpAccessException.ACCESS_ERROR);
    }

    try {
        Log.d(LOG_TAG, " ... disconnecting");
        connection.disconnect();
    } catch (Exception e) {
        Log.d(LOG_TAG, " ... disconnecting, got an exception, print stacktrace");
        e.printStackTrace();
    }
}