List of usage examples for org.apache.commons.io FileUtils writeStringToFile
public static void writeStringToFile(File file, String data) throws IOException
From source file:com.axiomine.largecollections.generator.GeneratorWritableKeyWritableValue.java
public static void main(String[] args) throws Exception { //Package of the new class you are generating Ex. com.mypackage String MY_PACKAGE = args[0];//from www .j a v a2 s. c o m //Any custom imports you need (: seperated). Use - if no custom imports are included //Ex. java.util.*:java.lang.Random String CUSTOM_IMPORTS = args[1].equals("-") ? "" : args[1]; //Package of your Key serializer class. Use com.axiomine.bigcollections.functions String KPACKAGE = args[2]; //Package of your value serializer class. Use com.axiomine.bigcollections.functions String VPACKAGE = args[3]; //Class name (no packages) of the Key class Ex. String String K = args[4]; //Class name (no packages) of the value class Ex. Integer String V = args[5]; String kCls = K; String vCls = V; if (kCls.equals("byte[]")) { kCls = "BytesArray"; } if (vCls.equals("byte[]")) { vCls = "BytesArray"; } String CLASS_NAME = kCls + vCls + "Map"; //Default //String templatePath = args[5]; File root = new File(""); File outFile = new File(root.getAbsolutePath() + "/src/main/java/" + MY_PACKAGE.replaceAll("\\.", "/") + "/" + CLASS_NAME + ".java"); if (outFile.exists()) { System.out.println(outFile.getAbsolutePath() + " already exists. Please delete it and try again"); } { String[] imports = null; String importStr = ""; if (!StringUtils.isBlank(CUSTOM_IMPORTS)) { CUSTOM_IMPORTS.split(":"); for (String s : imports) { importStr = "import " + s + ";\n"; } } String program = FileUtils.readFileToString(new File( root.getAbsolutePath() + "/src/main/resources/WritableKeyWritableValueMapTemplate.java")); program = program.replaceAll("#MY_PACKAGE#", MY_PACKAGE); program = program.replaceAll("#CUSTOM_IMPORTS#", importStr); program = program.replaceAll("#CLASS_NAME#", CLASS_NAME); program = program.replaceAll("#K#", K); program = program.replaceAll("#V#", V); program = program.replaceAll("#KCLS#", kCls); program = program.replaceAll("#VCLS#", vCls); program = program.replaceAll("#KPACKAGE#", KPACKAGE); program = program.replaceAll("#VPACKAGE#", VPACKAGE); System.out.println(outFile.getAbsolutePath()); FileUtils.writeStringToFile(outFile, program); } }
From source file:com.axiomine.largecollections.generator.GeneratorWritableKeyPrimitiveValue.java
public static void main(String[] args) throws Exception { //Package of the new class you are generating Ex. com.mypackage String MY_PACKAGE = args[0];//from ww w . j a va 2 s .c om //Any custom imports you need (: seperated). Use - if no custom imports are included //Ex. java.util.*:java.lang.Random String CUSTOM_IMPORTS = args[1].equals("-") ? "" : args[1]; //Package of your Key serializer class. Use com.axiomine.bigcollections.functions String KPACKAGE = args[2]; //Package of your value serializer class. Use com.axiomine.bigcollections.functions String VPACKAGE = args[3]; //Class name (no packages) of the Key class Ex. String String K = args[4]; //Class name (no packages) of the value class Ex. Integer String V = args[5]; String kCls = K; String vCls = V; if (kCls.equals("byte[]")) { kCls = "BytesArray"; } if (vCls.equals("byte[]")) { vCls = "BytesArray"; } String CLASS_NAME = kCls + vCls + "Map"; //Default //String templatePath = args[5]; File root = new File(""); File outFile = new File(root.getAbsolutePath() + "/src/main/java/" + MY_PACKAGE.replaceAll("\\.", "/") + "/" + CLASS_NAME + ".java"); if (outFile.exists()) { System.out.println(outFile.getAbsolutePath() + " already exists. Please delete it and try again"); } { String[] imports = null; String importStr = ""; if (!StringUtils.isBlank(CUSTOM_IMPORTS)) { CUSTOM_IMPORTS.split(":"); for (String s : imports) { importStr = "import " + s + ";\n"; } } String program = FileUtils.readFileToString(new File( root.getAbsolutePath() + "/src/main/resources/WritableKeyPrimitiveValueMapTemplate.java")); program = program.replaceAll("#MY_PACKAGE#", MY_PACKAGE); program = program.replaceAll("#CUSTOM_IMPORTS#", importStr); program = program.replaceAll("#CLASS_NAME#", CLASS_NAME); program = program.replaceAll("#K#", K); program = program.replaceAll("#V#", V); program = program.replaceAll("#KCLS#", kCls); program = program.replaceAll("#VCLS#", vCls); program = program.replaceAll("#KPACKAGE#", KPACKAGE); program = program.replaceAll("#VPACKAGE#", VPACKAGE); System.out.println(outFile.getAbsolutePath()); FileUtils.writeStringToFile(outFile, program); } }
From source file:com.axiomine.largecollections.generator.GeneratorPrimitiveKeyWritableValue.java
public static void main(String[] args) throws Exception { //Package of the new class you are generating Ex. com.mypackage String MY_PACKAGE = args[0];//from ww w. j av a2 s.c om //Any custom imports you need (: seperated). Use - if no custom imports are included //Ex. java.util.*:java.lang.Random String CUSTOM_IMPORTS = args[1].equals("-") ? "" : args[1]; //Package of your Key serializer class. Use com.axiomine.bigcollections.functions String KPACKAGE = args[2]; //Package of your value serializer class. Use com.axiomine.bigcollections.functions String VPACKAGE = args[3]; //Class name (no packages) of the Key class Ex. String String K = args[4]; //Class name (no packages) of the value class Ex. Integer String V = args[5]; String vWritableCls = args[6]; String kCls = K; String vCls = V; if (kCls.equals("byte[]")) { kCls = "BytesArray"; } if (vCls.equals("byte[]")) { vCls = "BytesArray"; } String CLASS_NAME = kCls + vCls + "Map"; //Default //String templatePath = args[5]; File root = new File(""); File outFile = new File(root.getAbsolutePath() + "/src/main/java/" + MY_PACKAGE.replaceAll("\\.", "/") + "/" + CLASS_NAME + ".java"); if (outFile.exists()) { System.out.println(outFile.getAbsolutePath() + " already exists. Please delete it and try again"); } { String[] imports = null; String importStr = ""; if (!StringUtils.isBlank(CUSTOM_IMPORTS)) { CUSTOM_IMPORTS.split(":"); for (String s : imports) { importStr = "import " + s + ";\n"; } } String program = FileUtils.readFileToString(new File( root.getAbsolutePath() + "/src/main/resources/PrimitiveKeyWritableValueMapTemplate.java")); program = program.replaceAll("#MY_PACKAGE#", MY_PACKAGE); program = program.replaceAll("#CUSTOM_IMPORTS#", importStr); program = program.replaceAll("#CLASS_NAME#", CLASS_NAME); program = program.replaceAll("#K#", K); program = program.replaceAll("#V#", V); program = program.replaceAll("#KCLS#", kCls); program = program.replaceAll("#VCLS#", vCls); program = program.replaceAll("#VWRITABLECLS#", vWritableCls); program = program.replaceAll("#KPACKAGE#", KPACKAGE); program = program.replaceAll("#VPACKAGE#", VPACKAGE); System.out.println(outFile.getAbsolutePath()); FileUtils.writeStringToFile(outFile, program); } }
From source file:net.itransformers.bgpPeeringMap.BgpPeeringMapFromFile.java
public static void main(String[] args) throws Exception { Map<String, String> params = CmdLineParser.parseCmdLine(args); logger.info("input params" + params.toString()); final String settingsFile = params.get("-s"); if (settingsFile == null) { printUsage("bgpPeeringMap.properties"); return;/* ww w . j a v a 2s .c o m*/ } Map<String, String> settings = loadProperties(new File(System.getProperty("base.dir"), settingsFile)); logger.info("Settings" + settings.toString()); File outputDir = new File(System.getProperty("base.dir"), settings.get("output.dir")); System.out.println(outputDir.getAbsolutePath()); boolean result = outputDir.mkdir(); // if (!result) { // System.out.println("result:"+result); // System.out.println("Unable to create dir: "+outputDir); // return; // } File graphmlDir = new File(outputDir, settings.get("output.dir.graphml")); result = outputDir.mkdir(); // if (!result) { // System.out.println("Unable to create dir: "+graphmlDir); // return; // } XsltTransformer transformer = new XsltTransformer(); byte[] rawData = readRawDataFile(settings.get("raw-data-file")); logger.info("First-transformation has started with xsltTransformator " + settings.get("xsltFileName1")); ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream(); File xsltFileName1 = new File(System.getProperty("base.dir"), settings.get("xsltFileName1")); ByteArrayInputStream inputStream1 = new ByteArrayInputStream(rawData); // transformer.transformXML(inputStream1, xsltFileName1, outputStream1, settings); logger.info("First transformation finished"); File outputFile1 = new File(graphmlDir, "bgpPeeringMap-intermediate.xml"); FileUtils.writeStringToFile(outputFile1, new String(outputStream1.toByteArray())); logger.info("Second transformation started with xsltTransformator " + settings.get("xsltFileName2")); ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream(); File xsltFileName2 = new File(System.getProperty("base.dir"), settings.get("xsltFileName2")); ByteArrayInputStream inputStream2 = new ByteArrayInputStream(outputStream1.toByteArray()); // transformer.transformXML(inputStream2, xsltFileName2, outputStream2, settings); logger.info("Second transformation finished"); File outputFile = new File(graphmlDir, "bgpPeeringMap.graphml"); File nodesFileListFile = new File(graphmlDir, "nodes-file-list.txt"); FileUtils.writeStringToFile(outputFile, new String(outputStream2.toByteArray())); logger.info("Output Graphml saved in a file in" + graphmlDir); FileUtils.writeStringToFile(nodesFileListFile, "bgpPeeringMap.graphml"); ByteArrayInputStream inputStream3 = new ByteArrayInputStream(outputStream2.toByteArray()); ByteArrayOutputStream outputStream3 = new ByteArrayOutputStream(); File xsltFileName3 = new File(System.getProperty("base.dir"), settings.get("xsltFileName3")); // transformer.transformXML(inputStream3, xsltFileName3, outputStream3); }
From source file:net.itransformers.snmp2xml4j.snmptoolkit.XsltExecutor.java
/** * <p>main.</p>//from w w w . ja v a 2 s. c om * * @param args an array of {@link java.lang.String} objects. * @throws java.io.IOException if any. */ public static void main(String[] args) throws IOException { if (args.length != 3 && args.length != 4) { System.out.println("Missing input parameters"); System.out.println( " Example usage: xsltTransform.sh /home/test/test.xslt /usr/data/Input.xml /usr/data/Output.xml "); return; } String inputXslt = args[0]; if (inputXslt == null) { System.out.println("Missing input xslt file path"); System.out.println( " Example usage: xsltTransformer.sh /home/test/test.xslt /usr/data/Input.xml /usr/data/Output.xml"); return; } String inputFilePath = args[1]; if (inputFilePath == null) { System.out.println("Missing input xml file path"); System.out.println( " Example usage: xsltTransformer.sh /home/test/test.xslt /usr/data/Input.xml /usr/data/Output.xml"); return; } String outputFilePath = args[2]; if (outputFilePath == null) { System.out.println("Missing output file path"); System.out.println( " Example usage: xsltTransformer.sh /home/test/test.xslt /usr/data/Input.xml /usr/data/Output.xml"); return; } Map params = new HashMap<String, String>(); if (args.length == 4) { String deviceOS = args[3]; if (deviceOS != null) { params.put("DeviceOS", deviceOS); } } ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream(); File xsltFileName1 = new File(inputXslt); FileInputStream inputStream1 = new FileInputStream(new File(inputFilePath)); XsltTransformer xsltTransformer = new XsltTransformer(); try { xsltTransformer.transformXML(inputStream1, xsltFileName1, outputStream1, params); } catch (TransformerException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (SAXException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } FileUtils.writeStringToFile(new File(outputFilePath), new String(outputStream1.toByteArray())); System.out.println("Done! please review the transformed file " + outputFilePath); }
From source file:Tester.java
public static void main(String[] args) throws Exception { final String filename = "fcl/generated.fcl"; final String[] linguisticTermNames = { "muuuuuuypeque", "muypeque", "peque", "normal", "grande", "muygrande", "muuuuygrande" }; final RegionDistributionInfo[] linguisticTerms = new RegionDistributionInfo[linguisticTermNames.length]; for (int i = 0; i < linguisticTermNames.length; ++i) linguisticTerms[i] = new RegionDistributionInfo(linguisticTermNames[i], 1.0 / (linguisticTerms.length - 1)); final boolean database = true; System.out.println("Creating dataset " + System.currentTimeMillis()); final MobileDevices mobileDevices = createDataset(database); System.out.println(mobileDevices.getMobileDevices().size()); final Map<DeviceCapability, Variable> inputVariables = new HashMap<DeviceCapability, Variable>(); final Variable realSizeVar = new Variable("real_size", Arrays.asList(linguisticTerms)); final Variable resoSizeVar = new Variable("reso_size", Arrays.asList(linguisticTerms)); inputVariables.put(DeviceCapability.real_size, realSizeVar); inputVariables.put(DeviceCapability.reso_size, resoSizeVar); final Map<String, Variable> outputVariables = new HashMap<String, Variable>(); outputVariables.put("hey", new Variable("hey", Arrays.asList(new RegionDistributionInfo("ho", 1.0 / 2), new RegionDistributionInfo("lets", 1.0 / 2), new RegionDistributionInfo("go", 1.0 / 2)))); final String rules = "// the rules \n"; final FclCreator creator = new FclCreator(); System.out.println("Creating rule file " + System.currentTimeMillis()); final WarningStore warningStore = new WarningStore(); final String fileContent = creator.createRuleFile("prueba", inputVariables, new HashMap<UserCapability, Variable>(), outputVariables, mobileDevices, rules, warningStore); warningStore.print();// w w w .j a v a 2 s. com final File file = new File(filename); file.createNewFile(); System.out.println("Dumping the rule file " + System.currentTimeMillis()); FileUtils.writeStringToFile(file, fileContent); System.out.println("Processing the file " + System.currentTimeMillis()); final FIS fis = FIS.load(filename, true); net.sourceforge.jFuzzyLogic.rule.Variable realSize = fis.getVariable("real_size"); JFreeChart theChart = realSize.chart(false); @SuppressWarnings("unused") BufferedImage img = theChart.createBufferedImage(1000, 1000); /* FileOutputStream fos = new FileOutputStream("imagen.png"); ImageEncoder myEncoder = ImageEncoderFactory.newInstance("png"); myEncoder.encode(img, fos); fos.flush(); fos.close(); */ fis.chart(); }
From source file:com.verizon.Main.java
public static void main(String[] args) throws Exception { String warehouseLocation = "file:" + System.getProperty("user.dir") + "spark-warehouse"; SparkSession spark = SparkSession.builder().appName("Verizon").config("spark.master", "local[2]") .config("spark.sql.warehouse.dir", warehouseLocation).enableHiveSupport().getOrCreate(); Configuration configuration = new Configuration(); configuration.addResource(new Path(System.getProperty("HADOOP_INSTALL") + "/conf/core-site.xml")); configuration.addResource(new Path(System.getProperty("HADOOP_INSTALL") + "/conf/hdfs-site.xml")); configuration.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName()); configuration.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName()); FileSystem hdfs = FileSystem.get(new URI("hdfs://localhost:9000"), configuration); SQLContext context = new SQLContext(spark); String schemaString = " Device,Title,ReviewText,SubmissionTime,UserNickname"; //spark.read().textFile(schemaString) Dataset<Row> df = spark.read().csv("hdfs://localhost:9000/data.csv"); //df.show();/* w w w . ja va 2s. c o m*/ //#df.printSchema(); df = df.select("_c2"); Path file = new Path("hdfs://localhost:9000/tempFile.txt"); if (hdfs.exists(file)) { hdfs.delete(file, true); } df.write().csv("hdfs://localhost:9000/tempFile.txt"); JavaRDD<String> lines = spark.read().textFile("hdfs://localhost:9000/tempFile.txt").javaRDD(); JavaRDD<String> words = lines.flatMap(new FlatMapFunction<String, String>() { @Override public Iterator<String> call(String s) { return Arrays.asList(SPACE.split(s)).iterator(); } }); JavaPairRDD<String, Integer> ones = words.mapToPair(new PairFunction<String, String, Integer>() { @Override public Tuple2<String, Integer> call(String s) { s = s.replaceAll("[^a-zA-Z0-9]+", ""); s = s.toLowerCase().trim(); return new Tuple2<>(s, 1); } }); JavaPairRDD<String, Integer> counts = ones.reduceByKey(new Function2<Integer, Integer, Integer>() { @Override public Integer call(Integer i1, Integer i2) { return i1 + i2; } }); JavaPairRDD<Integer, String> frequencies = counts .mapToPair(new PairFunction<Tuple2<String, Integer>, Integer, String>() { @Override public Tuple2<Integer, String> call(Tuple2<String, Integer> s) { return new Tuple2<Integer, String>(s._2, s._1); } }); frequencies = frequencies.sortByKey(false); JavaPairRDD<String, Integer> result = frequencies .mapToPair(new PairFunction<Tuple2<Integer, String>, String, Integer>() { @Override public Tuple2<String, Integer> call(Tuple2<Integer, String> s) throws Exception { return new Tuple2<String, Integer>(s._2, s._1); } }); //JavaPairRDD<Integer,String> sortedByFreq = sort(frequencies, "descending"); file = new Path("hdfs://localhost:9000/allresult.csv"); if (hdfs.exists(file)) { hdfs.delete(file, true); } //FileUtils.deleteDirectory(new File("allresult.csv")); result.saveAsTextFile("hdfs://localhost:9000/allresult.csv"); List<Tuple2<String, Integer>> output = result.take(250); ExportToHive hiveExport = new ExportToHive(); String rows = ""; for (Tuple2<String, Integer> tuple : output) { String date = new Date().toString(); String keyword = tuple._1(); Integer count = tuple._2(); //System.out.println( keyword+ "," +count); rows += date + "," + "Samsung Galaxy s7," + keyword + "," + count + System.lineSeparator(); } //System.out.println(rows); /* file = new Path("hdfs://localhost:9000/result.csv"); if ( hdfs.exists( file )) { hdfs.delete( file, true ); } OutputStream os = hdfs.create(file); BufferedWriter br = new BufferedWriter( new OutputStreamWriter( os, "UTF-8" ) ); br.write(rows); br.close(); */ hdfs.close(); FileUtils.deleteQuietly(new File("result.csv")); FileUtils.writeStringToFile(new File("result.csv"), rows); hiveExport.writeToHive(spark); ExportDataToServer exportServer = new ExportDataToServer(); exportServer.sendDataToRESTService(rows); spark.stop(); }
From source file:edu.lternet.pasta.client.EmlUtility.java
/** * @param args String array with three arguments: * arg[0] absolute path to the input XML file * arg[1] absolute path to the output HTML file * arg[2] absolute path to the EML XSLT stylesheet */// w w w .jav a2 s. c o m public static void main(String[] args) { String inputPath = args[0]; String outputPath = args[1]; String emlXslPath = args[2]; ConfigurationListener.configure(); File inFile = new File(inputPath); File outFile = new File(outputPath); String eml = null; try { eml = FileUtils.readFileToString(inFile); } catch (IOException e1) { logger.error(e1.getMessage()); e1.printStackTrace(); } EmlUtility eu = null; try { eu = new EmlUtility(eml); } catch (ParseException e) { logger.error(e.getMessage()); e.printStackTrace(); } String html = eu.xmlToHtml(emlXslPath, null); try { FileUtils.writeStringToFile(outFile, html); } catch (IOException e) { logger.error(e.getMessage()); e.printStackTrace(); } }
From source file:com.wittawat.wordseg.Main.java
public static void main(String[] args) throws Exception { Console con = System.console(); if (con == null) { System.out.println("The system must support console to run the program."); System.exit(1);//from w w w.j a v a 2 s. com } // Load model System.out.println("Loading model ..."); Classifier model = Data.getDefaultModel(); System.out.println("Finished loading model."); System.out.println(getAgreement()); boolean isUseDict = true; // Dummy statement to eliminate all lazy loading System.out.println("\n" + new NukeTokenizer3( "?????", model, isUseDict).tokenize() + "\n"); System.out.println(getHelp()); final String SET_DICT_PAT_STR = "\\s*set\\s+dict\\s+(true|false)\\s*"; final Pattern SET_DICT_PAT = Pattern.compile(SET_DICT_PAT_STR); while (true) { System.out.print(">> "); String line = con.readLine(); if (line != null && !line.trim().equals("")) { line = line.trim(); try { if (line.equals("h") || line.equals("help")) { System.out.println(getHelp()); } else if (line.equals("about")) { System.out.println(getAbout()); } else if (line.equals("agreement")) { System.out.println(getAgreement()); } else if (SET_DICT_PAT.matcher(line).find()) { Matcher m = SET_DICT_PAT.matcher(line); m.find(); String v = m.group(1); isUseDict = v.equals("true"); System.out.println("Dictionary will " + (isUseDict ? "" : "not ") + "be used."); } else if (line.matches("q|quit|exit")) { System.out.println("Bye"); System.exit(0); } else if (line.contains(":tokfile:")) { String[] splits = line.split(":tokfile:"); String in = splits[0]; String out = splits[1]; String content = FileUtils.readFileToString(new File(in)); long start = new Date().getTime(); NukeTokenizer tokenizer = new NukeTokenizer3(content, model, isUseDict); String tokenized = tokenizer.tokenize(); long end = new Date().getTime(); System.out.println("Time to tokenize: " + (end - start) + " ms."); FileUtils.writeStringToFile(new File(out), tokenized); } else if (line.contains(":tokfile")) { String[] splits = line.split(":tokfile"); String in = splits[0]; String content = FileUtils.readFileToString(new File(in)); long start = new Date().getTime(); NukeTokenizer tokenizer = new NukeTokenizer3(content, model, isUseDict); String tokenized = tokenizer.tokenize(); long end = new Date().getTime(); System.out.println(tokenized); System.out.println("Time to tokenize: " + (end - start) + " ms."); } else if (line.contains(":tok:")) { String[] splits = line.split(":tok:"); String inText = splits[0]; String out = splits[1]; long start = new Date().getTime(); NukeTokenizer tokenizer = new NukeTokenizer3(inText, model, isUseDict); String tokenized = tokenizer.tokenize(); long end = new Date().getTime(); System.out.println("Time to tokenize: " + (end - start) + " ms."); FileUtils.writeStringToFile(new File(out), tokenized); } else if (line.contains(":tok")) { String[] splits = line.split(":tok"); String inText = splits[0]; long start = new Date().getTime(); NukeTokenizer tokenizer = new NukeTokenizer3(inText, model, isUseDict); String tokenized = tokenizer.tokenize(); long end = new Date().getTime(); System.out.println(tokenized); System.out.println("Time to tokenize: " + (end - start) + " ms."); } else { System.out.println("Unknown command"); } } catch (Exception e) { System.out.println("Error. See the exception."); e.printStackTrace(); } } } }
From source file:CalcoloRitardiLotti.java
public static void main(String[] args) { String id_ref = "cbededce-269f-48d2-8c25-2359bf246f42"; String requestString = "http://dati.openexpo2015.it/catalog/api/action/datastore_search?resource_id=" + id_ref;/*from w ww.j a v a 2 s. co m*/ HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(requestString); try { HttpResponse response = client.execute(request); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String result = ""; String resline = ""; Calendar c = Calendar.getInstance(); Date current = Date.valueOf( c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH)); while ((resline = rd.readLine()) != null) result += resline; //System.out.println(jsonObject.toString()); if (result != null) { JSONObject jsonObject = new JSONObject(result); JSONObject resultJson = (JSONObject) jsonObject.get("result"); JSONArray records = (JSONArray) resultJson.get("records"); Date temp1, temp2; //System.out.printf(records.toString()); long diffInizioFineLavori; long ritardo; long den = (24 * 60 * 60 * 1000); JSONObject temp; DefaultCategoryDataset cdata = new DefaultCategoryDataset(); String partialQuery; DefaultPieDataset data = new DefaultPieDataset(); String totalQuery = ""; int countSospesi = 0; int countConclusi = 0; int countVerifica = 0; int countInCorso = 0; int countCollaudo = 0; String stato; for (int i = 0; i < records.length(); i++) { temp = (JSONObject) records.get(i); temp1 = Date.valueOf((temp.getString("Data Consegna Lavori")).substring(0, 10)); temp2 = Date.valueOf((temp.getString("Data Fine lavori")).substring(0, 10)); diffInizioFineLavori = (long) (temp2.getTime() - temp1.getTime()) / den; stato = temp.getString("STATO"); if (stato.equals("Concluso")) countConclusi++; else if (stato.equals("In corso")) countInCorso++; else if (stato.contains("Verifiche")) countVerifica++; else if (stato.contains("Collaudo sospeso") || stato.contains("sospeso")) countSospesi++; else countCollaudo++; if (!temp.getString("STATO").equals("Concluso") && temp2.getTime() < current.getTime()) ritardo = (long) (current.getTime() - temp2.getTime()) / den; else ritardo = 0; cdata.setValue(ritardo, String.valueOf(i + 1), String.valueOf(i + 1)); System.out.println( "Opera: " + temp.getString("Oggetto del lotto") + " | id: " + temp.getInt("_id")); System.out.println("Data consegna lavoro: " + temp.getString("Data Consegna Lavori") + " | Data fine lavoro: " + temp.getString("Data Fine lavori")); System.out.println("STATO: " + temp.getString("STATO")); System.out.println("Differenza in giorni: " + diffInizioFineLavori + " | Numero giorni contrattuali: " + temp.getString("numero di giorni contrattuali")); System.out.println("Ritardo accumulato: " + ritardo); System.out.println("----------------------------------"); partialQuery = "\nid: " + temp.getInt("_id") + "\nOpera:" + temp.getString("Oggetto del lotto") + "\n" + "Data consegna lavoro: " + temp.getString("Data Consegna Lavori") + "Data fine lavoro: " + temp.getString("Data Fine lavori") + "\n" + "STATO: " + temp.getString("STATO") + "\n" + "Differenza in giorni: " + diffInizioFineLavori + " - Numero giorni contrattuali: " + temp.getString("numero di giorni contrattuali") + "\n" + "Ritardo accumulato: " + ritardo + "\n" + "----------------------------------\n"; totalQuery = totalQuery + partialQuery; } JFreeChart chart1 = ChartFactory.createBarChart3D("RITARDI AL " + current, "Id lotto", "ritardo(in giorni)", cdata); ChartRenderingInfo info = null; ChartUtilities.saveChartAsPNG( new File(System.getProperty("user.dir") + "/istogramma" + current + ".png"), chart1, 1500, 1500, info, true, 10); FileUtils.writeStringToFile(new File(current + "_1.txt"), totalQuery); data.setValue("Conclusi: " + countConclusi, countConclusi); data.setValue("Sospeso: " + countSospesi, countSospesi); data.setValue("In Corso: " + countInCorso, countInCorso); data.setValue("Verifica: " + countVerifica, countVerifica); data.setValue("Collaudo: " + countCollaudo, countCollaudo); JFreeChart chart2 = ChartFactory.createPieChart3D("Statistiche del " + current, data, true, true, true); ChartUtilities.saveChartAsPNG(new File(System.getProperty("user.dir") + "/pie" + current + ".png"), chart2, 800, 450); } } catch (Exception e) { e.printStackTrace(); } }