List of usage examples for java.io InputStream close
public void close() throws IOException
From source file:cloudlens.cli.Main.java
public static void main(String[] args) throws Exception { final CommandLineParser optionParser = new DefaultParser(); final HelpFormatter formatter = new HelpFormatter(); final Option lens = Option.builder("r").longOpt("run").hasArg().argName("lens file").desc("Lens file.") .required(true).build();//w w w . ja va2 s .c o m final Option log = Option.builder("l").longOpt("log").hasArg().argName("log file").desc("Log file.") .build(); final Option jsonpath = Option.builder().longOpt("jsonpath").hasArg().argName("path") .desc("Path to logs in a json object.").build(); final Option js = Option.builder().longOpt("js").hasArg().argName("js file").desc("Load JS file.").build(); final Option format = Option.builder("f").longOpt("format").hasArg() .desc("Choose log format (text or json).").build(); final Option streaming = Option.builder().longOpt("stream").desc("Streaming mode.").build(); final Option history = Option.builder().longOpt("history").desc("Store history.").build(); final Options options = new Options(); options.addOption(log); options.addOption(lens); options.addOption(format); options.addOption(jsonpath); options.addOption(js); options.addOption(streaming); options.addOption(history); try { final CommandLine cmd = optionParser.parse(options, args); final String jsonPath = cmd.getOptionValue("jsonpath"); final String[] jsFiles = cmd.getOptionValues("js"); final String[] lensFiles = cmd.getOptionValues("run"); final String[] logFiles = cmd.getOptionValues("log"); final String source = cmd.getOptionValue("format"); final boolean stream = cmd.hasOption("stream") || !cmd.hasOption("log"); final boolean withHistory = cmd.hasOption("history") || !stream; final CL cl = new CL(System.out, System.err, stream, withHistory); try { final InputStream input = (cmd.hasOption("log")) ? FileReader.readFiles(logFiles) : System.in; if (source == null) { cl.source(input); } else { switch (source) { case "text": cl.source(input); break; case "json": cl.json(input, jsonPath); break; default: input.close(); throw new CLException("Unsupported format: " + source); } } for (final String jsFile : FileReader.fullPaths(jsFiles)) { cl.engine.eval("CL.loadjs('file://" + jsFile + "')"); } final List<ASTElement> top = ASTBuilder.parseFiles(lensFiles); cl.launch(top); } catch (final CLException | ASTException e) { cl.errWriter.println(e.getMessage()); } finally { cl.outWriter.flush(); cl.errWriter.flush(); } } catch (final ParseException e) { System.err.println(e.getMessage()); formatter.printHelp("cloudlens", options); } }
From source file:airnowgrib2tojson.AirNowGRIB2toJSON.java
/** * @param args the command line arguments *//*from www . j a v a 2s. c o m*/ public static void main(String[] args) { SimpleDateFormat GMT = new SimpleDateFormat("yyMMddHH"); GMT.setTimeZone(TimeZone.getTimeZone("GMT-2")); System.out.println(GMT.format(new Date())); FTPClient ftpClient = new FTPClient(); FileOutputStream fos = null; try { //Connecting to AirNow FTP server to get the fresh AQI data ftpClient.connect("ftp.airnowapi.org"); ftpClient.login("pixelshade", "GZDN8uqduwvk"); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); //downloading .grib2 file File of = new File("US-" + GMT.format(new Date()) + "_combined.grib2"); OutputStream outstr = new BufferedOutputStream(new FileOutputStream(of)); InputStream instr = ftpClient .retrieveFileStream("GRIB2/US-" + GMT.format(new Date()) + "_combined.grib2"); byte[] bytesArray = new byte[4096]; int bytesRead = -1; while ((bytesRead = instr.read(bytesArray)) != -1) { outstr.write(bytesArray, 0, bytesRead); } //Close used resources ftpClient.completePendingCommand(); outstr.close(); instr.close(); // logout the user ftpClient.logout(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { //disconnect from AirNow server ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } try { //Open .grib2 file final File AQIfile = new File("US-" + GMT.format(new Date()) + "_combined.grib2"); final GridDataset gridDS = GridDataset.open(AQIfile.getAbsolutePath()); //The data type needed - AQI; since it isn't defined in GRIB2 standard, //Aerosol type is used instead; look AirNow API documentation for details. GridDatatype AQI = gridDS.findGridDatatype("Aerosol_type_msl"); //Get the coordinate system for selected data type; //cut the rectangle to work with - time and height axes aren't present in these files //and latitude/longitude go "-1", which means all the data provided. GridCoordSystem AQIGCS = AQI.getCoordinateSystem(); List<CoordinateAxis> AQI_XY = AQIGCS.getCoordinateAxes(); Array AQIslice = AQI.readDataSlice(0, 0, -1, -1); //Variables for iterating through coordinates VariableDS var = AQI.getVariable(); Index index = AQIslice.getIndex(); //Variables for counting lat/long from the indices provided double stepX = (AQI_XY.get(2).getMaxValue() - AQI_XY.get(2).getMinValue()) / index.getShape(1); double stepY = (AQI_XY.get(1).getMaxValue() - AQI_XY.get(1).getMinValue()) / index.getShape(0); double curX = AQI_XY.get(2).getMinValue(); double curY = AQI_XY.get(1).getMinValue(); //Output details OutputStream ValLog = new FileOutputStream("USA_AQI.json"); Writer ValWriter = new OutputStreamWriter(ValLog); for (int j = 0; j < index.getShape(0); j++) { for (int i = 0; i < index.getShape(1); i++) { float val = AQIslice.getFloat(index.set(j, i)); //Write the AQI value and its coordinates if it's present by i/j indices if (!Float.isNaN(val)) ValWriter.write("{\r\n\"lat\":" + curX + ",\r\n\"lng\":" + curY + ",\r\n\"AQI\":" + val + ",\r\n},\r\n"); curX += stepX; } curY += stepY; curX = AQI_XY.get(2).getMinValue(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.badlogicgames.packr.Packr.java
public static void main(String[] args) throws IOException { if (args.length > 1) { Map<String, String> arguments = parseArgs(args); Config config = new Config(); config.platform = Platform.valueOf(arguments.get("platform")); config.jdk = arguments.get("jdk"); config.executable = arguments.get("executable"); config.jar = arguments.get("appjar"); config.mainClass = arguments.get("mainclass"); if (arguments.get("vmargs") != null) { config.vmArgs = Arrays.asList(arguments.get("vmargs").split(";")); }//from w ww . j a v a2s. com config.outDir = arguments.get("outdir"); if (arguments.get("minimizejre") != null) { if (new File(arguments.get("minimizejre")).exists()) { config.minimizeJre = FileUtils.readFileToString(new File(arguments.get("minimizejre"))) .split("\r?\n"); } else { InputStream in = Packr.class.getResourceAsStream("/minimize/" + arguments.get("minimizejre")); if (in != null) { config.minimizeJre = IOUtils.toString(in).split("\r?\n"); in.close(); } else { config.minimizeJre = new String[0]; } } } if (arguments.get("resources") != null) config.resources = Arrays.asList(arguments.get("resources").split(";")); new Packr().pack(config); } else { if (args.length == 0) { printHelp(); } else { JsonObject json = JsonObject.readFrom(FileUtils.readFileToString(new File(args[0]))); Config config = new Config(); config.platform = Platform.valueOf(json.get("platform").asString()); config.jdk = json.get("jdk").asString(); config.executable = json.get("executable").asString(); config.jar = json.get("appjar").asString(); config.mainClass = json.get("mainclass").asString(); if (json.get("vmargs") != null) { for (JsonValue val : json.get("vmargs").asArray()) { config.vmArgs.add(val.asString()); } } config.outDir = json.get("outdir").asString(); if (json.get("minimizejre") != null) { if (new File(json.get("minimizejre").asString()).exists()) { config.minimizeJre = FileUtils .readFileToString(new File(json.get("minimizejre").asString())).split("\r?\n"); } else { InputStream in = Packr.class.getResourceAsStream("/minimize/" + json.get("minimizejre")); if (in != null) { config.minimizeJre = IOUtils.toString(in).split("\r?\n"); in.close(); } else { config.minimizeJre = new String[0]; } } } if (json.get("resources") != null) { config.resources = toStringArray(json.get("resources").asArray()); } new Packr().pack(config); } } }
From source file:com.ccreservoirs.RSSReader.ClientConnectionRelease.java
public final static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try {//from ww w . j ava 2 s . c o m HttpGet httpget = new HttpGet("http://blog.csdn.net/rss.html?type=Home&channel="); System.out.println("Executing request " + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpget); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); // Get hold of the response entity HttpEntity entity = response.getEntity(); // If the response does not enclose an entity, there is no need // to bother about connection release if (entity != null) { InputStream instream = entity.getContent(); try { instream.read(); // do something useful with the response } catch (IOException ex) { // In case of an IOException the connection will be // released // back to the connection manager automatically throw ex; } finally { // Closing the input stream will trigger connection // release instream.close(); } } } finally { response.close(); } } finally { httpclient.close(); } }
From source file:luisjosediez.Ejercicio2.java
/** * @param args the command line arguments *//*from ww w. j a va 2s .c om*/ public static void main(String[] args) { // TODO code application logic here System.out.println("Introduce la direccin de un servidor ftp: "); FTPClient cliente = new FTPClient(); String servFTP = cadena(); String clave = ""; System.out.println("Introduce usuario (vaco para conexin annima): "); String usuario = cadena(); String opcion; if (usuario.equals("")) { clave = ""; } else { System.out.println("Introduce contrasea: "); clave = cadena(); } try { cliente.setPassiveNatWorkaround(false); cliente.connect(servFTP, 21); boolean login = cliente.login(usuario, clave); if (login) { System.out.println("Conexin ok"); } else { System.out.println("Login incorrecto"); cliente.disconnect(); System.exit(1); } do { System.out.println("Orden [exit para salir]: "); opcion = cadena(); if (opcion.equals("ls")) { FTPFile[] files = cliente.listFiles(); String tipos[] = { "Fichero", "Directorio", "Enlace" }; for (int i = 0; i < files.length; i++) { System.out.println("\t" + files[i].getName() + "\t=> " + tipos[files[i].getType()]); } } else if (opcion.startsWith("cd ")) { try { cliente.changeWorkingDirectory(opcion.substring(3)); } catch (IOException e) { } } else if (opcion.equals("help")) { System.out.println( "Puede ejecutar los comandos 'exit', 'ls', 'cd', 'get' y 'upload'. Para ms detalles utilice 'help <comando>'."); } else if (opcion.startsWith("help ")) { if (opcion.endsWith(" get")) { System.out.println( "Permite descargar un archivo concreto. Uso: 'get <rutaArchivoADescargar>'."); } else if (opcion.endsWith(" ls")) { System.out.println("Lista los ficheros y directorios en la ubicacin actual. Uso: 'ls'."); } else if (opcion.endsWith(" cd")) { System.out.println("Permite cambiar la ubicacin actual. Uso: 'cd <rutaDestino>'."); } else if (opcion.endsWith(" put")) { System.out.println( "Permite subir un archivo al directorio actual. Uso: 'put <rutaArchivoASubir>'."); } } else if (opcion.startsWith("get ")) { try { System.out.println("Indique la carpeta de descarga: "); try (FileOutputStream fos = new FileOutputStream(cadena() + opcion.substring(4))) { cliente.retrieveFile(opcion.substring(4), fos); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { } } else if (opcion.startsWith("put ")) { try { try { System.out.println(opcion.substring(4)); File local = new File(opcion.substring(4)); System.out.println(local.getName()); InputStream is = new FileInputStream(opcion.substring(4)); OutputStream os = cliente.storeFileStream(local.getName()); byte[] bytesIn = new byte[4096]; int read = 0; while ((read = is.read(bytesIn)) != -1) { os.write(bytesIn, 0, read); } is.close(); os.close(); boolean completed = cliente.completePendingCommand(); if (completed) { System.out.println("The file is uploaded successfully."); } } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { } } } while (!(opcion.equals("exit"))); boolean logout = cliente.logout(); if (logout) System.out.println("Logout..."); else System.out.println("Logout incorrecto"); cliente.disconnect(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.minoritycode.Application.java
public static void main(String[] args) { System.out.println("Trello Backup Application"); File configFile = new File(workingDir + "\\config.properties"); InputStream input = null; try {//from w w w. j a v a2 s.co m input = new FileInputStream(configFile); config.load(input); input.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // String workingDir = System.getProperty("user.dir"); manualOperation = Boolean.parseBoolean(config.getProperty("manualOperation")); logger.startErrorLogger(); setBackupDir(); try { report.put("backupDate", backupDate); } catch (JSONException e) { e.printStackTrace(); logger.logLine(e.getMessage()); } lock = new ReentrantLock(); lockErrorRep = new ReentrantLock(); lockErrorLog = new ReentrantLock(); Application.key = config.getProperty("trellokey"); Application.token = config.getProperty("trellotoken"); boolean useProxy = Boolean.parseBoolean(config.getProperty("useProxy")); boolean proxySet = true; if (useProxy) { proxySet = setProxy(); } // GUI swingContainerDemo = new GUI(); // swingContainerDemo.showJPanelDemo(); if (proxySet) { Credentials credentials = new Credentials(); if (Application.key.isEmpty()) { Application.key = credentials.getKey(); } else { Application.key = config.getProperty("trellokey"); } if (token.isEmpty()) { Application.token = credentials.getToken(); } else { Application.token = config.getProperty("trellotoken"); } BoardDownloader downloader = new BoardDownloader(); downloader.downloadMyBoard(url); boards = downloader.downloadOrgBoard(url); if (boards != null) { try { report.put("boardNum", boards.size()); } catch (JSONException e) { e.printStackTrace(); logger.logLine(e.getMessage()); } Integer numberOfThreads = Integer.parseInt(config.getProperty("numberOfThreads")); if (numberOfThreads == null) { logger.logLine("error number of threads not set in config file"); if (manualOperation) { String message = "How many threads do you want to use (10) is average"; numberOfThreads = Integer.parseInt(Credentials.getInput(message)); Credentials.saveProperty("numberOfThreads", numberOfThreads.toString()); } else { if (Boolean.parseBoolean(config.getProperty("useMailer"))) { Mailer mailer = new Mailer(); mailer.SendMail(); } System.exit(-1); } } ArrayList<Thread> threadList = new ArrayList<Thread>(); for (int i = 0; i < numberOfThreads; i++) { Thread thread = new Thread(new Application(), "BoardDownloadThread"); threadList.add(thread); thread.start(); } } else { //create empty report try { report.put("boardsNotDownloaded", "99999"); report.put("boardNum", 0); report.put("boardNumSuccessful", 0); } catch (JSONException e) { e.printStackTrace(); logger.logLine(e.getMessage()); } if (Boolean.parseBoolean(config.getProperty("useMailer"))) { Mailer mailer = new Mailer(); mailer.SendMail(); } logger.logger(report); } } else { //create empty report try { report.put("boardsNotDownloaded", "99999"); report.put("boardNum", 0); report.put("boardNumSuccessful", 0); } catch (JSONException e) { e.printStackTrace(); logger.logLine(e.getMessage()); } if (Boolean.parseBoolean(config.getProperty("useMailer"))) { Mailer mailer = new Mailer(); mailer.SendMail(); } } }
From source file:Main.java
public static void main(String[] args) throws Exception { InputStream is = new FileInputStream("C://test.txt"); // read and print characters one by one System.out.println("Char : " + (char) is.read()); System.out.println("Char : " + (char) is.read()); System.out.println("Char : " + (char) is.read()); // mark is set on the input stream is.mark(0);/* w ww. j a v a 2 s . com*/ System.out.println("Char : " + (char) is.read()); System.out.println("Char : " + (char) is.read()); if (is.markSupported()) { // reset invoked if mark() is supported is.reset(); System.out.println("Char : " + (char) is.read()); System.out.println("Char : " + (char) is.read()); } is.close(); }
From source file:MondrianService.java
public static void main(String[] arg) { System.out.println("Starting Mondrian Connector for Infoveave"); Properties prop = new Properties(); InputStream input = null; int listenPort = 9998; int threads = 100; try {//from w w w. j a v a 2s.com System.out.println("Staring from :" + getSettingsPath()); input = new FileInputStream(getSettingsPath() + File.separator + "MondrianService.properties"); prop.load(input); listenPort = Integer.parseInt(prop.getProperty("port")); threads = Integer.parseInt(prop.getProperty("maxThreads")); if (input != null) { input.close(); } System.out.println("Found MondrianService.Properties"); } catch (FileNotFoundException e) { } catch (IOException e) { } port(listenPort); threadPool(threads); enableCORS("*", "*", "*"); ObjectMapper mapper = new ObjectMapper(); MondrianConnector connector = new MondrianConnector(); get("/ping", (request, response) -> { response.type("application/json"); return "\"Here\""; }); post("/cubes", (request, response) -> { response.type("application/json"); try { Query queryObject = mapper.readValue(request.body(), Query.class); response.status(200); return mapper.writeValueAsString(connector.GetCubes(queryObject)); } catch (JsonParseException ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } catch (Exception ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } }); post("/measures", (request, response) -> { response.type("application/json"); try { Query queryObject = mapper.readValue(request.body(), Query.class); response.status(200); return mapper.writeValueAsString(connector.GetMeasures(queryObject)); } catch (JsonParseException ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } catch (Exception ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } }); post("/dimensions", (request, response) -> { response.type("application/json"); try { Query queryObject = mapper.readValue(request.body(), Query.class); response.status(200); return mapper.writeValueAsString(connector.GetDimensions(queryObject)); } catch (JsonParseException ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } catch (Exception ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } }); post("/cleanCache", (request, response) -> { response.type("application/json"); try { Query queryObject = mapper.readValue(request.body(), Query.class); response.status(200); return mapper.writeValueAsString(connector.CleanCubeCache(queryObject)); } catch (JsonParseException ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } catch (Exception ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } }); post("/executeQuery", (request, response) -> { response.type("application/json"); try { Query queryObject = mapper.readValue(request.body(), Query.class); response.status(200); String content = mapper.writeValueAsString(connector.ExecuteQuery2(queryObject)); return content; } catch (JsonParseException ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } catch (Exception ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } }); }
From source file:com.mtea.macrotea_httpclient_study.ClientConnectionRelease.java
public final static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); try {//from w w w .j av a 2 s .c om HttpGet httpget = new HttpGet("http://www.apache.org/"); // Execute HTTP request System.out.println("executing request " + httpget.getURI()); HttpResponse response = httpclient.execute(httpget); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println("----------------------------------------"); HttpEntity entity = response.getEntity(); //????? if (entity != null) { InputStream instream = entity.getContent(); try { instream.read(); } catch (IOException ex) { //IOExceptionConnectionManager throw ex; } catch (RuntimeException ex) { //RuntimeExceptionhttpget.abort(); httpget.abort(); throw ex; } finally { // instream.close() ?ConnectionManager try { instream.close(); } catch (Exception ignore) { } } } } finally { //??httpclient??? httpclient.getConnectionManager().shutdown(); } }
From source file:com.image32.demo.simpleapi.SimpleApiDemo.java
final public static void main(String[] args) { me = new SimpleApiDemo(); me.contentHandlers = new ContentHandler(); //load configurations try {//from w w w. j a va2s . c om Properties prop = new Properties(); InputStream input = SimpleApiDemo.class.getResourceAsStream("/demoConfig.properties"); // load a properties file prop.load(input); image32ApiClientId = prop.getProperty("image32ApiClientId"); image32ApiSecrect = prop.getProperty("image32ApiSecrect"); image32ApiAuthUrl = prop.getProperty("image32ApiAuthUrl"); image32ApiGetStudiesUrl = prop.getProperty("image32ApiGetStudiesUrl"); demoDataFile = prop.getProperty("demoDataFile"); input.close(); } catch (Exception ex) { logger.info("No configuration found."); System.exit(1); } // test port availability while (!checkPortAvailablity(port)) { if (port > 8090) { logger.info("Port is not available. Exiting..."); System.exit(1); } port++; } ; // run server server = new Server(port); HashSessionIdManager hashSessionIdManager = new HashSessionIdManager(); server.setSessionIdManager(hashSessionIdManager); WebAppContext homecontext = new WebAppContext(); homecontext.setContextPath("/home"); ResourceCollection resources = new ResourceCollection(new String[] { "site" }); homecontext.setBaseResource(resources); HashSessionManager manager = new HashSessionManager(); manager.setSecureCookies(true); SessionHandler sessionHandler = new SessionHandler(manager); sessionHandler.setHandler(me.contentHandlers); ContextHandler context = new ContextHandler(); context.setContextPath("/app"); context.setResourceBase("."); context.setClassLoader(Thread.currentThread().getContextClassLoader()); context.setHandler(sessionHandler); HandlerList handlers = new HandlerList(); handlers.setHandlers(new Handler[] { homecontext, context }); server.setHandler(handlers); try { server.start(); logger.info("Server started on port " + port); logger.info("Please access this demo from browser with this url: http://localhost:" + port); if (Desktop.isDesktopSupported()) Desktop.getDesktop().browse(new URI("http://localhost:" + port + "/home")); server.join(); } catch (Exception exception) { logger.error(exception.getMessage()); } System.exit(1); }