List of usage examples for java.io FileWriter flush
public void flush() throws IOException
From source file:com.alibaba.dubbo.monitor.simple.SimpleMonitorService.java
private void write() throws Exception { URL statistics = queue.take(); if (POISON_PROTOCOL.equals(statistics.getProtocol())) { return;// ww w . j a v a 2 s . com } String timestamp = statistics.getParameter(Constants.TIMESTAMP_KEY); Date now; if (timestamp == null || timestamp.length() == 0) { now = new Date(); } else if (timestamp.length() == "yyyyMMddHHmmss".length()) { now = new SimpleDateFormat("yyyyMMddHHmmss").parse(timestamp); } else { now = new Date(Long.parseLong(timestamp)); } String day = new SimpleDateFormat("yyyyMMdd").format(now); SimpleDateFormat format = new SimpleDateFormat("HHmm"); for (String key : types) { try { String type; String consumer; String provider; if (statistics.hasParameter(PROVIDER)) { type = CONSUMER; consumer = statistics.getHost(); provider = statistics.getParameter(PROVIDER); int i = provider.indexOf(':'); if (i > 0) { provider = provider.substring(0, i); } } else { type = PROVIDER; consumer = statistics.getParameter(CONSUMER); int i = consumer.indexOf(':'); if (i > 0) { consumer = consumer.substring(0, i); } provider = statistics.getHost(); } String filename = statisticsDirectory + "/" + day + "/" + statistics.getServiceInterface() + "/" + statistics.getParameter(METHOD) + "/" + consumer + "/" + provider + "/" + type + "." + key; File file = new File(filename); File dir = file.getParentFile(); if (dir != null && !dir.exists()) { dir.mkdirs(); } FileWriter writer = new FileWriter(file, true); try { writer.write(format.format(now) + " " + statistics.getParameter(key, 0) + "\n"); writer.flush(); } finally { writer.close(); } } catch (Throwable t) { logger.error(t.getMessage(), t); } } }
From source file:com.me.edu.Servlet.ElasticSearch_Backup.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { String filepath = request.getParameter("hiddenPath"); String fileName = request.getParameter("hiddenFileName"); /* TODO output your page here. You may use following sample code. */ Tika tika = new Tika(); final File folder = new File(filepath); String fileEntry = filepath + fileName; String filetype = tika.detect(fileEntry); System.out.println("FileType " + filetype); BodyContentHandler handler = new BodyContentHandler(-1); Metadata metadata = new Metadata(); FileInputStream inputstream = null; try {//from w w w . ja v a 2 s . com inputstream = new FileInputStream(fileEntry); } catch (FileNotFoundException ex) { Logger.getLogger(ElasticSearch.class.getName()).log(Level.SEVERE, null, ex); } ParseContext pcontext = new ParseContext(); //parsing the document using PDF parser PDFParser pdfparser = new PDFParser(); try { pdfparser.parse(inputstream, handler, metadata, pcontext); } catch (IOException ex) { Logger.getLogger(ElasticSearch.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(ElasticSearch.class.getName()).log(Level.SEVERE, null, ex); } catch (TikaException ex) { Logger.getLogger(ElasticSearch.class.getName()).log(Level.SEVERE, null, ex); } //getting the content of the document String docText = handler.toString().replaceAll("(/[^\\da-zA-Z.]/)", ""); String outputArray[] = docText.split("Article|Section|Borrower|Agents"); try { //Put The Defined Terms in the elastic search parseString(docText); out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet ElasticSearch</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet ElasticSearch at " + request.getContextPath() + "</h1>"); getDocument(out, client, "definedterms", "term", "Accounts"); getDocument(out, client, "definedterms", "term", "Accountant"); out.println("</body>"); out.println("</html>"); } catch (FileNotFoundException ex) { Logger.getLogger(ElasticSearch.class.getName()).log(Level.SEVERE, null, ex); } docText = cleanStopWords(docText); Set<String> allCapsWords = new HashSet<>(); Pattern p = Pattern.compile("\\b[A-Z]{2,}\\b"); Matcher m = p.matcher(docText); while (m.find()) { String word = m.group(); // System.out.println(word); allCapsWords.add(word); } for (String allcaps : allCapsWords) { // System.out.println(allcaps); } System.out.println("Caps word count" + allCapsWords.size()); org.json.simple.JSONObject obj = new org.json.simple.JSONObject(); int count = 0; for (String output : outputArray) { obj.put(String.valueOf(count), output.replaceAll("\\s+", " ")); count++; } try { FileWriter file = new FileWriter("filename.json"); file.write(obj.toJSONString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } } catch (IOException ex) { Logger.getLogger(ElasticSearch.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:dk.netarkivet.archive.checksum.DatabaseChecksumArchive.java
@Override public File correct(String filename, File correctFile) throws IOFailure, ArgumentNotValid, IllegalState { ArgumentNotValid.checkNotNullOrEmpty(filename, "String filename"); ArgumentNotValid.checkNotNull(correctFile, "File correctFile"); // If no file entry exists, then IllegalState if (!hasEntry(filename)) { String errMsg = "No file entry for file '" + filename + "'."; log.error(errMsg);//w w w . j a v a2s .com throw new IllegalState(errMsg); } // retrieve the checksum String currentChecksum = getChecksum(filename); // Calculate the new checksum and verify that it is different. String newChecksum = calculateChecksum(correctFile); if (newChecksum.equals(currentChecksum)) { // This should never occur. throw new IllegalState("The checksum of the old 'bad' entry is " + " the same as the checksum of the new correcting entry"); } // Make entry in the wrongEntryFile. String badEntry = ChecksumJob.makeLine(filename, currentChecksum); appendWrongRecordToWrongEntryFile(badEntry); // Correct the bad entry, by changing the value to the newChecksum.' // Since the checksumArchive is a hashmap, then putting an existing // entry with a new value will override the existing one. put(filename, newChecksum); // Make the file containing the bad entry be returned in the // CorrectMessage. File removedEntryFile; try { // Initialise file and writer. removedEntryFile = File.createTempFile(filename, "tmp", FileUtils.getTempDir()); FileWriter fw = new FileWriter(removedEntryFile); // Write the bad entry. fw.write(badEntry); // flush and close. fw.flush(); fw.close(); } catch (IOException e) { throw new IOFailure("Unable to create return file for CorrectMessage", e); } // Return the file containing the removed entry. return removedEntryFile; }
From source file:gov.nih.nci.cacis.mirth.XSLForMirthFormatter.java
/** * Formats one XSL file for Mirth//from ww w .ja va2 s . c om * * @param outputDir - File instance for the output dir * @param xsl - String representing the path to the xsl file * @throws IOException - error thrown, if any */ public void formatSingleXSl(File outputDir, String xsl) throws IOException { File xslF = null; File formattedF = null; FileWriter fw = null; String xslContent = null; String formattedContent = null; try { xslF = new File(xsl); formattedF = new File(outputDir, xslF.getName()); fw = new FileWriter(formattedF); xslContent = FileUtils.readFileToString(xslF); // htmlencode content formattedContent = StringEscapeUtils.escapeXml(xslContent); // escape all dollar signs formattedContent = formattedContent.replaceAll("\\$", "\\\\\\$"); fw.write(formattedContent); fw.flush(); } catch (IOException e) { LOG.debug("Error writing formatted xsl", e); throw e; } finally { if (fw != null) { try { fw.close(); } catch (IOException e) { LOG.debug("Error while closing the output writer", e); } } } }
From source file:org.ala.spatial.web.services.SitesBySpeciesWSControllerTabulated.java
private void initListProperties() throws IOException { //create a list.properties if it does not exist String pth = AlaspatialProperties.getAnalysisWorkingDir() + File.separator + "sxs" + File.separator; File f = new File(pth + "list.properties"); if (!f.exists()) { new File(pth).mkdir(); FileWriter fw = new FileWriter(f); fw.write("1=q=tasmanian%20devil&gridsize=0.01&layers=aus1\n" + "2=q=tasmanian%20devil&gridsize=0.1&layers=aus1\n" + "3=q=tasmanian%20devil&gridsize=10&layers=aus1"); fw.flush(); fw.close();/* w ww .j a va 2s .c o m*/ } }
From source file:bridge.toolkit.commands.PDFBuilder.java
/** * @see org.apache.commons.chain.Command#execute(org.apache.commons.chain.Context) */// w w w . ja va 2s . com @Override public boolean execute(Context ctx) { System.out.println("Executing PDF Builder"); String resource_dir = (String) ctx.get(Keys.RESOURCE_PACKAGE); ContentPackageCreator cpc = new ContentPackageCreator(resource_dir); try { src_dir = cpc.createPackage(); } catch (IOException e1) { System.out.println(PDFBUILDER_FAILED); e1.printStackTrace(); return PROCESSING_COMPLETE; } catch (JDOMException e1) { System.out.println(PDFBUILDER_FAILED); e1.printStackTrace(); return PROCESSING_COMPLETE; } scpm_file = (String) ctx.get(Keys.SCPM_FILE); List<File> src_files = new ArrayList<File>(); try { src_files = URNMapper.getSourceFiles(resource_dir); } catch (NullPointerException npe) { System.out.println(PDFBUILDER_FAILED); System.out.println("The 'Resource Package' is empty."); return PROCESSING_COMPLETE; } catch (JDOMException e) { System.out.println(PDFBUILDER_FAILED); e.printStackTrace(); return PROCESSING_COMPLETE; } catch (IOException e) { System.out.println(PDFBUILDER_FAILED); e.printStackTrace(); return PROCESSING_COMPLETE; } urn_map = URNMapper.writeURNMap(src_files, ""); String Stylesheet = ""; String filenameending = ""; try { //Apply css to the data modules StylesheetApplier sa = new StylesheetApplier(); if (((String) ctx.get(Keys.PDF_OUTPUT_OPTION)) == "-instructor") { sa.applyStylesheetToDMCs(src_dir, INSTRUCTORPDFSTYLESHEET, "css", " media='all'"); Stylesheet = INSTRUCTORPDFSTYLESHEET; filenameending = "-instructor"; } else { sa.applyStylesheetToDMCs(src_dir, STUDENTPDFSTYLESHEET, "css", " media='all'"); Stylesheet = STUDENTPDFSTYLESHEET; filenameending = "-student"; } } catch (JDOMException e) { System.out.println(PDFBUILDER_FAILED); e.printStackTrace(); return PROCESSING_COMPLETE; } catch (IOException e) { System.out.println(PDFBUILDER_FAILED); e.printStackTrace(); return PROCESSING_COMPLETE; } //Copy the css file to the data modules location try { CopyDirectory cd = new CopyDirectory(); //check if the directory exists if it does use it else copy it from the jar File pdfCss = new File( System.getProperty("user.dir") + File.separator + "pdfCSS" + File.separator + Stylesheet); if (pdfCss.exists()) { cd.copyDirectory(pdfCss, new File(src_dir + File.separator + "resources" + File.separator + "s1000d")); } else { cd.CopyJarFiles(this.getClass(), "pdfCSS", src_dir + File.separator + "resources" + File.separator + "s1000d"); } } catch (FileNotFoundException e) { System.out.println(PDFBUILDER_FAILED); e.printStackTrace(); return PROCESSING_COMPLETE; } catch (IOException e) { System.out.println(PDFBUILDER_FAILED); e.printStackTrace(); return PROCESSING_COMPLETE; } try { transform = this.getClass().getResourceAsStream(TRANSFORM_FILE); doTransform(scpm_file); } catch (TransformerException e) { System.out.println(PDFBUILDER_FAILED); e.printStackTrace(); return PROCESSING_COMPLETE; } catch (JDOMException e) { System.out.println("Content Package creation was unsuccessful"); e.printStackTrace(); return PROCESSING_COMPLETE; } catch (IOException e) { System.out.println(PDFBUILDER_FAILED); e.printStackTrace(); return PROCESSING_COMPLETE; } XMLOutputter imsoutputter = new XMLOutputter(Format.getPrettyFormat()); File imsfile = new File(src_dir + File.separator + "imsmanifest.xml"); try { //writes the imsmanfest.xml file out to the content package FileWriter writer = new FileWriter(imsfile, false); imsoutputter.output(manifest, writer); writer.flush(); writer.close(); } catch (java.io.IOException e) { System.out.println("Content Package creation was unsuccessful"); e.printStackTrace(); return PROCESSING_COMPLETE; } //get the organization title from the manifest file //replace any white spaces with Element title = null; XPath xp = null; try { xp = XPath.newInstance("//ns:organization//ns:title"); xp.addNamespace("ns", "http://www.imsglobal.org/xsd/imscp_v1p1"); title = (Element) xp.selectSingleNode(manifest); } catch (JDOMException e) { System.out.println("Content Package creation was unsuccessful"); e.printStackTrace(); return PROCESSING_COMPLETE; } String FileName = title.getValue(); try { String outputPath = ""; if (ctx.get(Keys.OUTPUT_DIRECTORY) != null) { outputPath = (String) ctx.get(Keys.OUTPUT_DIRECTORY); if (outputPath.length() > 0) { outputPath = outputPath + File.separator; } } File outputDir = new File(outputPath); if (!outputDir.exists()) { outputDir.mkdirs(); } String outputFile = outputDir.getAbsolutePath() + File.separator + FileName.trim() + filenameending + ".pdf"; OutputStream os = new FileOutputStream(outputFile); ITextRenderer renderer = new ITextRenderer(); DMParser dmp = new DMParser(); boolean created = false; xp = XPath.newInstance("//scoEntry[@scoEntryType='scot01']"); @SuppressWarnings("unchecked") List<Element> scos = xp.selectNodes(dmp.getDoc(new File(scpm_file))); Iterator<Element> iterator = scos.iterator(); while (iterator.hasNext()) { Element sco = iterator.next(); sco.detach(); Document temp = new Document(sco); List<String> dms = dmp.searchForDmRefs(temp); Iterator<String> childIterator = dms.iterator(); while (childIterator.hasNext()) { String urnDM = childIterator.next(); xp = XPath.newInstance("//urn[@name='URN:S1000D:" + urnDM + "']"); Element urn = (Element) xp.selectSingleNode(urn_map); File dataModule = new File(src_dir + File.separator + "resources" + File.separator + "s1000d" + File.separator + urn.getChild("target").getValue()); xp = XPath.newInstance("//graphic"); Document dmDoc = dmp.getDoc(dataModule); @SuppressWarnings("unchecked") List<Element> graphics = xp.selectNodes(dmDoc); Iterator<Element> graphicIterator = graphics.iterator(); while (graphicIterator.hasNext()) { Element graphic = graphicIterator.next(); Attribute infoEntityIdent = graphic.getAttribute("infoEntityIdent"); Element graphicParent = graphic.getParentElement(); Element img = new Element("img"); Attribute src = new Attribute("src", "file:///" + src_dir + File.separator + "resources" + File.separator + "s1000d" + File.separator + infoEntityIdent.getValue() + ".jpg"); img.setAttribute(src); graphicParent.addContent(img); XMLOutputter outputter = new XMLOutputter(Format.getRawFormat()); File updatedDM = new File(src_dir + File.separator + "resources" + File.separator + "s1000d" + File.separator + dataModule.getName()); FileWriter writer = new FileWriter(updatedDM); outputter.output(dmDoc, writer); writer.close(); } renderer.setDocument(dataModule); renderer.layout(); if (!created) { renderer.createPDF(os, false); created = true; } else { renderer.writeNextDocument(); } } } // complete the PDF renderer.finishPDF(); os.close(); System.out.println("Successfully created PDF"); } catch (JDOMException e) { System.out.println(PDFBUILDER_FAILED); e.printStackTrace(); return PROCESSING_COMPLETE; } catch (DocumentException e) { System.out.println(PDFBUILDER_FAILED); e.printStackTrace(); return PROCESSING_COMPLETE; } catch (FileNotFoundException e) { System.out.println(PDFBUILDER_FAILED); e.printStackTrace(); return PROCESSING_COMPLETE; } catch (IOException e) { System.out.println(PDFBUILDER_FAILED); e.printStackTrace(); return PROCESSING_COMPLETE; } catch (Exception e) { System.out.println(PDFBUILDER_FAILED); e.printStackTrace(); return PROCESSING_COMPLETE; } return CONTINUE_PROCESSING; }
From source file:com.ephesoft.dcma.cmis.CmisImport.java
/** * This api is used to send output to xml file. * @param document {@link org.jdom.Document} * @param destFile {@link String}// ww w . j av a2s . co m */ public void outputToXml(final org.jdom.Document document, final String destFile) { final XMLOutputter outputter = new XMLOutputter(); FileWriter writer = null; try { writer = new FileWriter(destFile); outputter.output(document, writer); } catch (final IOException e) { LOGGER.error("Error while generating cmis properties xml" + e.getMessage(), e); } finally { if (writer != null) { try { writer.flush(); writer.close(); } catch (final IOException e) { LOGGER.info("Error in closing output stream", e); } } } }
From source file:com.swdouglass.winter.Winter.java
public void generateClassFromTable(String inTableName, String inIdColumnName, String inPackageName) { String outputDir = System.getProperty("winter.output_dir", System.getProperty("user.dir")); // convert java package name to directory path StringBuilder sb = new StringBuilder(outputDir); sb.append(FS);//from www . jav a 2 s .c om String[] parts = inPackageName.split("\\."); for (int i = 0; i < parts.length; i++) { sb.append(parts[i]); sb.append(FS); } File packageDir = new File(sb.toString()); packageDir.mkdirs(); String className = dbNameToJavaName(inTableName, JAVA_CLASS); sb.append(className); StringBuilder hbm = new StringBuilder(sb.toString()); sb.append(".java"); File classFile = new File(sb.toString()); hbm.append(".hbm.xml"); File hbmFile = new File(hbm.toString()); try { FileWriter fw = new FileWriter(classFile); fw.write(readFileAsString(System.getProperty("winter.license", "license.txt"), JAVA_COMMENT)); fw.write(javaFromTable(inPackageName, className, inTableName, inIdColumnName)); fw.flush(); fw.close(); fw = new FileWriter(hbmFile); //fw.write(readFileAsString(System.getProperty("winter.license", "license.txt"), XML_COMMENT)); fw.write(hbmFromTable(inPackageName, className, inTableName, inIdColumnName)); fw.flush(); fw.close(); } catch (IOException ex) { logger.severe(ex.toString()); } }
From source file:com.greatmancode.craftconomy3.utils.OldFormatConverter.java
public void run() throws SQLException, IOException, ParseException { String dbType = Common.getInstance().getMainConfig().getString("System.Database.Type"); HikariConfig config = new HikariConfig(); if (dbType.equalsIgnoreCase("mysql")) { config.setMaximumPoolSize(10);/*from w ww .j a v a 2 s .c o m*/ config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource"); config.addDataSourceProperty("serverName", Common.getInstance().getMainConfig().getString("System.Database.Address")); config.addDataSourceProperty("port", Common.getInstance().getMainConfig().getString("System.Database.Port")); config.addDataSourceProperty("databaseName", Common.getInstance().getMainConfig().getString("System.Database.Db")); config.addDataSourceProperty("user", Common.getInstance().getMainConfig().getString("System.Database.Username")); config.addDataSourceProperty("password", Common.getInstance().getMainConfig().getString("System.Database.Password")); config.addDataSourceProperty("autoDeserialize", true); config.setConnectionTimeout(5000); db = new HikariDataSource(config); } else if (dbType.equalsIgnoreCase("sqlite")) { config.setDriverClassName("org.sqlite.JDBC"); config.setJdbcUrl("jdbc:sqlite:" + Common.getInstance().getServerCaller().getDataFolder() + File.separator + "database.db"); db = new HikariDataSource(config); } else { Common.getInstance().sendConsoleMessage(Level.SEVERE, "Unknown database type for old format converter!"); return; } Connection connection = db.getConnection(); this.tablePrefix = Common.getInstance().getMainConfig().getString("System.Database.Prefix"); File accountFile = new File(Common.getInstance().getServerCaller().getDataFolder(), "accounts.json"); Common.getInstance().sendConsoleMessage(Level.INFO, "Doing a backup in a xml file before doing the conversion."); //Document setup JSONObject mainObject = new JSONObject(); Common.getInstance().sendConsoleMessage(Level.INFO, "Saving currency table"); //Currencies PreparedStatement statement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "currency"); ResultSet set = statement.executeQuery(); JSONArray array = new JSONArray(); while (set.next()) { JSONObject entry = new JSONObject(); entry.put("id", set.getInt("id")); entry.put("name", set.getString("name")); entry.put("plural", set.getString("plural")); entry.put("minor", set.getString("minor")); entry.put("minorPlural", set.getString("minorPlural")); entry.put("sign", set.getString("sign")); entry.put("status", set.getBoolean("status")); array.add(entry); } statement.close(); mainObject.put("currencies", array); //World groups Common.getInstance().sendConsoleMessage(Level.INFO, "Saving world group table"); array = new JSONArray(); statement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "worldgroup"); set = statement.executeQuery(); while (set.next()) { JSONObject entry = new JSONObject(); entry.put("groupName", set.getString("groupName")); entry.put("worldList", set.getString("worldList")); array.add(entry); } statement.close(); mainObject.put("worldgroups", array); //Exchange table Common.getInstance().sendConsoleMessage(Level.INFO, "Saving exchange table"); array = new JSONArray(); statement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "exchange"); set = statement.executeQuery(); while (set.next()) { JSONObject entry = new JSONObject(); entry.put("from_currency_id", set.getInt("from_currency_id")); entry.put("to_currency_id", set.getInt("to_currency_id")); entry.put("amount", set.getDouble("amount")); array.add(entry); } statement.close(); mainObject.put("exchanges", array); //config table Common.getInstance().sendConsoleMessage(Level.INFO, "Saving config table"); array = new JSONArray(); statement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "config"); set = statement.executeQuery(); while (set.next()) { JSONObject entry = new JSONObject(); entry.put("name", set.getString("name")); entry.put("value", set.getString("value")); array.add(entry); } statement.close(); mainObject.put("configs", array); //account table Common.getInstance().sendConsoleMessage(Level.INFO, "Saving account table"); array = new JSONArray(); statement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "account"); set = statement.executeQuery(); while (set.next()) { JSONObject entry = new JSONObject(); entry.put("name", set.getString("name")); entry.put("infiniteMoney", set.getBoolean("infiniteMoney")); entry.put("ignoreACL", set.getBoolean("ignoreACL")); entry.put("uuid", set.getString("uuid")); JSONArray balanceArray = new JSONArray(); PreparedStatement internalStatement = connection .prepareStatement("SELECT * FROM " + tablePrefix + "balance WHERE username_id=?"); internalStatement.setInt(1, set.getInt("id")); ResultSet internalSet = internalStatement.executeQuery(); while (internalSet.next()) { JSONObject object = new JSONObject(); object.put("currency_id", internalSet.getInt("currency_id")); object.put("worldName", internalSet.getString("worldName")); object.put("balance", internalSet.getDouble("balance")); balanceArray.add(object); } internalStatement.close(); entry.put("balances", balanceArray); internalStatement = connection .prepareStatement("SELECT * FROM " + tablePrefix + "log WHERE username_id=?"); internalStatement.setInt(1, set.getInt("id")); internalSet = internalStatement.executeQuery(); JSONArray logArray = new JSONArray(); while (internalSet.next()) { JSONObject object = new JSONObject(); object.put("type", internalSet.getObject("type")); object.put("cause", internalSet.getObject("cause")); object.put("timestamp", internalSet.getTimestamp("timestamp")); object.put("causeReason", internalSet.getString("causeReason")); object.put("currencyName", internalSet.getString("currencyName")); object.put("worldName", internalSet.getString("worldName")); object.put("amount", internalSet.getDouble("amount")); logArray.add(object); } internalStatement.close(); entry.put("logs", logArray); internalStatement = connection .prepareStatement("SELECT * FROM " + tablePrefix + "acl WHERE account_id=?"); internalStatement.setInt(1, set.getInt("id")); internalSet = internalStatement.executeQuery(); JSONArray aclArray = new JSONArray(); while (internalSet.next()) { JSONObject object = new JSONObject(); object.put("playerName", internalSet.getString("playerName")); object.put("deposit", internalSet.getBoolean("deposit")); object.put("withdraw", internalSet.getBoolean("withdraw")); object.put("acl", internalSet.getBoolean("acl")); object.put("balance", internalSet.getBoolean("balance")); object.put("owner", internalSet.getBoolean("owner")); aclArray.add(object); } internalStatement.close(); entry.put("acls", aclArray); array.add(entry); } statement.close(); mainObject.put("accounts", array); Common.getInstance().sendConsoleMessage(Level.INFO, "Writing json file"); FileWriter writer = new FileWriter(accountFile); writer.write(mainObject.toJSONString()); writer.flush(); writer.close(); Common.getInstance().sendConsoleMessage(Level.INFO, "File written! Dropping all tables"); //The backup is now saved. Let's drop everything statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "config"); statement.execute(); statement.close(); statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "acl"); statement.execute(); statement.close(); statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "balance"); statement.execute(); statement.close(); statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "log"); statement.execute(); statement.close(); statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "worldgroup"); statement.execute(); statement.close(); statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "exchange"); statement.execute(); statement.close(); statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "account"); statement.execute(); statement.close(); statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "currency"); statement.execute(); statement.close(); statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "payday"); statement.execute(); statement.close(); connection.close(); step2(); }
From source file:com.mum.app.AutoSubmitPriceApp.java
public void CheckAndSubmitPrice() { Date dt = new Date(); DateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss"); String dtstr = format.format(dt); Map<String, Float> submitSkuMap = new HashMap<String, Float>(); for (Entry<String, MyPriceInfo> entry : mapMyPriceInfo.entrySet()) { String asin = entry.getKey(); Float newMyPrice = CheckStrategy(asin, entry.getValue()); if (null != newMyPrice) { MyLog.log.log(Level.INFO, "Submit price:" + asin + ":" + newMyPrice); submitSkuMap.put(entry.getValue().sellerSKU, newMyPrice); }//from w ww . j ava 2 s .c o m } if (!submitSkuMap.isEmpty()) { String xml = BuildSubmitPriceXml(submitSkuMap); MyLog.log.log(Level.INFO, "Submit XML:\n" + xml); String xmlFilename = AutoSubmitPriceConfig.submitPriceFile + "SubmitPrice_" + dtstr + ".xml"; try { FileWriter fileWriter = new FileWriter(xmlFilename, false); fileWriter.write(xml); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } if (true) { SubmitPriceFromFile(xmlFilename); } } else { MyLog.log.log(Level.INFO, "No need submit!!!!"); } }