List of usage examples for java.io DataOutputStream close
@Override public void close() throws IOException
From source file:net.bashtech.geobot.BotManager.java
public static String postRemoteDataStrawpoll(String urlString) { String line = ""; try {//from w w w. j a v a 2 s. c om HttpURLConnection c = (HttpURLConnection) (new URL("http://strawpoll.me/api/v2/polls") .openConnection()); c.setRequestMethod("POST"); c.setRequestProperty("Content-Type", "application/json"); c.setRequestProperty("User-Agent", "CB2"); c.setDoOutput(true); c.setDoInput(true); c.setUseCaches(false); String queryString = urlString; c.setRequestProperty("Content-Length", Integer.toString(queryString.length())); DataOutputStream wr = new DataOutputStream(c.getOutputStream()); wr.writeBytes(queryString); wr.flush(); wr.close(); Scanner inStream = new Scanner(c.getInputStream()); while (inStream.hasNextLine()) line += (inStream.nextLine()); inStream.close(); System.out.println(line); try { JSONParser parser = new JSONParser(); Object obj = parser.parse(line); JSONObject jsonObject = (JSONObject) obj; line = (Long) jsonObject.get("id") + ""; } catch (Exception e) { e.printStackTrace(); } } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } return line; }
From source file:com.juhnowski.sanskrvar.Main.java
public Entry checkWord(String word) { StringBuilder sb = new StringBuilder(); sb.append("http://www.sanskrit-lexicon.uni-koeln.de/scans/WILScan/2014/web/webtc/getword.php?key="); sb.append(word);//from w w w.j a v a 2 s . c o m sb.append("&filter=roman&noLit=off&transLit=hk"); String targetURL = sb.toString(); String urlParameters = ""; HttpURLConnection connection = null; try { //Create connection URL url = new URL(targetURL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/xhr"); connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(urlParameters); wr.close(); InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); StringBuilder response = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); String s = response.toString(); if (!s.contains("<h2>not found:")) { return new Entry(word, s); } else { return null; } } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return null; }
From source file:com.gagein.crawler.FileDownLoader.java
/** * ? filePath ???/* ww w . j av a2s . c om*/ */ private void saveToLocal(byte[] data, String filePath) { try { System.out.println("========SaveToLocal========filePath===" + filePath); DataOutputStream out = new DataOutputStream(new FileOutputStream(new File(filePath))); for (int i = 0; i < data.length; i++) out.write(data[i]); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:db.dao.ArticleDao.java
public void deletebyId(String deleteId) { try {//from www.j a v a2 s . co m String url = this.checkIfLocal("article/delete"); URL obj = new URL(url); 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 = "id=" + URLEncoder.encode(deleteId); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); //print result System.out.println(responseCode); } catch (MalformedURLException ex) { Logger.getLogger(ArticleDao.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ArticleDao.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:edu.umn.cs.spatialHadoop.visualization.MultilevelPlot.java
private static void plotLocal(Path[] inFiles, final Path outPath, final Class<? extends Plotter> plotterClass, final OperationsParams params) throws IOException, InterruptedException, ClassNotFoundException { final boolean vflip = params.getBoolean("vflip", true); OperationsParams mbrParams = new OperationsParams(params); mbrParams.setBoolean("background", false); final Rectangle inputMBR = params.get("mbr") != null ? params.getShape("mbr").getMBR() : FileMBR.fileMBR(inFiles, mbrParams); OperationsParams.setShape(params, InputMBR, inputMBR); // Retrieve desired output image size and keep aspect ratio if needed int tileWidth = params.getInt("tilewidth", 256); int tileHeight = params.getInt("tileheight", 256); // Adjust width and height if aspect ratio is to be kept if (params.getBoolean("keepratio", true)) { // Expand input file to a rectangle for compatibility with the pyramid // structure if (inputMBR.getWidth() > inputMBR.getHeight()) { inputMBR.y1 -= (inputMBR.getWidth() - inputMBR.getHeight()) / 2; inputMBR.y2 = inputMBR.y1 + inputMBR.getWidth(); } else {/*www. j a v a2 s .c o m*/ inputMBR.x1 -= (inputMBR.getHeight() - inputMBR.getWidth()) / 2; inputMBR.x2 = inputMBR.x1 + inputMBR.getHeight(); } } String outFName = outPath.getName(); int extensionStart = outFName.lastIndexOf('.'); final String extension = extensionStart == -1 ? ".png" : outFName.substring(extensionStart); // Start reading input file Vector<InputSplit> splits = new Vector<InputSplit>(); final SpatialInputFormat3<Rectangle, Shape> inputFormat = new SpatialInputFormat3<Rectangle, Shape>(); for (Path inFile : inFiles) { FileSystem inFs = inFile.getFileSystem(params); if (!OperationsParams.isWildcard(inFile) && inFs.exists(inFile) && !inFs.isDirectory(inFile)) { if (SpatialSite.NonHiddenFileFilter.accept(inFile)) { // Use the normal input format splitter to add this non-hidden file Job job = Job.getInstance(params); SpatialInputFormat3.addInputPath(job, inFile); splits.addAll(inputFormat.getSplits(job)); } else { // A hidden file, add it immediately as one split // This is useful if the input is a hidden file which is automatically // skipped by FileInputFormat. We need to plot a hidden file for the case // of plotting partition boundaries of a spatial index splits.add(new FileSplit(inFile, 0, inFs.getFileStatus(inFile).getLen(), new String[0])); } } else { Job job = Job.getInstance(params); SpatialInputFormat3.addInputPath(job, inFile); splits.addAll(inputFormat.getSplits(job)); } } try { Plotter plotter = plotterClass.newInstance(); plotter.configure(params); String[] strLevels = params.get("levels", "7").split("\\.\\."); int minLevel, maxLevel; if (strLevels.length == 1) { minLevel = 0; maxLevel = Integer.parseInt(strLevels[0]); } else { minLevel = Integer.parseInt(strLevels[0]); maxLevel = Integer.parseInt(strLevels[1]); } GridInfo bottomGrid = new GridInfo(inputMBR.x1, inputMBR.y1, inputMBR.x2, inputMBR.y2); bottomGrid.rows = bottomGrid.columns = 1 << maxLevel; TileIndex key = new TileIndex(); // All canvases in the pyramid, one per tile Map<TileIndex, Canvas> canvases = new HashMap<TileIndex, Canvas>(); for (InputSplit split : splits) { FileSplit fsplit = (FileSplit) split; RecordReader<Rectangle, Iterable<Shape>> reader = inputFormat.createRecordReader(fsplit, null); if (reader instanceof SpatialRecordReader3) { ((SpatialRecordReader3) reader).initialize(fsplit, params); } else if (reader instanceof RTreeRecordReader3) { ((RTreeRecordReader3) reader).initialize(fsplit, params); } else if (reader instanceof HDFRecordReader) { ((HDFRecordReader) reader).initialize(fsplit, params); } else { throw new RuntimeException("Unknown record reader"); } while (reader.nextKeyValue()) { Rectangle partition = reader.getCurrentKey(); if (!partition.isValid()) partition.set(inputMBR); Iterable<Shape> shapes = reader.getCurrentValue(); for (Shape shape : shapes) { Rectangle shapeMBR = shape.getMBR(); if (shapeMBR == null) continue; java.awt.Rectangle overlappingCells = bottomGrid.getOverlappingCells(shapeMBR); // Iterate over levels from bottom up for (key.level = maxLevel; key.level >= minLevel; key.level--) { for (key.x = overlappingCells.x; key.x < overlappingCells.x + overlappingCells.width; key.x++) { for (key.y = overlappingCells.y; key.y < overlappingCells.y + overlappingCells.height; key.y++) { Canvas canvas = canvases.get(key); if (canvas == null) { Rectangle tileMBR = new Rectangle(); int gridSize = 1 << key.level; tileMBR.x1 = (inputMBR.x1 * (gridSize - key.x) + inputMBR.x2 * key.x) / gridSize; tileMBR.x2 = (inputMBR.x1 * (gridSize - (key.x + 1)) + inputMBR.x2 * (key.x + 1)) / gridSize; tileMBR.y1 = (inputMBR.y1 * (gridSize - key.y) + inputMBR.y2 * key.y) / gridSize; tileMBR.y2 = (inputMBR.y1 * (gridSize - (key.y + 1)) + inputMBR.y2 * (key.y + 1)) / gridSize; canvas = plotter.createCanvas(tileWidth, tileHeight, tileMBR); canvases.put(key.clone(), canvas); } plotter.plot(canvas, shape); } } // Update overlappingCells for the higher level int updatedX1 = overlappingCells.x / 2; int updatedY1 = overlappingCells.y / 2; int updatedX2 = (overlappingCells.x + overlappingCells.width - 1) / 2; int updatedY2 = (overlappingCells.y + overlappingCells.height - 1) / 2; overlappingCells.x = updatedX1; overlappingCells.y = updatedY1; overlappingCells.width = updatedX2 - updatedX1 + 1; overlappingCells.height = updatedY2 - updatedY1 + 1; } } } reader.close(); } // Done with all splits. Write output to disk LOG.info("Done with plotting. Now writing the output"); final FileSystem outFS = outPath.getFileSystem(params); LOG.info("Writing default empty image"); // Write a default empty image to be displayed for non-generated tiles BufferedImage emptyImg = new BufferedImage(tileWidth, tileHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g = new SimpleGraphics(emptyImg); g.setBackground(new Color(0, 0, 0, 0)); g.clearRect(0, 0, tileWidth, tileHeight); g.dispose(); // Write HTML file to browse the mutlielvel image OutputStream out = outFS.create(new Path(outPath, "default.png")); ImageIO.write(emptyImg, "png", out); out.close(); // Add an HTML file that visualizes the result using Google Maps LOG.info("Writing the HTML viewer file"); LineReader templateFileReader = new LineReader( MultilevelPlot.class.getResourceAsStream("/zoom_view.html")); PrintStream htmlOut = new PrintStream(outFS.create(new Path(outPath, "index.html"))); Text line = new Text(); while (templateFileReader.readLine(line) > 0) { String lineStr = line.toString(); lineStr = lineStr.replace("#{TILE_WIDTH}", Integer.toString(tileWidth)); lineStr = lineStr.replace("#{TILE_HEIGHT}", Integer.toString(tileHeight)); lineStr = lineStr.replace("#{MAX_ZOOM}", Integer.toString(maxLevel)); lineStr = lineStr.replace("#{MIN_ZOOM}", Integer.toString(minLevel)); lineStr = lineStr.replace("#{TILE_URL}", "'tile-' + zoom + '-' + coord.x + '-' + coord.y + '" + extension + "'"); htmlOut.println(lineStr); } templateFileReader.close(); htmlOut.close(); // Write the tiles final Entry<TileIndex, Canvas>[] entries = canvases.entrySet().toArray(new Map.Entry[canvases.size()]); // Clear the hash map to save memory as it is no longer needed canvases.clear(); int parallelism = params.getInt("parallel", Runtime.getRuntime().availableProcessors()); Parallel.forEach(entries.length, new RunnableRange<Object>() { @Override public Object run(int i1, int i2) { boolean output = params.getBoolean("output", true); try { Plotter plotter = plotterClass.newInstance(); plotter.configure(params); for (int i = i1; i < i2; i++) { Map.Entry<TileIndex, Canvas> entry = entries[i]; TileIndex key = entry.getKey(); if (vflip) key.y = ((1 << key.level) - 1) - key.y; Path imagePath = new Path(outPath, key.getImageFileName() + extension); // Write this tile to an image DataOutputStream outFile = output ? outFS.create(imagePath) : new DataOutputStream(new NullOutputStream()); plotter.writeImage(entry.getValue(), outFile, vflip); outFile.close(); // Remove entry to allows GC to collect it entries[i] = null; } return null; } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }, parallelism); } catch (InstantiationException e) { throw new RuntimeException("Error creating rastierizer", e); } catch (IllegalAccessException e) { throw new RuntimeException("Error creating rastierizer", e); } }
From source file:lk.appzone.client.MchoiceAventuraSmsSender.java
private void sendRequest(String urlParameters, HttpURLConnection connection) throws IOException { if (logger.isDebugEnabled()) { logger.debug("sending the request: " + urlParameters); }//ww w.j a v a 2s. c o m //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); }
From source file:edu.stanford.muse.slant.CustomSearchHelper.java
/** returns an oauth token for the user's CSE. returns null if login failed. */ public static String authenticate(String login, String password) { //System.out.println("About to post\nURL: "+target+ "content: " + content); String authToken = null;/*from ww w. j a va 2s .c o m*/ String response = ""; try { URL url = new URL("https://www.google.com/accounts/ClientLogin"); URLConnection conn = url.openConnection(); // Set connection parameters. conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); // Make server believe we are form data... conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); // TODO: escape password, we'll fail if password has & // login = "musetestlogin1"; // password = "whowonthelottery"; String content = "accountType=HOSTED_OR_GOOGLE&Email=" + login + "&Passwd=" + password + "&service=cprose&source=muse.chrome.extension"; out.writeBytes(content); out.flush(); out.close(); // Read response from the input stream. BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String temp; while ((temp = in.readLine()) != null) { response += temp + "\n"; } temp = null; in.close(); log.info("Obtaining auth token: Server response:\n'" + response + "'"); String delimiter = "Auth="; /* given string will be split by the argument delimiter provided. */ String[] token = response.split(delimiter); authToken = token[1]; authToken = authToken.trim(); authToken = authToken.replaceAll("(\\r|\\n)", ""); log.info("auth token: " + authToken); return authToken; } catch (Exception e) { log.warn("Unable to authorize: " + e.getMessage()); return null; } }
From source file:com.example.jarida.http.AsyncConnection.java
@Override public String doInBackground(String... params) { final String method = params[0]; final String urlString = params[1]; final StringBuilder builder = new StringBuilder(); try {//from w w w.ja va2 s .c o m final URL url = new URL(urlString); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(method); if (method.equals(METHOD_POST)) { final String urlParams = params[2]; conn.setRequestProperty(HTTP.CONTENT_LEN, "" + Integer.toString(urlParams.getBytes().length)); System.out.println(urlParams); // Send request final DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(urlParams); wr.flush(); wr.close(); } // Get Response final InputStream is = conn.getInputStream(); final BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; while ((line = rd.readLine()) != null) { builder.append(line); } rd.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); }
From source file:com.cloudera.seismic.segy.SegyUnloader.java
@Override public int run(String[] args) throws Exception { Options options = new Options(); options.addOption("input", true, "SU sequence files to export from Hadoop"); options.addOption("output", true, "The local SU file to write"); // Parse the commandline and check for required arguments. CommandLine cmdLine = new PosixParser().parse(options, args, false); if (!cmdLine.hasOption("input") || !cmdLine.hasOption("output")) { System.out.println("Mising required input/output arguments"); new HelpFormatter().printHelp("SegyUnloader", options); System.exit(1);// ww w . j a va 2 s . c o m } Configuration conf = getConf(); FileSystem hdfs = FileSystem.get(conf); Path inputPath = new Path(cmdLine.getOptionValue("input")); if (!hdfs.exists(inputPath)) { System.out.println("Input path does not exist"); System.exit(1); } PathFilter pf = new PathFilter() { @Override public boolean accept(Path path) { return !path.getName().startsWith("_"); } }; DataOutputStream os = new DataOutputStream(new FileOutputStream(cmdLine.getOptionValue("output"))); for (FileStatus fs : hdfs.listStatus(inputPath, pf)) { write(fs.getPath(), os, conf); } os.close(); return 0; }
From source file:com.csipsimple.backup.SipProfilesHelper.java
@Override public void writeNewStateDescription(ParcelFileDescriptor newState) { long fileModified = databaseFile.lastModified(); try {/*from w ww. j a v a 2 s . c o m*/ FileOutputStream outstream = new FileOutputStream(newState.getFileDescriptor()); DataOutputStream out = new DataOutputStream(outstream); out.writeLong(fileModified); out.close(); } catch (IOException e) { Log.e(THIS_FILE, "Cannot manage final local backup state", e); } }