List of usage examples for java.io IOException printStackTrace
public void printStackTrace()
From source file:com.rockstor.tools.RockStorFsFormat.java
public static void main(String[] args) { int res = 0;// w ww . jav a2 s .c o m try { res = ToolRunner.run(RockConfiguration.create(), new RockStorFsFormat(), args); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } System.exit(res); }
From source file:grnet.validation.XMLValidation.java
public static void main(String[] args) throws IOException { // TODO Auto-generated method ssstub Enviroment enviroment = new Enviroment(args[0]); if (enviroment.envCreation) { String schemaUrl = enviroment.getArguments().getSchemaURL(); Core core = new Core(schemaUrl); XMLSource source = new XMLSource(args[0]); File sourceFile = source.getSource(); if (sourceFile.exists()) { Collection<File> xmls = source.getXMLs(); System.out.println("Validating repository:" + sourceFile.getName()); System.out.println("Number of files to validate:" + xmls.size()); Iterator<File> iterator = xmls.iterator(); System.out.println("Validating against schema:" + schemaUrl + "..."); ValidationReport report = null; if (enviroment.getArguments().createReport().equalsIgnoreCase("true")) { report = new ValidationReport(enviroment.getArguments().getDestFolderLocation(), enviroment.getDataProviderValid().getName()); }//from w w w . j a va2 s.c o m ConnectionFactory factory = new ConnectionFactory(); factory.setHost(enviroment.getArguments().getQueueHost()); factory.setUsername(enviroment.getArguments().getQueueUserName()); factory.setPassword(enviroment.getArguments().getQueuePassword()); while (iterator.hasNext()) { StringBuffer logString = new StringBuffer(); logString.append(sourceFile.getName()); logString.append(" " + schemaUrl); File xmlFile = iterator.next(); String name = xmlFile.getName(); name = name.substring(0, name.indexOf(".xml")); logString.append(" " + name); boolean xmlIsValid = core.validateXMLSchema(xmlFile); if (xmlIsValid) { logString.append(" " + "Valid"); slf4jLogger.info(logString.toString()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes()); channel.close(); connection.close(); try { if (report != null) { report.raiseValidFilesNum(); } FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderValid()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { logString.append(" " + "Invalid"); slf4jLogger.info(logString.toString()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes()); channel.close(); connection.close(); try { if (report != null) { if (enviroment.getArguments().extendedReport().equalsIgnoreCase("true")) report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.invalidData, core.getReason()); report.raiseInvalidFilesNum(); } FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderInValid()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } if (report != null) { report.writeErrorBank(core.getErrorBank()); report.appendGeneralInfo(); } System.out.println("Validation is done."); } } }
From source file:examples.mail.IMAPImportMbox.java
public static void main(String[] args) throws IOException { if (args.length < 2) { System.err.println(/* w ww . ja va2s . c om*/ "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:com.comcast.oscar.examples.InsertDigitMapToConfigurationBinaryTest.java
/** * @param args/*from ww w .ja v a 2 s .c om*/ */ @SuppressWarnings("deprecation") public static void main(String[] args) { boolean debug = Boolean.FALSE; File fDigitMap = null; File fPacketCableTxt = null; File fPacketCableBin = null; //Get DigitMap try { fDigitMap = new File(new java.io.File(".").getCanonicalPath() + File.separatorChar + "testfiles" + File.separatorChar + "digitMap.txt"); } catch (IOException e) { e.printStackTrace(); } //OID String sOID = "enterprises.4491.2.2.8.2.1.1.3.1.1.2.1"; //Convert File to ByteArray byte[] bDigitMap = HexString.fileToByteArray(fDigitMap); //Need to get the JSON Dictionary Object, in this case, we need to use Snmp64 DictionarySQLQueries dsqSnmp64 = new DictionarySQLQueries( DictionarySQLQueries.PACKET_CABLE_DICTIONARY_TABLE_NAME); //Get JSON Dictionary Object JSONObject joDictSnmp64 = dsqSnmp64.getTlvDictionary(64); //Create JSON ARRAY for JSON Snmp64 Dictionary OIDToJSONArray otjoSnmp64 = new OIDToJSONArray(sOID, bDigitMap); try { joDictSnmp64 = otjoSnmp64.updateSnmpJsonObject(joDictSnmp64); } catch (JSONException e) { e.printStackTrace(); } // Validate: http://www.jsoneditoronline.org/ if (debug) System.out.println("Snmp64 - JSON-DICTIONARY: " + joDictSnmp64); /* Convert to TLV */ //Create a TlvAssembler for the JSON Dictionary TlvAssembler taSnmp64 = null; //Create an JSONArray Object - Need to make this more clean JSONArray jaSnmp64 = new JSONArray(); //Add JSONObject to JSONArray for TlvAssembler jaSnmp64.put(joDictSnmp64); //Get TlvAssembler() with Snmp64 TLV Encoding taSnmp64 = new TlvAssembler(jaSnmp64); //Display JSONObject if (debug) System.out.println("Snmp64: " + taSnmp64.toString()); /*Insert into Configuration File*/ /******************************** * Text To Binary ********************************/ try { fPacketCableTxt = new File(new java.io.File(".").getCanonicalPath() + File.separatorChar + "testfiles" + File.separatorChar + "IMS-PKT-CABLE-CONFIG-NO-DIGITMAP.txt"); } catch (IOException e) { e.printStackTrace(); } ConfigurationFileImport cfiPacketCable = null; try { try { cfiPacketCable = new ConfigurationFileImport(fPacketCableTxt); } catch (ConfigurationFileException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } ConfigurationFile cfSnmp64 = new ConfigurationFile(ConfigurationFile.PKT_CBL_VER_20, cfiPacketCable.getTlvBuilder()); //Add DigitMap cfSnmp64.add(taSnmp64); ConfigurationFile cfPacketCAble = new ConfigurationFile(ConfigurationFile.PKT_CBL_VER_20, cfiPacketCable.getTlvBuilder()); cfPacketCAble.commit(); try { fPacketCableBin = new File(new java.io.File(".").getCanonicalPath() + File.separatorChar + "testfiles" + File.separatorChar + File.separatorChar + "output" + File.separatorChar + "IMS-PKT-CABLE-CONFIG-WITH-DIGIT-MAP.bin"); } catch (IOException e) { e.printStackTrace(); } cfPacketCAble.setConfigurationFileName(fPacketCableBin); if (cfPacketCAble.writeToDisk()) { System.out.println("Write to File: "); } else { System.out.println("Write to File FAILED: "); } /******************************** * Binary To Text ********************************/ System.out.println( "+========================================================================================================================+"); try { fPacketCableBin = new File(new java.io.File(".").getCanonicalPath() + File.separatorChar + "testfiles" + File.separatorChar + "IMS-PKT-CABLE-CONFIG-NO-DIGITMAP.bin"); } catch (IOException e) { e.printStackTrace(); } ConfigurationFileExport cfePacketCable = new ConfigurationFileExport(fPacketCableBin); try { cfSnmp64 = new ConfigurationFile(ConfigurationFile.PKT_CBL_VER_20, cfePacketCable.getTlvBuilder()); } catch (TlvException e) { e.printStackTrace(); } //Add Snmp64 DigitMap cfSnmp64.add(taSnmp64); ConfigurationFileExport cfeSnmp64Insert = new ConfigurationFileExport(cfSnmp64); System.out.println(cfeSnmp64Insert.toPrettyPrint(0)); }
From source file:btrplace.fromEntropy.Converter.java
public static void main(String[] args) { String src, dst = null, output, scriptDC = null, dirScriptsCL = null; if (args.length < 5 || args.length > 6 || !args[args.length - 2].equals("-o")) { usage(1);/*from w w w. j a v a 2 s . c o m*/ } src = args[0]; output = args[args.length - 1]; if (args.length > 5) { dst = args[1]; } scriptDC = args[args.length - 4]; dirScriptsCL = args[args.length - 3]; OutputStreamWriter out = null; try { // Convert the src file ConfigurationConverter conv = new ConfigurationConverter(src); Instance i = conv.getInstance(); // Read the dst file, deduce and add the states constraints if (dst != null) { i.getSatConstraints().addAll(conv.getNextStates(dst)); } // Read the script files ScriptBuilder scriptBuilder = new ScriptBuilder(i.getModel()); //scriptBuilder.setIncludes(new PathBasedIncludes(scriptBuilder, // new File("src/test/resources"))); // Read the datacenter script file if exists if (scriptDC != null) { String strScriptDC = null; try { strScriptDC = readFile(scriptDC); } catch (IOException e) { e.printStackTrace(); } Script scrDC = null; try { // Build the DC script scrDC = scriptBuilder.build(strScriptDC); } catch (ScriptBuilderException sbe) { System.out.println(sbe); } // Set the DC script as an include BasicIncludes bi = new BasicIncludes(); bi.add(scrDC); scriptBuilder.setIncludes(bi); } // Read all the client script files String scriptCL = null, strScriptCL = null; Script scrCL = null; Iterator it = FileUtils.iterateFiles(new File(dirScriptsCL), null, false); while (it.hasNext()) { scriptCL = dirScriptsCL + "/" + ((File) it.next()).getName(); if (scriptCL != null) { // Read try { strScriptCL = readFile(scriptCL); } catch (IOException e) { e.printStackTrace(); } // Parse try { scrCL = scriptBuilder.build(strScriptCL); } catch (ScriptBuilderException sbe) { System.out.println(sbe); sbe.printStackTrace(); } // Add the resulting constraints if (scrCL.getConstraints() != null) { i.getSatConstraints().addAll(scrCL.getConstraints()); } } } /************** PATCH **************/ // State constraints; for (Node n : i.getModel().getMapping().getOnlineNodes()) { i.getSatConstraints().add(new Online(n)); } for (Node n : i.getModel().getMapping().getOfflineNodes()) { i.getSatConstraints().add(new Offline(n)); } // Remove preserve constraints for (Iterator<SatConstraint> ite = i.getSatConstraints().iterator(); ite.hasNext();) { SatConstraint s = ite.next(); if (s instanceof Preserve && src.contains("nr")) { ite.remove(); } } /************************************/ // Convert to JSON InstanceConverter iConv = new InstanceConverter(); JSONObject o = iConv.toJSON(i); // Check for gzip extension if (output.endsWith(".gz")) { out = new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(output))); } else { out = new FileWriter(output); } // Write the output file o.writeJSONString(out); out.close(); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(1); } finally { if (out != null) { try { out.close(); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(1); } } } }
From source file:de.uni_koblenz.jgralab.utilities.greqlinterface.GReQLConsole.java
/** * Performs some queries, extend this method to perform more queries * // w ww.j a v a2 s . com * @param args */ public static void main(String[] args) { CommandLine comLine = processCommandLineOptions(args); assert comLine != null; String queryFile = comLine.getOptionValue("q"); String graphFile = comLine.getOptionValue("g"); boolean loadSchema = comLine.hasOption("s"); JGraLab.setLogLevel(Level.SEVERE); GReQLConsole console = new GReQLConsole(graphFile, loadSchema, comLine.hasOption('v')); Object result = console.performQuery(new File(queryFile)); if (comLine.hasOption("o")) { try { console.resultToHTML(result, comLine.getOptionValue("o")); } catch (IOException e) { System.err.println("Exception while creating HTML output:"); e.printStackTrace(); } } else { System.out.println("Result: " + result); } }
From source file:edu.southampton.wais.crowd.terrier.applications.Indexing.java
/** * Used for testing purposes.//from w ww . j av a 2s . c o m * @param args the command line arguments. */ public static void main(String[] args) { long startTime = System.currentTimeMillis(); Indexing t = new Indexing(); t.setTRECIndexing(t.terrierIndexPath, t.terrierIndexPrefix); logger.info("Cleaning the dirs with previous index.."); try { FileUtils.cleanDirectory(new File(t.terrierIndexPath)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); logger.info("Exception : " + e.getMessage()); } logger.info("Cleaning done"); t.index(); long endTime = System.currentTimeMillis(); if (logger.isInfoEnabled()) logger.info("Elapsed time=" + ((endTime - startTime) / 1000.0D)); }
From source file:com.tmo.swagger.main.GenrateSwaggerJson.java
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException, EmptyXlsRows { PropertyReader pr = new PropertyReader(); Properties prop = pr.readPropertiesFile(args[0]); //Properties prop =pr.readClassPathPropertyFile("common.properties"); String swaggerFile = prop.getProperty("swagger.json"); String sw = ""; if (swaggerFile != null && swaggerFile.length() > 0) { Swagger swagger = populatePropertiesOnlyPaths(prop, new SwaggerParser().read(swaggerFile)); ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); sw = mapper.writeValueAsString(swagger); } else {//from w w w .jav a2 s. c o m ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); Swagger swagger = populateProperties(prop); sw = mapper.writeValueAsString(swagger); } try { File file = new File(args[1] + prop.getProperty("path.operation.tags") + ".json"); //File file = new File("src/main/resources/"+prop.getProperty("path.operation.tags")+".json"); if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(sw); logger.info("Swagger Genration Done!"); bw.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:test1.ApacheHttpRestClient2.java
public final static void main(String[] args) { HttpClient httpClient = new DefaultHttpClient(); try {//from w w w. jav a 2 s . c o m // this ona api call returns results in a JSON format HttpGet httpGetRequest = new HttpGet("https://api.ona.io/api/v1/users"); // Execute HTTP request HttpResponse httpResponse = httpClient.execute(httpGetRequest); System.out.println("------------------HTTP RESPONSE----------------------"); System.out.println(httpResponse.getStatusLine()); System.out.println("------------------HTTP RESPONSE----------------------"); // Get hold of the response entity HttpEntity entity = httpResponse.getEntity(); // If the response does not enclose an entity, there is no need // to bother about connection release byte[] buffer = new byte[1024]; if (entity != null) { InputStream inputStream = entity.getContent(); try { int bytesRead = 0; BufferedInputStream bis = new BufferedInputStream(inputStream); while ((bytesRead = bis.read(buffer)) != -1) { String chunk = new String(buffer, 0, bytesRead); FileWriter file = new FileWriter("C:\\Users\\fred\\Desktop\\webicons\\output.txt"); //file.write(chunk.toJSONString()); file.write(chunk.toCharArray()); file.flush(); file.close(); System.out.print(chunk); System.out.println(chunk); } } catch (IOException ioException) { // In case of an IOException the connection will be released // back to the connection manager automatically ioException.printStackTrace(); } catch (RuntimeException runtimeException) { // In case of an unexpected exception you may want to abort // the HTTP request in order to shut down the underlying // connection immediately. httpGetRequest.abort(); runtimeException.printStackTrace(); } // try { // FileWriter file = new FileWriter("C:\\Users\\fred\\Desktop\\webicons\\output.json"); // file.write(bis.toJSONString()); // file.flush(); // file.close(); // // System.out.print(bis); // } catch (Exception e) { // } finally { // Closing the input stream will trigger connection release try { inputStream.close(); } catch (Exception ignore) { } } } } catch (ClientProtocolException e) { // thrown by httpClient.execute(httpGetRequest) e.printStackTrace(); } catch (IOException e) { // thrown by entity.getContent(); e.printStackTrace(); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpClient.getConnectionManager().shutdown(); } }
From source file:de.moritzrupp.stockreader.Main.java
/** * main/*from w w w. j a v a2 s . c o m*/ * @param args */ public static void main(String[] args) { initOptions(); clParser = new GnuParser(); if (args.length == 0) { // if no arguments formatter.printHelp("stockreader", header, options, footer); System.exit(1); } try { CommandLine line = clParser.parse(options, args); if (line.hasOption("h")) { printHelp(); } if (line.hasOption("v")) { System.out.println("stockreader version " + VERSION + ". Copyright 2013 by Moritz Rupp. All rights reserved.\n" + "This application is licensed under The MIT License (MIT). See https://github.com/moritzrupp/stockreader/blob/master/LICENSE.md"); System.exit(0); } if (line.hasOption("p")) { priceArg = true; } if (line.hasOption("f")) { fileArg = true; theFile = new File(line.getOptionValue("f")); } host = line.getOptionValue("host"); username = line.getOptionValue("user"); passwd = line.getOptionValue("password"); from = line.getOptionValue("from"); to = line.getOptionValue("to"); } catch (ParseException exp) { // TODO Auto-generated catch block exp.printStackTrace(); } try { reader = new StockReader(';', new StockQuote(), "UTF-8", (fileArg) ? theFile.toString() : new File(".").getCanonicalPath() + ((System.getProperty("os.name").toLowerCase().startsWith("win")) ? "\\" : "/") + "stocks.csv"); for (int i = 0; i < args.length; i++) { switch (args[i].charAt(0)) { case '-': if (args[i].length() < 2) { System.err.println("Not a valid argument: " + args[i]); printHelp(); System.exit(1); } if (args[i].charAt(1) == 'f' || (args[i].charAt(1) == '-' && args[i].charAt(2) == 'f')) { // get the path and set it to "nosymbol" args[i + 1] = "nosymbol"; } break; default: if (!args[i].equals("nosymbol")) { reader.addSymbol(args[i]); } break; } } reader.getQuotes(); reader.writeToCSV(priceArg); reader.sendmail(from, to, "Aktienkurse", host, username, passwd); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (java.text.ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } }