List of usage examples for java.io DataOutputStream close
@Override public void close() throws IOException
From source file:com.alexholmes.hadooputils.test.TextIOJobBuilder.java
/** * Gathers all the inputs buffered by calls to {@link #addInput(String)} or * {@link #addInput(String...)} and writes them to the input directory, in * preparation for running the MapReduce job. * * @return a reference to this object//w ww . j a va2s . com * @throws IOException if something goes wrong */ public TextIOJobBuilder writeInputs() throws IOException { if (fs.exists(outputPath)) { fs.delete(outputPath, true); } if (fs.exists(inputPath)) { fs.delete(inputPath, true); } fs.mkdirs(inputPath); DataOutputStream stream = fs.create(new Path(inputPath, "part-0")); IOUtils.writeLines(inputs, String.format("%n"), stream); stream.close(); return this; }
From source file:org.fosstrak.ale.server.type.FileSubscriberOutputChannel.java
/** * This method writes ec reports to a file. * /* w w w. j a v a 2 s .com*/ * @param reports to write to the file * @throws ImplementationException if an implementation exception occures */ private void writeNotificationToFile(ECReports reports) throws ImplementationException { // append reports as xml to file LOG.debug("Append reports '" + reports.getSpecName() + "' as xml to file '" + getPath() + "'."); File file = getFile(); // create file if it does not already exists if (!file.exists() || !file.isFile()) { try { file.createNewFile(); } catch (IOException e) { throw new ImplementationException("Could not create new file '" + getPath() + "'.", e); } } try { // open streams FileOutputStream fileOutputStream = new FileOutputStream(file, true); DataOutputStream dataOutputStream = new DataOutputStream(fileOutputStream); // append reports as xml to file dataOutputStream.writeBytes(getPrettyXml(reports)); dataOutputStream.writeBytes("\n\n"); dataOutputStream.flush(); // close streams dataOutputStream.close(); fileOutputStream.close(); } catch (IOException e) { throw new ImplementationException("Could not write to file '" + getPath() + "'.", e); } }
From source file:com.towerlabs.yildizyemek.ViewPagerDinner.java
public boolean fileIsExist() throws IOException, InterruptedException, ExecutionException, NotFoundException, JSONException, ParseException { MainActivity.fileName = MainActivity.dateFormatFile.format(new Date()); fileDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + MainActivity.folderName); file = new File(fileDir, MainActivity.fileName); if (!fileDir.exists() && !fileDir.isDirectory()) { fileDir.mkdirs();/*from ww w . jav a 2 s . c o m*/ } if (!file.exists()) { Log.d("girdimi", "girdi"); httpTask.execute(urls[0]); rawText = httpTask.get(); if (httpTask.isError()) { if (!correctDate(rawText).equalsIgnoreCase(MainActivity.fileName)) { MainActivity.errorDialog(getResources().getString(R.string.new_list_error_msg)); return false; } FileOutputStream fo; DataOutputStream dos; fo = new FileOutputStream(file); dos = new DataOutputStream(fo); dos.writeUTF(rawText); fo.close(); dos.close(); fo = null; dos = null; return true; } else { MainActivity.errorDialog(getResources().getString(R.string.connection_error_msg)); return false; } } return true; }
From source file:copter.ServerConnection.java
/** * this function make a post request to server and get response it sends * copter IP Address, Unique ID and Name * * @param ipAddress/* w ww .java 2s.c om*/ */ private String registerCopterOnServer(String ipAddress) { String serverHost = Config.getInstance().getString("main", "server_host"); String copter_unique_id = Config.getInstance().getString("copter", "unique_id"); String copter_name = Config.getInstance().getString("copter", "name"); URL url; try { url = new URL("http://" + serverHost + Config.getInstance().getString("main", "register_copter_url")); HttpURLConnection con = (HttpURLConnection) url.openConnection(); //add reuqest header con.setRequestMethod("POST"); //con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "copter_ip=" + ipAddress + "&unique_id=" + copter_unique_id + "&name=" + copter_name; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); logger.log("\nSending 'POST' request to URL : " + url); logger.log("Post parameters : " + urlParameters); logger.log("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); String jsonResponse = response.toString(); JSONParser parser = new JSONParser(); Object obj = parser.parse(jsonResponse); JSONObject jsonObj = (JSONObject) obj; String status = (String) jsonObj.get("status"); if (status != null && status.equals("ok")) { return "ok"; } else { return (String) jsonObj.get("message"); } } catch (Exception ex) { return ex.getMessage(); } }
From source file:edu.ku.brc.specify.toycode.ResFileCompare.java
/** * Save as Ascii.// ww w . j a va 2s.c om */ public boolean save(final File file, final Vector<String> list) { FileOutputStream fos = null; DataOutputStream dos = null; try { fos = new FileOutputStream(file); dos = new DataOutputStream(fos); for (String line : list) { String str = line + '\n'; dos.writeBytes(str); } dos.flush(); dos.close(); return true; } catch (Exception e) { System.out.println("e: " + e); } return false; }
From source file:io.teak.sdk.Request.java
@Override public void run() { HttpsURLConnection connection = null; SecretKeySpec keySpec = new SecretKeySpec(this.session.appConfiguration.apiKey.getBytes(), "HmacSHA256"); String requestBody;/*from ww w .j av a2s . c o m*/ String hostnameForEndpoint = this.hostname; if (hostnameForEndpoint == null) { hostnameForEndpoint = this.session.remoteConfiguration.getHostnameForEndpoint(this.endpoint); } try { ArrayList<String> payloadKeys = new ArrayList<>(this.payload.keySet()); Collections.sort(payloadKeys); StringBuilder builder = new StringBuilder(); for (String key : payloadKeys) { Object value = this.payload.get(key); if (value != null) { String valueString; if (value instanceof Map) { valueString = new JSONObject((Map) value).toString(); } else if (value instanceof Array) { valueString = new JSONArray(Collections.singletonList(value)).toString(); } else if (value instanceof Collection) { valueString = new JSONArray((Collection) value).toString(); } else { valueString = value.toString(); } builder.append(key).append("=").append(valueString).append("&"); } else { Log.e(LOG_TAG, "Value for key: " + key + " is null."); } } builder.deleteCharAt(builder.length() - 1); String stringToSign = "POST\n" + hostnameForEndpoint + "\n" + this.endpoint + "\n" + builder.toString(); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(keySpec); byte[] result = mac.doFinal(stringToSign.getBytes()); builder = new StringBuilder(); for (String key : payloadKeys) { Object value = this.payload.get(key); String valueString; if (value instanceof Map) { valueString = new JSONObject((Map) value).toString(); } else if (value instanceof Array) { valueString = new JSONArray(Collections.singletonList(value)).toString(); } else if (value instanceof Collection) { valueString = new JSONArray((Collection) value).toString(); } else { valueString = value.toString(); } builder.append(key).append("=").append(URLEncoder.encode(valueString, "UTF-8")).append("&"); } builder.append("sig=") .append(URLEncoder.encode(Base64.encodeToString(result, Base64.NO_WRAP), "UTF-8")); requestBody = builder.toString(); } catch (Exception e) { Log.e(LOG_TAG, "Error signing payload: " + Log.getStackTraceString(e)); return; } try { if (Teak.isDebug) { Log.d(LOG_TAG, "Submitting request to '" + this.endpoint + "': " + new JSONObject(this.payload).toString(2)); } URL url = new URL("https://" + hostnameForEndpoint + this.endpoint); connection = (HttpsURLConnection) url.openConnection(); connection.setRequestProperty("Accept-Charset", "UTF-8"); connection.setUseCaches(false); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(requestBody.getBytes().length)); // Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(requestBody); wr.flush(); wr.close(); // Get Response InputStream is; if (connection.getResponseCode() < 400) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); } BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuilder response = new StringBuilder(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); if (Teak.isDebug) { String responseText = response.toString(); try { responseText = new JSONObject(response.toString()).toString(2); } catch (Exception ignored) { } Log.d(LOG_TAG, "Reply from '" + this.endpoint + "': " + responseText); } // For extending classes done(connection.getResponseCode(), response.toString()); } catch (Exception e) { Log.e(LOG_TAG, Log.getStackTraceString(e)); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:com.mendhak.gpslogger.senders.googledrive.GoogleDriveJob.java
private String createEmptyFile(String authToken, String fileName, String mimeType, String parentFolderId) { String fileId = null;/*from w ww . ja v a2s .co m*/ HttpURLConnection conn = null; String createFileUrl = "https://www.googleapis.com/drive/v2/files"; String createFilePayload = " {\n" + " \"title\": \"" + fileName + "\",\n" + " \"mimeType\": \"" + mimeType + "\",\n" + " \"parents\": [\n" + " {\n" + " \"id\": \"" + parentFolderId + "\"\n" + " }\n" + " ]\n" + " }"; try { URL url = new URL(createFileUrl); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", "GPSLogger for Android"); conn.setRequestProperty("Authorization", "Bearer " + authToken); conn.setRequestProperty("Content-Type", "application/json"); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setConnectTimeout(10000); conn.setReadTimeout(30000); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(createFilePayload); wr.flush(); wr.close(); fileId = null; String fileMetadata = Streams.getStringFromInputStream(conn.getInputStream()); JSONObject fileMetadataJson = new JSONObject(fileMetadata); fileId = fileMetadataJson.getString("id"); LOG.debug("File created with ID " + fileId + " of type " + mimeType); } catch (Exception e) { LOG.error("Could not create file", e); } finally { if (conn != null) { conn.disconnect(); } } return fileId; }
From source file:com.ricemap.spateDB.core.RTreeGridRecordWriter.java
/** * Closes a cell by writing all outstanding objects and closing current file. * Then, the file is read again, an RTree is built on top of it and, finally, * the file is written again with the RTree built. */// ww w . j a v a 2 s. c o m @Override protected Path flushAllEntries(Path intermediateCellPath, OutputStream intermediateCellStream, Path finalCellPath) throws IOException { // Close stream to current intermediate file. intermediateCellStream.close(); // Read all data of the written file in memory byte[] cellData = new byte[(int) new File(intermediateCellPath.toUri().getPath()).length()]; InputStream cellIn = new FileInputStream(intermediateCellPath.toUri().getPath()); cellIn.read(cellData); cellIn.close(); // Build an RTree over the elements read from file RTree<S> rtree = new RTree<S>(); rtree.setStockObject(stockObject); // It should create a new stream DataOutputStream cellStream = (DataOutputStream) createFinalCellStream(finalCellPath); cellStream.writeLong(SpatialSite.RTreeFileMarker); int degree = 4096 / RTree.NodeSize; rtree.bulkLoadWrite(cellData, 0, cellData.length, degree, cellStream, fastRTree, columnarStorage); cellStream.close(); cellData = null; // To allow GC to collect it return finalCellPath; }
From source file:mvm.rya.accumulo.pig.AccumuloStorage.java
@Override public WritableComparable<?> getSplitComparable(InputSplit inputSplit) throws IOException { //cannot get access to the range directly AccumuloInputFormat.RangeInputSplit rangeInputSplit = (AccumuloInputFormat.RangeInputSplit) inputSplit; ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(baos); rangeInputSplit.write(out);//from ww w.j a v a 2s . c om out.close(); DataInputStream stream = new DataInputStream(new ByteArrayInputStream(baos.toByteArray())); Range range = new Range(); range.readFields(stream); stream.close(); return range; }
From source file:MainFrame.HttpCommunicator.java
public void setCombos(JComboBox comboGroups, JComboBox comboDates, LessonTableModel tableModel) throws MalformedURLException, IOException { BufferedReader in = null;//from ww w.j av a 2s. c om if (SingleDataHolder.getInstance().isProxyActivated) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword)); HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider) .build(); HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress, SingleDataHolder.getInstance().proxyPort); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php"); post.setConfig(config); StringBody head = new StringBody(new JSONObject().toString(), ContentType.TEXT_PLAIN); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("apideskviewer.getAllLessons", head); HttpEntity entity = builder.build(); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String response = client.execute(post, responseHandler); System.out.println("responseBody : " + response); InputStream stream = new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8)); in = new BufferedReader(new InputStreamReader(stream)); } else { URL obj = new URL(SingleDataHolder.getInstance().hostAdress); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "apideskviewer.getAllLessons={}"; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + SingleDataHolder.getInstance().hostAdress); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); in = new BufferedReader(new InputStreamReader(con.getInputStream())); } JSONParser parser = new JSONParser(); try { Object parsedResponse = parser.parse(in); JSONObject jsonParsedResponse = (JSONObject) parsedResponse; for (int i = 0; i < jsonParsedResponse.size(); i++) { String s = (String) jsonParsedResponse.get(String.valueOf(i)); String[] splittedPath = s.split("/"); DateFormat DF = new SimpleDateFormat("yyyyMMdd"); Date d = DF.parse(splittedPath[1].replaceAll(".bin", "")); Lesson lesson = new Lesson(splittedPath[0], d, false); String group = splittedPath[0]; String date = new SimpleDateFormat("dd.MM.yyyy").format(d); if (((DefaultComboBoxModel) comboGroups.getModel()).getIndexOf(group) == -1) { comboGroups.addItem(group); } if (((DefaultComboBoxModel) comboDates.getModel()).getIndexOf(date) == -1) { comboDates.addItem(date); } tableModel.addLesson(lesson); } } catch (Exception ex) { } }