List of usage examples for java.io BufferedReader readLine
public String readLine() throws IOException
From source file:org.kuali.student.git.importer.ApplyManualBranchCleanup.java
/** * @param args// w ww . jav a 2s . co m */ public static void main(String[] args) { if (args.length < 4 || args.length > 7) { usage(); } File inputFile = new File(args[0]); if (!inputFile.exists()) usage(); boolean bare = false; if (args[2].trim().equals("1")) { bare = true; } String remoteName = args[3].trim(); String refPrefix = Constants.R_HEADS; if (args.length == 5) refPrefix = args[4].trim(); String userName = null; String password = null; if (args.length == 6) userName = args[5].trim(); if (args.length == 7) password = args[6].trim(); try { Repository repo = GitRepositoryUtils.buildFileRepository(new File(args[1]).getAbsoluteFile(), false, bare); Git git = new Git(repo); RevWalk rw = new RevWalk(repo); ObjectInserter objectInserter = repo.newObjectInserter(); BufferedReader fileReader = new BufferedReader(new FileReader(inputFile)); String line = fileReader.readLine(); int lineNumber = 1; BatchRefUpdate batch = repo.getRefDatabase().newBatchUpdate(); List<RefSpec> branchesToDelete = new ArrayList<>(); while (line != null) { if (line.startsWith("#") || line.length() == 0) { // skip over comments and blank lines line = fileReader.readLine(); lineNumber++; continue; } String parts[] = line.trim().split(":"); String branchName = parts[0]; Ref branchRef = repo.getRef(refPrefix + "/" + branchName); if (branchRef == null) { log.warn("line: {}, No branch matching {} exists, skipping.", lineNumber, branchName); line = fileReader.readLine(); lineNumber++; continue; } String tagName = null; if (parts.length > 1) tagName = parts[1]; if (tagName != null) { if (tagName.equals("keep")) { log.info("keeping existing branch for {}", branchName); line = fileReader.readLine(); lineNumber++; continue; } if (tagName.equals("tag")) { /* * Shortcut to say make the tag start with the same name as the branch. */ tagName = branchName; } // create a tag RevCommit commit = rw.parseCommit(branchRef.getObjectId()); ObjectId tag = GitRefUtils.insertTag(tagName, commit, objectInserter); batch.addCommand(new ReceiveCommand(null, tag, Constants.R_TAGS + tagName, Type.CREATE)); log.info("converting branch {} into a tag {}", branchName, tagName); } if (remoteName.equals("local")) { batch.addCommand( new ReceiveCommand(branchRef.getObjectId(), null, branchRef.getName(), Type.DELETE)); } else { // if the branch is remote then remember its name so we can batch delete after we have the full list. branchesToDelete.add(new RefSpec(":" + Constants.R_HEADS + branchName)); } line = fileReader.readLine(); lineNumber++; } fileReader.close(); // run the batch update batch.execute(rw, new TextProgressMonitor()); if (!remoteName.equals("local")) { // push the tag to the remote right now log.info("pushing tags to {}", remoteName); PushCommand pushCommand = git.push().setRemote(remoteName).setPushTags() .setProgressMonitor(new TextProgressMonitor()); if (userName != null) pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, password)); Iterable<PushResult> results = pushCommand.call(); for (PushResult pushResult : results) { if (!pushResult.equals(Result.NEW)) { log.warn("failed to push tag " + pushResult.getMessages()); } } // delete the branches from the remote log.info("pushing branch deletes to remote: {}", remoteName); results = git.push().setRemote(remoteName).setRefSpecs(branchesToDelete) .setProgressMonitor(new TextProgressMonitor()).call(); } objectInserter.release(); rw.release(); } catch (Exception e) { log.error("unexpected Exception ", e); } }
From source file:org.openimaj.demos.sandbox.flickr.geo.PlotFlickrGeo.java
public static void main(String[] args) throws IOException { final File inputcsv = new File("/Volumes/SSD/training_latlng"); final List<double[]> data = new ArrayList<double[]>(10000000); // read in images final BufferedReader br = new BufferedReader(new FileReader(inputcsv)); String line;//from w w w . j av a 2 s . c om int i = 0; br.readLine(); while ((line = br.readLine()) != null) { final String[] parts = line.split(" "); final double longitude = Double.parseDouble(parts[2]); final double latitude = Double.parseDouble(parts[1]); data.add(new double[] { longitude, latitude }); if (longitude >= -0.1 && longitude < 0 && latitude > 50 && latitude < 54) System.out.println(parts[0] + " " + latitude + " " + longitude); // if (i++ % 10000 == 0) // System.out.println(i); } br.close(); System.out.println("Done reading"); final float[][] dataArr = new float[2][data.size()]; for (i = 0; i < data.size(); i++) { dataArr[0][i] = (float) data.get(i)[0]; dataArr[1][i] = (float) data.get(i)[1]; } final NumberAxis domainAxis = new NumberAxis("X"); domainAxis.setRange(-180, 180); final NumberAxis rangeAxis = new NumberAxis("Y"); rangeAxis.setRange(-90, 90); final FastScatterPlot plot = new FastScatterPlot(dataArr, domainAxis, rangeAxis); final JFreeChart chart = new JFreeChart("Fast Scatter Plot", plot); chart.getRenderingHints().put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); final ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(500, 270)); final ApplicationFrame frame = new ApplicationFrame("Title"); frame.setContentPane(chartPanel); frame.pack(); frame.setVisible(true); }
From source file:com.honnix.yaacs.adapter.http.ui.ACHttpClientCli.java
public static void main(String[] args) { ACHttpClientCli acHttpClientCli = new ACHttpClientCli(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (true) { acHttpClientCli.help();/*from ww w . j av a2 s .com*/ String cmd = null; try { cmd = br.readLine(); } catch (IOException e) { e.printStackTrace(); // NOPMD by honnix on 3/29/08 10:35 PM System.err.println(BAD_INPUT); // NOPMD by honnix on 3/29/08 10:35 PM continue; } if ("li".equals(cmd)) { try { acHttpClientCli.handleLogin(br); } catch (Exception e) { e.printStackTrace(); // NOPMD by honnix on 3/29/08 10:35 PM System.err.println("Error logging in."); // NOPMD by honnix on 3/29/08 10:35 PM } } else if ("lo".equals(cmd)) { try { acHttpClientCli.handleLogout(); } catch (Exception e) { e.printStackTrace(); // NOPMD by honnix on 3/29/08 10:35 PM System.err.println("Error logging out."); // NOPMD by honnix on 3/29/08 10:35 PM } } if ("p".equals(cmd)) { try { acHttpClientCli.handlePut(br); } catch (Exception e) { e.printStackTrace(); // NOPMD by honnix on 3/29/08 10:35 PM System.err.println("Error putting album cover."); // NOPMD by honnix on 3/29/08 10:36 PM } } else if ("r".equals(cmd)) { try { acHttpClientCli.handleRetrieve(br); } catch (Exception e) { e.printStackTrace(); // NOPMD by honnix on 3/29/08 10:35 PM System.err.println("Error retrieving album cover list."); // NOPMD by honnix on 3/29/08 10:36 PM } } else if ("q".equals(cmd)) { break; } } }
From source file:examples.mail.IMAPImportMbox.java
public static void main(String[] args) throws IOException { if (args.length < 2) { System.err.println(/*from www. ja v a 2 s.c o m*/ "Usage: IMAPImportMbox imap[s]://user:password@host[:port]/folder/path <mboxfile> [selectors]"); System.err.println("\tWhere: a selector is a list of numbers/number ranges - 1,2,3-10" + " - or a list of strings to match in the initial From line"); System.exit(1); } final URI uri = URI.create(args[0]); final String file = args[1]; final File mbox = new File(file); if (!mbox.isFile() || !mbox.canRead()) { throw new IOException("Cannot read mailbox file: " + mbox); } String path = uri.getPath(); if (path == null || path.length() < 1) { throw new IllegalArgumentException("Invalid folderPath: '" + path + "'"); } String folder = path.substring(1); // skip the leading / List<String> contains = new ArrayList<String>(); // list of strings to find BitSet msgNums = new BitSet(); // list of message numbers for (int i = 2; i < args.length; i++) { String arg = args[i]; if (arg.matches("\\d+(-\\d+)?(,\\d+(-\\d+)?)*")) { // number,m-n for (String entry : arg.split(",")) { String[] parts = entry.split("-"); if (parts.length == 2) { // m-n int low = Integer.parseInt(parts[0]); int high = Integer.parseInt(parts[1]); for (int j = low; j <= high; j++) { msgNums.set(j); } } else { msgNums.set(Integer.parseInt(entry)); } } } else { contains.add(arg); // not a number/number range } } // System.out.println(msgNums.toString()); // System.out.println(java.util.Arrays.toString(contains.toArray())); // Connect and login final IMAPClient imap = IMAPUtils.imapLogin(uri, 10000, null); int total = 0; int loaded = 0; try { imap.setSoTimeout(6000); final BufferedReader br = new BufferedReader(new FileReader(file)); // TODO charset? String line; StringBuilder sb = new StringBuilder(); boolean wanted = false; // Skip any leading rubbish while ((line = br.readLine()) != null) { if (line.startsWith("From ")) { // start of message; i.e. end of previous (if any) if (process(sb, imap, folder, total)) { // process previous message (if any) loaded++; } sb.setLength(0); total++; wanted = wanted(total, line, msgNums, contains); } else if (startsWith(line, PATFROM)) { // Unescape ">+From " in body text line = line.substring(1); } // TODO process first Received: line to determine arrival date? if (wanted) { sb.append(line); sb.append(CRLF); } } br.close(); if (wanted && process(sb, imap, folder, total)) { // last message (if any) loaded++; } } catch (IOException e) { System.out.println(imap.getReplyString()); e.printStackTrace(); System.exit(10); return; } finally { imap.logout(); imap.disconnect(); } System.out.println("Processed " + total + " messages, loaded " + loaded); }
From source file:PeerDiscovery.java
/** * @param args/* ww w. j a v a2s .co m*/ */ public static void main(String[] args) { try { int group = 6969; PeerDiscovery mp = new PeerDiscovery(group, 6969); boolean stop = false; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (!stop) { System.out.println("enter \"q\" to quit, or anything else to query peers"); String s = br.readLine(); if (s.equals("q")) { System.out.print("Closing down..."); mp.disconnect(); System.out.println(" done"); stop = true; } else { System.out.println("Querying"); Peer[] peers = mp.getPeers(100, (byte) 0); System.out.println(peers.length + " peers found"); for (Peer p : peers) { System.out.println("\t" + p); } } } } catch (Exception e) { e.printStackTrace(); } }
From source file:edu.oregonstate.eecs.mcplan.domains.inventory.InventorySimulator.java
public static void main(final String[] argv) throws IOException { final RandomGenerator rng = new MersenneTwister(42); final int Nproducts = 2; final int max_inventory = 10; final double warehouse_cost = 1; final int min_order = 1; final int max_order = 2; final double delivery_probability = 0.5; final int max_demand = 5; final int[] price = new int[] { 1, 2 }; final InventoryProblem problem = InventoryProblem.TwoProducts(); // Nproducts, price, max_inventory, warehouse_cost, min_order, max_order, delivery_probability, max_demand ); while (true) { final InventoryState s = new InventoryState(rng, problem); final InventorySimulator sim = new InventorySimulator(s); final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (!s.isTerminal()) { System.out.println(sim.state()); final String cmd = reader.readLine(); final String[] tokens = cmd.split(","); final InventoryAction a; if ("n".equals(tokens[0])) { a = new InventoryNothingAction(); } else { final int product = Integer.parseInt(tokens[0]); final int quantity = Integer.parseInt(tokens[1]); a = new InventoryOrderAction(product, quantity, s.problem.cost[product]); }//from w ww. j av a 2s. c o m sim.takeAction(new JointAction<InventoryAction>(a)); System.out.println("r = " + Arrays.toString(sim.reward())); } // System.out.print( "Hand: " ); // System.out.print( sim.state().player_hand ); // System.out.print( " (" ); // final ArrayList<int[]> values = sim.state().player_hand.values(); // for( int i = 0; i < values.size(); ++i ) { // if( i > 0 ) { // System.out.print( ", " ); // } // System.out.print( Arrays.toString( values.get( i ) ) ); // } // System.out.println( ")" ); // // System.out.print( "Reward: " ); // System.out.println( Arrays.toString( sim.reward() ) ); // System.out.print( "Dealer hand: " ); // System.out.print( sim.state().dealerHand().toString() ); // System.out.print( " (" ); // System.out.print( SpBjHand.handValue( sim.state().dealerHand() )[0] ); // System.out.println( ")" ); // System.out.println( "----------------------------------------" ); } }
From source file:EchoClient.java
public static void main(String[] args) throws IOException { Socket echoSocket = null;//from ww w . ja va 2 s . c o m PrintWriter out = null; BufferedReader in = null; try { echoSocket = new Socket("taranis", 7); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( echoSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: taranis."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to: taranis."); System.exit(1); } BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); } out.close(); in.close(); stdIn.close(); echoSocket.close(); }
From source file:at.spardat.xma.xdelta.JarPatcher.java
/** * Main method to make {@link #applyDelta(ZipFile, ZipFile, ZipArchiveOutputStream, BufferedReader)} available at * the command line.<br>/* w w w . j a v a2s . com*/ * usage JarPatcher source patch output * * @param args the arguments * @throws IOException Signals that an I/O exception has occurred. */ public static void main(String[] args) throws IOException { String patchName = null; String outputName = null; String sourceName = null; if (args.length == 0) { System.err.println("usage JarPatcher patch [output [source]]"); System.exit(1); } else { patchName = args[0]; if (args.length > 1) { outputName = args[1]; if (args.length > 2) { sourceName = args[2]; } } } ZipFile patch = new ZipFile(patchName); ZipArchiveEntry listEntry = patch.getEntry("META-INF/file.list"); if (listEntry == null) { System.err.println("Invalid patch - list entry 'META-INF/file.list' not found"); System.exit(2); } BufferedReader list = new BufferedReader(new InputStreamReader(patch.getInputStream(listEntry))); String next = list.readLine(); if (sourceName == null) { sourceName = next; } next = list.readLine(); if (outputName == null) { outputName = next; } int ignoreSourcePaths = Integer.parseInt(System.getProperty("patcher.ignoreSourcePathElements", "0")); int ignoreOutputPaths = Integer.parseInt(System.getProperty("patcher.ignoreOutputPathElements", "0")); Path sourcePath = Paths.get(sourceName); Path outputPath = Paths.get(outputName); if (ignoreOutputPaths >= outputPath.getNameCount()) { patch.close(); StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in output (") .append(ignoreOutputPaths).append(" in ").append(outputName).append(")"); throw new IOException(b.toString()); } if (ignoreSourcePaths >= sourcePath.getNameCount()) { patch.close(); StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in source (") .append(sourcePath).append(" in ").append(sourceName).append(")"); throw new IOException(b.toString()); } sourcePath = sourcePath.subpath(ignoreSourcePaths, sourcePath.getNameCount()); outputPath = outputPath.subpath(ignoreOutputPaths, outputPath.getNameCount()); File sourceFile = sourcePath.toFile(); File outputFile = outputPath.toFile(); if (!(outputFile.getAbsoluteFile().getParentFile().mkdirs() || outputFile.getAbsoluteFile().getParentFile().exists())) { patch.close(); throw new IOException("Failed to create " + outputFile.getAbsolutePath()); } new JarPatcher(patchName, sourceFile.getName()).applyDelta(patch, new ZipFile(sourceFile), new ZipArchiveOutputStream(new FileOutputStream(outputFile)), list); list.close(); }
From source file:org.wso2.charon3.samples.group.sample01.CreateGroupSample.java
public static void main(String[] args) { try {// w w w .jav a 2 s. co m String url = "http://localhost:8080/scim/v2/Groups"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // Setting basic post request con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/scim+json"); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(createRequestBody); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader in; if (responseCode == HttpURLConnection.HTTP_CREATED) { // success in = new BufferedReader(new InputStreamReader(con.getInputStream())); } else { in = new BufferedReader(new InputStreamReader(con.getErrorStream())); } String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //printing result from response System.out.println("Response Code : " + responseCode); System.out.println("Response Message : " + con.getResponseMessage()); System.out.println("Response Content : " + response.toString()); } catch (ProtocolException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:visualizer.datamining.dataanalysis.NeighborhoodPreservation.java
public static void main(String[] args) throws IOException { String outfile = "precision.txt"; String pointsfile = args[0];/*from w ww . ja v a 2s . c om*/ String projsfile = "projfiles.txt"; int nrneighbors = Integer.parseInt(args[1]); DissimilarityType disstype = DissimilarityType.EUCLIDEAN; if (args[2].trim().toLowerCase().equals("cosine")) { disstype = DissimilarityType.COSINE_BASED; } ArrayList<String> projfiles = new ArrayList<String>(); BufferedReader br = new BufferedReader(new FileReader(new File(projsfile))); String line = null; while ((line = br.readLine()) != null) { projfiles.add(line.trim()); } NeighborhoodPreservationEngine npe = new NeighborhoodPreservationEngine(); npe.neighborhoodPreservation(outfile, pointsfile, projfiles, disstype, nrneighbors); }