List of usage examples for java.io DataOutputStream flush
public void flush() throws IOException
From source file:com.hollandhaptics.babyapp.BabyService.java
/** * @param sourceFile The file to upload. * @return int The server's response code. * @brief Uploads a file to the server. Is called by uploadAudioFiles(). *///from ww w . ja v a 2 s.c om public int uploadFile(File sourceFile) { HttpURLConnection conn; DataOutputStream dos; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1024 * 1024; String sourceFileUri = sourceFile.getAbsolutePath(); if (!sourceFile.isFile()) { Log.e("uploadFile", "Source File does not exist :" + sourceFileUri); 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("fileToUpload", sourceFileUri); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"fileToUpload\";filename=\"" + sourceFileUri + "\"" + 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) { boolean deleted = sourceFile.delete(); Log.i("Deleted succes", String.valueOf(deleted)); } //close the streams // fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { ex.printStackTrace(); Log.e("Upload file to server", "error: " + ex.getMessage(), ex); } catch (Exception e) { e.printStackTrace(); Log.e("Upload file to server", "Exception : " + e.getMessage(), e); } return serverResponseCode; } // End else block }
From source file:com.roamprocess1.roaming4world.syncadapter.SyncAdapter.java
public int uploadFile(String sourceFileUri) { String upLoadServerUri = ""; upLoadServerUri = "http://ip.roaming4world.com/esstel/fetch_contacts_upload.php"; String fileName = sourceFileUri; Log.d("file upload url", upLoadServerUri); 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()) { Log.d("uploadFile", "Source File Does not exist"); return 0; }//from w ww . j a va2s.c om int serverResponseCode = 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("uploaded_file", fileName); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + selfNumber + "-" + fileName + "\"" + 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(); Log.d("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); //close the streams // fileInputStream.close(); dos.flush(); dos.close(); Log.d("Contact file ", "uploaded"); } catch (MalformedURLException ex) { ex.printStackTrace(); Log.e("Upload file to server", "error: " + ex.getMessage(), ex); } catch (Exception e) { e.printStackTrace(); Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e); } return serverResponseCode; }
From source file:com.yahoo.pulsar.testclient.LoadSimulationClient.java
private void handle(final byte command, final DataInputStream inputStream, final DataOutputStream outputStream) throws Exception { final TradeConfiguration tradeConf = new TradeConfiguration(); tradeConf.command = command;/*from www .j a v a 2s .c o m*/ switch (command) { case CHANGE_COMMAND: // Change the topic's settings if it exists. Report whether the // topic was found on this server. decodeProducerOptions(tradeConf, inputStream); if (topicsToTradeUnits.containsKey(tradeConf.topic)) { topicsToTradeUnits.get(tradeConf.topic).change(tradeConf); outputStream.write(FOUND_TOPIC); } else { outputStream.write(NO_SUCH_TOPIC); } break; case STOP_COMMAND: // Stop the topic if it exists. Report whether the topic was found, // and whether it was already stopped. tradeConf.topic = inputStream.readUTF(); if (topicsToTradeUnits.containsKey(tradeConf.topic)) { final boolean wasStopped = topicsToTradeUnits.get(tradeConf.topic).stop.getAndSet(true); outputStream.write(wasStopped ? REDUNDANT_COMMAND : FOUND_TOPIC); } else { outputStream.write(NO_SUCH_TOPIC); } break; case TRADE_COMMAND: // Create the topic. It is assumed that the topic does not already // exist. decodeProducerOptions(tradeConf, inputStream); final TradeUnit tradeUnit = new TradeUnit(tradeConf, client, producerConf, consumerConf, payloadCache); topicsToTradeUnits.put(tradeConf.topic, tradeUnit); executor.submit(() -> { try { tradeUnit.start(); } catch (Exception ex) { throw new RuntimeException(ex); } }); // Tell controller topic creation is finished. outputStream.write(NO_SUCH_TOPIC); break; case CHANGE_GROUP_COMMAND: // Change the settings of all topics belonging to a group. Report // the number of topics changed. decodeGroupOptions(tradeConf, inputStream); tradeConf.size = inputStream.readInt(); tradeConf.rate = inputStream.readDouble(); // See if a topic belongs to this tenant and group using this regex. final String groupRegex = ".*://.*/" + tradeConf.tenant + "/" + tradeConf.group + "-.*/.*"; int numFound = 0; for (Map.Entry<String, TradeUnit> entry : topicsToTradeUnits.entrySet()) { final String destination = entry.getKey(); final TradeUnit unit = entry.getValue(); if (destination.matches(groupRegex)) { ++numFound; unit.change(tradeConf); } } outputStream.writeInt(numFound); break; case STOP_GROUP_COMMAND: // Stop all topics belonging to a group. Report the number of topics // stopped. decodeGroupOptions(tradeConf, inputStream); // See if a topic belongs to this tenant and group using this regex. final String regex = ".*://.*/" + tradeConf.tenant + "/" + tradeConf.group + "-.*/.*"; int numStopped = 0; for (Map.Entry<String, TradeUnit> entry : topicsToTradeUnits.entrySet()) { final String destination = entry.getKey(); final TradeUnit unit = entry.getValue(); if (destination.matches(regex) && !unit.stop.getAndSet(true)) { ++numStopped; } } outputStream.writeInt(numStopped); break; default: throw new IllegalArgumentException("Unrecognized command code received: " + command); } outputStream.flush(); }
From source file:com.roamprocess1.roaming4world.ui.messages.MessageActivity.java
public int uploadFile(String sourceFileUri, String fileName) { String upLoadServerUri = ""; upLoadServerUri = "http://ip.roaming4world.com/esstel/file-transfer/file_upload.php"; 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()) { Log.e("uploadFile", "Source File Does not exist"); return 0; }//from ww w . java 2 s .com 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("uploaded_file", sourceFileUri); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + multimediaMsg + fileName + "\"" + 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(); Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); // close the streams // fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { ex.printStackTrace(); Log.e("Upload file to server", "error: " + ex.getMessage(), ex); } catch (Exception e) { e.printStackTrace(); Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e); } return serverResponseCode; }
From source file:com.phonegap.FileTransfer.java
/** * Uploads the specified file to the server URL provided using an HTTP * multipart request. /* w ww.j a v a 2 s . c om*/ * @param file Full path of the file on the file system * @param server URL of the server to receive the file * @param fileKey Name of file request parameter * @param fileName File name to be used on server * @param mimeType Describes file content type * @param params key:value pairs of user-defined parameters * @return FileUploadResult containing result of upload request */ public FileUploadResult upload(String file, String server, final String fileKey, final String fileName, final String mimeType, JSONObject params, boolean trustEveryone) throws IOException, SSLException { // Create return object FileUploadResult result = new FileUploadResult(); // Get a input stream of the file on the phone InputStream fileInputStream = getPathFromUri(file); HttpURLConnection conn = null; DataOutputStream dos = null; int bytesRead, bytesAvailable, bufferSize; long totalBytes; byte[] buffer; int maxBufferSize = 8096; //------------------ CLIENT REQUEST // open a URL connection to the server URL url = new URL(server); // Open a HTTP connection to the URL based on protocol if (url.getProtocol().toLowerCase().equals("https")) { // Using standard HTTPS connection. Will not allow self signed certificate if (!trustEveryone) { conn = (HttpsURLConnection) url.openConnection(); } // Use our HTTPS connection that blindly trusts everyone. // This should only be used in debug environments else { // Setup the HTTPS connection class to trust everyone trustAllHosts(); HttpsURLConnection https = (HttpsURLConnection) url.openConnection(); // Save the current hostnameVerifier defaultHostnameVerifier = https.getHostnameVerifier(); // Setup the connection not to verify hostnames https.setHostnameVerifier(DO_NOT_VERIFY); conn = https; } } // Return a standard HTTP conneciton else { conn = (HttpURLConnection) url.openConnection(); } // Allow Inputs conn.setDoInput(true); // Allow Outputs conn.setDoOutput(true); // Don't use a cached copy. conn.setUseCaches(false); // Use a post method. conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDRY); // Set the cookies on the response String cookie = CookieManager.getInstance().getCookie(server); if (cookie != null) { conn.setRequestProperty("Cookie", cookie); } dos = new DataOutputStream(conn.getOutputStream()); // Send any extra parameters try { for (Iterator iter = params.keys(); iter.hasNext();) { Object key = iter.next(); dos.writeBytes(LINE_START + BOUNDRY + LINE_END); dos.writeBytes("Content-Disposition: form-data; name=\"" + key.toString() + "\"; "); dos.writeBytes(LINE_END + LINE_END); dos.writeBytes(params.getString(key.toString())); dos.writeBytes(LINE_END); } } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); } dos.writeBytes(LINE_START + BOUNDRY + LINE_END); dos.writeBytes("Content-Disposition: form-data; name=\"" + fileKey + "\";" + " filename=\"" + fileName + "\"" + LINE_END); dos.writeBytes("Content-Type: " + mimeType + LINE_END); dos.writeBytes(LINE_END); // 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); totalBytes = 0; while (bytesRead > 0) { totalBytes += bytesRead; result.setBytesSent(totalBytes); 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(LINE_END); dos.writeBytes(LINE_START + BOUNDRY + LINE_START + LINE_END); // close streams fileInputStream.close(); dos.flush(); dos.close(); //------------------ read the SERVER RESPONSE StringBuffer responseString = new StringBuffer(""); DataInputStream inStream = new DataInputStream(conn.getInputStream()); String line; while ((line = inStream.readLine()) != null) { responseString.append(line); } Log.d(LOG_TAG, "got response from server"); Log.d(LOG_TAG, responseString.toString()); // send request and retrieve response result.setResponseCode(conn.getResponseCode()); result.setResponse(responseString.toString()); inStream.close(); conn.disconnect(); // Revert back to the proper verifier and socket factories if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) { ((HttpsURLConnection) conn).setHostnameVerifier(defaultHostnameVerifier); HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory); } return result; }
From source file:com.jaspersoft.studio.statistics.UsageManager.java
/** * Send the statistics to the defined server. They are read from the properties filed and converted into a JSON * string. Then this string is sent to the server as a post parameter named data *///from w w w.ja v a 2 s . co m protected void sendStatistics() { BufferedReader responseReader = null; DataOutputStream postWriter = null; try { if (!STATISTICS_SERVER_URL.trim().isEmpty()) { URL obj = new URL(STATISTICS_SERVER_URL); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // add request header con.setRequestMethod("POST"); //$NON-NLS-1$ con.setRequestProperty("User-Agent", "Mozilla/5.0"); //$NON-NLS-1$ //$NON-NLS-2$ con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); //$NON-NLS-1$ //$NON-NLS-2$ // Read and convert the statistics into a JSON string UsagesContainer container = new UsagesContainer(getAppDataFolder().getName()); boolean fileChanged = false; synchronized (UsageManager.this) { Properties prop = getStatisticsContainer(); for (Object key : new ArrayList<Object>(prop.keySet())) { try { String[] id_category = key.toString().split(Pattern.quote(ID_CATEGORY_SEPARATOR)); String value = prop.getProperty(key.toString(), "0"); int usageNumber = Integer.parseInt(value); //$NON-NLS-1$ String version = getVersion(); //Check if the id contains the version if (id_category.length == 3) { version = id_category[2]; } else { //Old structure, remove the old entry and insert the new fixed one //this is a really limit case and should almost never happen prop.remove(key); String fixed_key = id_category[0] + ID_CATEGORY_SEPARATOR + id_category[1] + ID_CATEGORY_SEPARATOR + version; prop.setProperty(fixed_key, value); fileChanged = true; } container.addStat( new UsageStatistic(id_category[0], id_category[1], version, usageNumber)); } catch (Exception ex) { //if a key is invalid remove it ex.printStackTrace(); prop.remove(key); fileChanged = true; } } } if (fileChanged) { //The statistics file was changed, maybe a fix or an invalid property removed //write it corrected on the disk writeStatsToDisk.cancel(); writeStatsToDisk.setPriority(Job.SHORT); writeStatsToDisk.schedule(MINIMUM_WAIT_TIME); } ObjectMapper mapper = new ObjectMapper(); String serializedData = mapper.writeValueAsString(container); // Send post request with the JSON string as the data parameter String urlParameters = "data=" + serializedData; //$NON-NLS-1$ con.setDoOutput(true); postWriter = new DataOutputStream(con.getOutputStream()); postWriter.writeBytes(urlParameters); postWriter.flush(); int responseCode = con.getResponseCode(); responseReader = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = responseReader.readLine()) != null) { response.append(inputLine); } // Update the upload time if (responseCode == 200 && ModelUtils.safeEquals(response.toString(), "ok")) { setInstallationInfo(TIMESTAMP_INFO, String.valueOf(getCurrentTime())); } else { //print result System.out.println("Response error: " + response.toString()); } } } catch (Exception ex) { ex.printStackTrace(); JaspersoftStudioPlugin.getInstance().logError(Messages.UsageManager_errorStatUpload, ex); } finally { FileUtils.closeStream(postWriter); FileUtils.closeStream(responseReader); } }
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 w ww . j a v a2 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.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); }/* w w w . j a v a 2 s.co 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:com.cognizant.trumobi.PersonaLauncher.java
private static void writeConfiguration(Context context, LocaleConfiguration configuration) { DataOutputStream out = null; try {/*from w w w . j ava 2 s. c o m*/ out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE)); out.writeUTF(configuration.locale); out.writeInt(configuration.mcc); out.writeInt(configuration.mnc); out.flush(); } catch (FileNotFoundException e) { // Ignore } catch (IOException e) { // noinspection ResultOfMethodCallIgnored context.getFileStreamPath(PREFERENCES).delete(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // Ignore } } } }
From source file:org.motechproject.mobile.web.OXDFormUploadServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w. jav a 2 s . co m*/ * * @param request * servlet request * @param response * servlet response * @throws ServletException * if a servlet-specific error occurs * @throws IOException * if an I/O error occurs */ @RequestMapping(method = RequestMethod.POST) public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long startTime = System.currentTimeMillis(); IMPService impService = (IMPService) appCtx.getBean("impService"); StudyProcessor studyProcessor = (StudyProcessor) appCtx.getBean("studyProcessor"); InputStream input = request.getInputStream(); OutputStream output = response.getOutputStream(); ZOutputStream zOutput = null; // Wrap the streams for compression // Wrap the streams so for logical types DataInputStream dataInput = null; DataOutputStream dataOutput = null; // Set the MIME type so clients don't misinterpret response.setContentType("application/octet-stream"); try { zOutput = new ZOutputStream(output, JZlib.Z_BEST_COMPRESSION); dataInput = new DataInputStream(input); dataOutput = new DataOutputStream(zOutput); if (rawUploadLog.isInfoEnabled()) { byte[] rawPayload = IOUtils.toByteArray(dataInput); String hexEncodedPayload = Hex.encodeHexString(rawPayload); rawUploadLog.info(hexEncodedPayload); // Replace the original input stream with one using read payload dataInput.close(); dataInput = new DataInputStream(new ByteArrayInputStream(rawPayload)); } String name = dataInput.readUTF(); String password = dataInput.readUTF(); String serializer = dataInput.readUTF(); String locale = dataInput.readUTF(); byte action = dataInput.readByte(); // TODO Authentication of usename and password. Possible M6 // enhancement log.info("uploading: name=" + name + ", password=" + password + ", serializer=" + serializer + ", locale=" + locale + ", action=" + action); EpihandyXformSerializer serObj = new EpihandyXformSerializer(); serObj.addDeserializationListener(studyProcessor); try { Map<Integer, String> formVersionMap = formService.getXForms(); serObj.deserializeStudiesWithEvents(dataInput, formVersionMap); } catch (FormNotFoundException fne) { String msg = "failed to deserialize forms: "; log.error(msg + fne.getMessage()); dataOutput.writeByte(ResponseHeader.STATUS_FORMS_STALE); response.setStatus(HttpServletResponse.SC_OK); return; } catch (Exception e) { String msg = "failed to deserialize forms"; log.error(msg, e); dataOutput.writeByte(ResponseHeader.STATUS_ERROR); response.setStatus(HttpServletResponse.SC_OK); return; } String[][] studyForms = studyProcessor.getConvertedStudies(); int numForms = studyProcessor.getNumForms(); log.debug("upload contains: studies=" + studyForms.length + ", forms=" + numForms); // Starting processing here, only process until we run out of time int processedForms = 0; int faultyForms = 0; if (studyForms != null && numForms > 0) { formprocessing: for (int i = 0; i < studyForms.length; i++) { for (int j = 0; j < studyForms[i].length; j++, processedForms++) { if (maxProcessingTime > 0 && System.currentTimeMillis() - startTime > maxProcessingTime) break formprocessing; try { studyForms[i][j] = impService.processXForm(studyForms[i][j]); } catch (Exception ex) { log.error("processing form failed", ex); studyForms[i][j] = ex.getMessage(); } if (!impService.getFormProcessSuccess().equalsIgnoreCase(studyForms[i][j])) { faultyForms++; } } } } // Write out usual upload response dataOutput.writeByte(ResponseHeader.STATUS_SUCCESS); dataOutput.writeInt(processedForms); dataOutput.writeInt(faultyForms); for (int s = 0; s < studyForms.length; s++) { for (int f = 0; f < studyForms[s].length; f++) { if (!impService.getFormProcessSuccess().equalsIgnoreCase(studyForms[s][f])) { dataOutput.writeByte((byte) s); dataOutput.writeShort((short) f); dataOutput.writeUTF(studyForms[s][f]); } } } response.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { log.error("failure during upload", e); } finally { if (dataOutput != null) dataOutput.flush(); if (zOutput != null) zOutput.finish(); response.flushBuffer(); } }