List of usage examples for java.io BufferedWriter newLine
public void newLine() throws IOException
From source file:com.imaginary.home.controller.HomeController.java
private void saveSchedule() throws ControllerException { synchronized (commandQueue) { ArrayList<Map<String, Object>> all = new ArrayList<Map<String, Object>>(); HashMap<String, Object> cfg = new HashMap<String, Object>(); for (ScheduledCommandList sList : scheduler) { ArrayList<Map<String, Object>> commands = new ArrayList<Map<String, Object>>(); HashMap<String, Object> schedule = new HashMap<String, Object>(); for (JSONObject cmd : sList) { try { commands.add(toMap(cmd)); } catch (JSONException e) { throw new ControllerException(e); }//from w ww . j a v a2 s. c o m } schedule.put("commands", commands); schedule.put("executeAfter", sList.getExecuteAfter()); schedule.put("scheduleId", sList.getScheduleId()); schedule.put("serviceId", sList.getServiceId()); all.add(schedule); } cfg.put("schedule", all); try { File f = new File(SCHEDULER_FILE); File backup = null; if (f.exists()) { backup = new File(SCHEDULER_FILE + "." + System.currentTimeMillis()); if (!f.renameTo(backup)) { throw new ControllerException("Unable to make backup of configuration file"); } f = new File(SCHEDULER_FILE); } boolean success = false; try { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f))); writer.write((new JSONObject(cfg)).toString()); writer.newLine(); writer.flush(); writer.close(); success = true; } finally { if (!success && backup != null) { //noinspection ResultOfMethodCallIgnored backup.renameTo(f); } } } catch (IOException e) { throw new ControllerException("Unable to save command file: " + e.getMessage()); } } }
From source file:com.google.code.maven.plugin.http.client.transformer.JiraRssLinkedIssuesEnricher.java
@Override protected Resource doTransform(Resource input) throws Exception { Assert.notNull(input, "source can not be null"); BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(input.getFile()), charset)); if (target.getFile().getParentFile() != null && !target.getFile().getParentFile().exists()) { Assert.isTrue(target.getFile().getParentFile().mkdirs(), "failed to make directory tree for [" + target.getFile().getParentFile() + "]"); }//from w w w . j a v a 2 s. c om String line; StringBuilder item = new StringBuilder(); BufferedWriter writer = new BufferedWriter(new FileWriter(target.getFile())); // read rss and find jira links while ((line = reader.readLine()) != null) { if (line.contains(CHANNEL_END_TAG)) { break; } if (line.contains(ITEM_END_TAG)) { item.append(line.substring(0, line.indexOf(ITEM_END_TAG))); linkedIssues.addAll(inspectItem(item.toString())); } if (line.contains(ITEM_START_TAG)) { item = new StringBuilder(); item.append(line.substring(line.indexOf(ITEM_START_TAG))); } else { item.append(line).append("\n"); } writer.write(line); writer.newLine(); writer.flush(); } enrich(writer, linkedIssues, depth - 1); while (remaining.get() > 0) { Thread.sleep(100); } // write end of rss do { writer.write(line); } while ((line = reader.readLine()) != null); reader.close(); writer.close(); if (deleteSource) { Assert.isTrue(input.getFile().delete(), "failed to delete source"); } return target; }
From source file:com.qspin.qtaste.ui.xmleditor.TestRequirementEditor.java
public void save() { File xmlFile = new File(currentXMLFile); String path = xmlFile.getParent(); BufferedWriter output = null; try {/*from w w w . j av a 2s. c o m*/ String outputFile = path + File.separator + StaticConfiguration.TEST_REQUIREMENTS_FILENAME; output = new BufferedWriter(new FileWriter(new File(outputFile))); output.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"); output.newLine(); output.write("<" + XMLFile.ROOT_ELEMENT + ">"); for (TestRequirement req : m_TestRequirementModel.getRequirements()) { output.newLine(); output.write("\t<" + XMLFile.REQUIREMENT_ELEMENT + " "); output.append(XMLFile.REQUIREMENT_ID + "=\""); output.append(req.getIdEscapeXml()); output.append("\">"); for (String dataId : req.getDataId()) { if (dataId.equals(TestRequirement.ID)) { continue; } output.newLine(); output.append("\t\t<" + dataId.replace(" ", XMLFile.SPACE_REPLACEMENT) + ">"); output.append(req.getDataEscapeXml(dataId)); output.append("</" + dataId.replace(" ", XMLFile.SPACE_REPLACEMENT) + ">"); } output.newLine(); output.append("\t</" + XMLFile.REQUIREMENT_ELEMENT + ">"); } output.newLine(); output.write("</" + XMLFile.ROOT_ELEMENT + ">"); output.close(); } catch (IOException ex) { logger.error(ex.getMessage()); } finally { try { if (output != null) output.close(); } catch (IOException ex) { logger.error(ex.getMessage()); } } // reload loadXMLFile(currentXMLFile); setModified(false); }
From source file:com.baomidou.mybatisplus.generator.AutoGenerator.java
/** * ?/*from w ww . ja v a 2 s . co m*/ * * @param bw * @param idMap * @param columns * @throws IOException */ protected void buildSQL(BufferedWriter bw, Map<String, IdInfo> idMap, List<String> columns) throws IOException { int size = columns.size(); bw.write("\t<!-- -->"); bw.newLine(); bw.write("\t<sql id=\"Base_Column_List\">"); bw.newLine(); bw.write("\t\t"); /* * */ if (null != config.getConfigBaseEntity()) { for (String column : config.getConfigBaseEntity().getColumns()) { bw.write(DBKeywordsProcessor.convert(column)); if (column.contains("_")) { bw.write(" AS " + processField(column)); } bw.write(", "); } } /** * */ for (int i = 0; i < size; i++) { String column = columns.get(i); IdInfo idInfo = idMap.get(column); if (idInfo != null) { bw.write(DBKeywordsProcessor.convert(idInfo.getValue())); if (idInfo.getValue().contains("_")) { bw.write(" AS " + processField(idInfo.getValue())); } } else { if (null == config.getConfigBaseEntity()) { bw.write(" "); } bw.write(DBKeywordsProcessor.convert(column)); if (column.contains("_")) { bw.write(" AS " + processField(column)); } } if (i != size - 1) { bw.write(","); } } bw.newLine(); bw.write("\t</sql>"); bw.newLine(); bw.newLine(); }
From source file:com.holycityaudio.SpinCAD.SpinCADFile.java
public void fileSaveSpj(SpinCADBank bank) { // Create a file chooser String savedPath = prefs.get("MRUSpjFolder", ""); String[] spnFileNames = new String[8]; final JFileChooser fc = new JFileChooser(savedPath); // In response to a button click: FileNameExtensionFilter filter = new FileNameExtensionFilter("Spin Project Files", "spj"); fc.setFileFilter(filter);/* ww w.j a v a 2 s . c om*/ // XXX debug fc.showSaveDialog(new JFrame()); File fileToBeSaved = fc.getSelectedFile(); if (!fc.getSelectedFile().getAbsolutePath().endsWith(".spj")) { fileToBeSaved = new File(fc.getSelectedFile() + ".spj"); } int n = JOptionPane.YES_OPTION; if (fileToBeSaved.exists()) { JFrame frame1 = new JFrame(); n = JOptionPane.showConfirmDialog(frame1, "Would you like to overwrite it?", "File already exists!", JOptionPane.YES_NO_OPTION); } if (n == JOptionPane.YES_OPTION) { // filePath points at the desired Spj file String filePath = fileToBeSaved.getPath(); String folder = fileToBeSaved.getParent().toString(); // export the individual SPN files for (int i = 0; i < 8; i++) { try { String asmFileNameRoot = FilenameUtils.removeExtension(bank.patch[i].patchFileName); String asmFileName = folder + "\\" + asmFileNameRoot + ".spn"; if (bank.patch[i].patchFileName != "Untitled") { fileSaveAsm(bank.patch[i], asmFileName); spnFileNames[i] = asmFileName; } } catch (IOException e) { JOptionPane.showOptionDialog(null, "File save error!", "Error", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); e.printStackTrace(); } finally { } } // now create the Spin Project file fileToBeSaved.delete(); BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(fileToBeSaved, true)); } catch (IOException e1) { e1.printStackTrace(); } try { writer.write("NUMDOCS:8"); writer.newLine(); } catch (IOException e1) { e1.printStackTrace(); } for (int i = 0; i < 8; i++) { try { if (bank.patch[i].patchFileName != "Untitled") { writer.write(spnFileNames[i] + ",1"); } else { writer.write(",0"); } writer.newLine(); } catch (IOException e) { JOptionPane.showOptionDialog(null, "File save error!\n" + filePath, "Error", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); e.printStackTrace(); } } // write the build flags try { writer.write(",1,1,1"); writer.newLine(); } catch (IOException e1) { e1.printStackTrace(); } try { writer.close(); } catch (IOException e) { e.printStackTrace(); } saveMRUSpjFolder(filePath); } }
From source file:de.bfs.radon.omsimulation.gui.OMPanelData.java
/** * Initialises the interface of the data panel. *//* ww w . j a v a 2 s. c om*/ protected void initialize() { setLayout(null); lblExportChartTo = new JLabel("Export chart to ..."); lblExportChartTo.setBounds(436, 479, 144, 14); lblExportChartTo.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); lblExportChartTo.setVisible(false); add(lblExportChartTo); btnCsv = new JButton("CSV"); btnCsv.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser fileDialog = new JFileChooser(); fileDialog.setFileFilter(new FileNameExtensionFilter("*.csv", "csv")); fileDialog.showSaveDialog(getParent()); final File file = fileDialog.getSelectedFile(); if (file != null) { String csv; String[] tmpFileName = file.getAbsolutePath().split("\\."); if (tmpFileName[tmpFileName.length - 1].equals("csv")) { csv = ""; } else { csv = ".csv"; } String csvPath = file.getAbsolutePath() + csv; OMRoom selectedRoom = (OMRoom) comboBoxRooms.getSelectedItem(); double[] selectedValues = selectedRoom.getValues(); File csvFile = new File(csvPath); try { FileWriter logWriter = new FileWriter(csvFile); BufferedWriter csvOutput = new BufferedWriter(logWriter); csvOutput.write("\"ID\";\"" + selectedRoom.getId() + "\""); csvOutput.newLine(); for (int i = 0; i < selectedValues.length; i++) { csvOutput.write("\"" + i + "\";\"" + (int) selectedValues[i] + "\""); csvOutput.newLine(); } JOptionPane.showMessageDialog(null, "CSV saved successfully!\n" + csvPath, "Success", JOptionPane.INFORMATION_MESSAGE); csvOutput.close(); } catch (IOException ioe) { JOptionPane.showMessageDialog(null, "Failed to write CSV. Please check permissions!\n" + ioe.getMessage(), "Failed", JOptionPane.ERROR_MESSAGE); ioe.printStackTrace(); } } else { JOptionPane.showMessageDialog(null, "Failed to write CSV. Please check the file path!", "Failed", JOptionPane.ERROR_MESSAGE); } } }); btnCsv.setBounds(590, 475, 70, 23); btnCsv.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); btnCsv.setVisible(false); add(btnCsv); btnPdf = new JButton("PDF"); btnPdf.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser fileDialog = new JFileChooser(); fileDialog.setFileFilter(new FileNameExtensionFilter("*.pdf", "pdf")); fileDialog.showSaveDialog(getParent()); final File file = fileDialog.getSelectedFile(); if (file != null) { String pdf; String[] tmpFileName = file.getAbsolutePath().split("\\."); if (tmpFileName[tmpFileName.length - 1].equals("pdf")) { pdf = ""; } else { pdf = ".pdf"; } String pdfPath = file.getAbsolutePath() + pdf; OMBuilding building = (OMBuilding) comboBoxProjects.getSelectedItem(); String title = building.getName(); OMRoom selectedRoom = (OMRoom) comboBoxRooms.getSelectedItem(); JFreeChart chart = OMCharts.createRoomChart(title, selectedRoom, false); int height = (int) PageSize.A4.getWidth(); int width = (int) PageSize.A4.getHeight(); try { OMExports.exportPdf(pdfPath, chart, width, height, new DefaultFontMapper(), title); JOptionPane.showMessageDialog(null, "PDF saved successfully!\n" + pdfPath, "Success", JOptionPane.INFORMATION_MESSAGE); } catch (IOException ioe) { JOptionPane.showMessageDialog(null, "Failed to write PDF. Please check permissions!\n" + ioe.getMessage(), "Failed", JOptionPane.ERROR_MESSAGE); ioe.printStackTrace(); } } else { JOptionPane.showMessageDialog(null, "Failed to write PDF. Please check the file path!", "Failed", JOptionPane.ERROR_MESSAGE); } } }); btnPdf.setBounds(670, 475, 70, 23); btnPdf.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); btnPdf.setVisible(false); add(btnPdf); lblSelectProject = new JLabel("Select Project"); lblSelectProject.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); lblSelectProject.setBounds(10, 65, 132, 14); add(lblSelectProject); lblSelectRoom = new JLabel("Select Room"); lblSelectRoom.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); lblSelectRoom.setBounds(10, 94, 132, 14); add(lblSelectRoom); panelData = new JPanel(); panelData.setBounds(10, 118, 730, 347); add(panelData); btnRefresh = new JButton("Load"); btnRefresh.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); btnRefresh.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (txtOmbFile.getText() != null && !txtOmbFile.getText().equals("") && !txtOmbFile.getText().equals(" ")) { txtOmbFile.setBackground(Color.WHITE); String ombPath = txtOmbFile.getText(); String omb; String[] tmpFileName = ombPath.split("\\."); if (tmpFileName[tmpFileName.length - 1].equals("omb")) { omb = ""; } else { omb = ".omb"; } txtOmbFile.setText(ombPath + omb); setOmbFile(ombPath + omb); File ombFile = new File(ombPath + omb); if (ombFile.exists()) { txtOmbFile.setBackground(Color.WHITE); btnRefresh.setEnabled(false); comboBoxProjects.setEnabled(false); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); btnPdf.setVisible(false); btnCsv.setVisible(false); lblExportChartTo.setVisible(false); progressBar.setVisible(true); progressBar.setStringPainted(true); progressBar.setIndeterminate(true); refreshProjectsTask = new RefreshProjects(); refreshProjectsTask.execute(); } else { txtOmbFile.setBackground(new Color(255, 222, 222, 128)); JOptionPane.showMessageDialog(null, "OMB-file not found, please check the file path!", "Error", JOptionPane.ERROR_MESSAGE); } } else { txtOmbFile.setBackground(new Color(255, 222, 222, 128)); JOptionPane.showMessageDialog(null, "Please select an OMB-file!", "Warning", JOptionPane.WARNING_MESSAGE); } } }); btnRefresh.setBounds(616, 61, 124, 23); add(btnRefresh); btnMaximize = new JButton("Fullscreen"); btnMaximize.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); btnMaximize.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (comboBoxRooms.isEnabled()) { if (comboBoxRooms.getSelectedItem() != null) { OMBuilding building = (OMBuilding) comboBoxProjects.getSelectedItem(); String title = building.getName(); OMRoom room = (OMRoom) comboBoxRooms.getSelectedItem(); panelRoom = createRoomPanel(title, room, false, false); JFrame chartFrame = new JFrame(); JPanel chartPanel = createRoomPanel(title, room, false, true); chartFrame.getContentPane().add(chartPanel); chartFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); chartFrame.setBounds(0, 0, (int) dim.getWidth(), (int) dim.getHeight()); chartFrame.setTitle("OM Simulation Tool: " + title + ", Room " + room.getId()); chartFrame.setResizable(true); chartFrame.setExtendedState(JFrame.MAXIMIZED_BOTH); chartFrame.setVisible(true); } } } }); btnMaximize.setBounds(10, 475, 124, 23); btnMaximize.setVisible(false); add(btnMaximize); comboBoxProjects = new JComboBox<OMBuilding>(); comboBoxProjects.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); comboBoxProjects.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { boolean b = false; Color c = null; if (comboBoxProjects.isEnabled()) { if (comboBoxProjects.getSelectedItem() != null) { b = true; c = Color.WHITE; OMBuilding building = (OMBuilding) comboBoxProjects.getSelectedItem(); comboBoxRooms.removeAllItems(); for (int i = 0; i < building.getRooms().length; i++) { comboBoxRooms.addItem(building.getRooms()[i]); } for (int i = 0; i < building.getCellars().length; i++) { comboBoxRooms.addItem(building.getCellars()[i]); } for (int i = 0; i < building.getMiscs().length; i++) { comboBoxRooms.addItem(building.getMiscs()[i]); } } else { b = false; c = null; } } else { b = false; c = null; } lblSelectRoom.setEnabled(b); panelData.setEnabled(b); btnMaximize.setVisible(b); comboBoxRooms.setEnabled(b); panelData.setBackground(c); } }); comboBoxProjects.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { boolean b = false; Color c = null; if (comboBoxProjects.isEnabled()) { if (comboBoxProjects.getSelectedItem() != null) { b = true; c = Color.WHITE; OMBuilding building = (OMBuilding) comboBoxProjects.getSelectedItem(); comboBoxRooms.removeAllItems(); for (int i = 0; i < building.getRooms().length; i++) { comboBoxRooms.addItem(building.getRooms()[i]); } for (int i = 0; i < building.getCellars().length; i++) { comboBoxRooms.addItem(building.getCellars()[i]); } for (int i = 0; i < building.getMiscs().length; i++) { comboBoxRooms.addItem(building.getMiscs()[i]); } } else { b = false; c = null; } } else { b = false; c = null; } lblSelectRoom.setEnabled(b); panelData.setEnabled(b); btnMaximize.setVisible(b); comboBoxRooms.setEnabled(b); panelData.setBackground(c); } }); comboBoxProjects.setBounds(152, 61, 454, 22); add(comboBoxProjects); comboBoxRooms = new JComboBox<OMRoom>(); comboBoxRooms.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); comboBoxRooms.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (comboBoxRooms.isEnabled()) { if (comboBoxRooms.getSelectedItem() != null) { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); remove(panelData); comboBoxRooms.setEnabled(false); refreshChartsTask = new RefreshCharts(); refreshChartsTask.execute(); } } } }); comboBoxRooms.setBounds(152, 90, 454, 22); add(comboBoxRooms); progressBar = new JProgressBar(); progressBar.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); progressBar.setBounds(10, 475, 730, 23); progressBar.setVisible(false); add(progressBar); lblSelectRoom.setEnabled(false); panelData.setEnabled(false); comboBoxRooms.setEnabled(false); lblHelp = new JLabel( "Select an OMB-Object file to analyse its data. You can inspect radon concentration for each room."); lblHelp.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); lblHelp.setForeground(Color.GRAY); lblHelp.setBounds(10, 10, 730, 14); add(lblHelp); txtOmbFile = new JTextField(); txtOmbFile.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); txtOmbFile.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent arg0) { setOmbFile(txtOmbFile.getText()); } }); txtOmbFile.setBounds(152, 33, 454, 20); add(txtOmbFile); txtOmbFile.setColumns(10); btnBrowse = new JButton("Browse"); btnBrowse.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); btnBrowse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JFileChooser fileDialog = new JFileChooser(); fileDialog.setFileFilter(new FileNameExtensionFilter("*.omb", "omb")); fileDialog.showOpenDialog(getParent()); final File file = fileDialog.getSelectedFile(); if (file != null) { String omb; String[] tmpFileName = file.getAbsolutePath().split("\\."); if (tmpFileName[tmpFileName.length - 1].equals("omb")) { omb = ""; } else { omb = ".omb"; } txtOmbFile.setText(file.getAbsolutePath() + omb); setOmbFile(file.getAbsolutePath() + omb); } } }); btnBrowse.setBounds(616, 32, 124, 23); add(btnBrowse); lblSelectOmbfile = new JLabel("Select OMB-File"); lblSelectOmbfile.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); lblSelectOmbfile.setBounds(10, 36, 132, 14); add(lblSelectOmbfile); }
From source file:com.netflix.ice.processor.ReservationCapacityPoller.java
@Override protected void poll() throws Exception { ProcessorConfig config = ProcessorConfig.getInstance(); // read from s3 if not exists File file = new File(config.localDir, "reservation_capacity.txt"); if (!file.exists()) { logger.info("downloading " + file + "..."); AwsUtils.downloadFileIfNotExist(config.workS3BucketName, config.workS3BucketPrefix, file); logger.info("downloaded " + file); }//from www .j ava2s. com // read from file Map<String, ReservedInstances> reservations = Maps.newTreeMap(); if (file.exists()) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String line; while ((line = reader.readLine()) != null) { String[] tokens = line.split(","); String accountId = tokens[0]; String region = tokens[1]; String reservationId = tokens[2]; String zone = tokens[3]; Long start = Long.parseLong(tokens[4]); long duration = Long.parseLong(tokens[5]); String instanceType = tokens[6]; String productDescription = tokens[7]; int instanceCount = Integer.parseInt(tokens[8]); String offeringType = tokens[9]; String state = tokens[10]; Long end = tokens.length > 11 ? Long.parseLong(tokens[11]) : null; float fixedPrice = tokens.length > 12 ? Float.parseFloat(tokens[12]) : 0; float usagePrice = tokens.length > 13 ? Float.parseFloat(tokens[13]) : 0; ReservedInstances reservation = new ReservedInstances().withAvailabilityZone(zone) .withStart(new Date(start)).withDuration(duration).withInstanceType(instanceType) .withProductDescription(productDescription).withInstanceCount(instanceCount) .withOfferingType(offeringType).withState(state).withFixedPrice(fixedPrice) .withUsagePrice(usagePrice); if (end != null) reservation.setEnd(new Date(end)); else reservation.setEnd(new Date(start + duration * 1000)); reservations.put(accountId + "," + region + "," + reservationId, reservation); } } catch (Exception e) { logger.error("error in reading " + file, e); } finally { if (reader != null) try { reader.close(); } catch (Exception e) { } } } logger.info("read " + reservations.size() + " reservations."); for (Account account : config.accountService.getReservationAccounts().keySet()) { try { AmazonEC2Client ec2Client; String assumeRole = config.accountService.getReservationAccessRoles().get(account); if (assumeRole != null) { String externalId = config.accountService.getReservationAccessExternalIds().get(account); final Credentials credentials = AwsUtils.getAssumedCredentials(account.id, assumeRole, externalId); ec2Client = new AmazonEC2Client(new AWSSessionCredentials() { public String getAWSAccessKeyId() { return credentials.getAccessKeyId(); } public String getAWSSecretKey() { return credentials.getSecretAccessKey(); } public String getSessionToken() { return credentials.getSessionToken(); } }); } else ec2Client = new AmazonEC2Client(AwsUtils.awsCredentialsProvider.getCredentials(), AwsUtils.clientConfig); for (Region region : Region.getAllRegions()) { ec2Client.setEndpoint("ec2." + region.name + ".amazonaws.com"); try { DescribeReservedInstancesResult result = ec2Client.describeReservedInstances(); for (ReservedInstances reservation : result.getReservedInstances()) { String key = account.id + "," + region.name + "," + reservation.getReservedInstancesId(); reservations.put(key, reservation); if (reservation.getEnd() == null) reservation.setEnd(new Date( reservation.getStart().getTime() + reservation.getDuration() * 1000L)); if (reservation.getFixedPrice() == null) reservation.setFixedPrice(0f); if (reservation.getUsagePrice() == null) reservation.setUsagePrice(0f); } } catch (Exception e) { logger.error("error in describeReservedInstances for " + region.name + " " + account.name, e); } } ec2Client.shutdown(); } catch (Exception e) { logger.error("Error in describeReservedInstances for " + account.name, e); } } config.reservationService.updateEc2Reservations(reservations); updatedConfig = true; // archive to disk BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(file)); for (String key : reservations.keySet()) { ReservedInstances reservation = reservations.get(key); String[] line = new String[] { key, reservation.getAvailabilityZone(), reservation.getStart().getTime() + "", reservation.getDuration().toString(), reservation.getInstanceType(), reservation.getProductDescription(), reservation.getInstanceCount().toString(), reservation.getOfferingType(), reservation.getState(), reservation.getEnd().getTime() + "", reservation.getFixedPrice() + "", reservation.getUsagePrice() + "", }; writer.write(StringUtils.join(line, ",")); writer.newLine(); } } catch (Exception e) { logger.error("", e); } finally { if (writer != null) try { writer.close(); } catch (Exception e) { } } logger.info("archived " + reservations.size() + " reservations."); // archive to s3 logger.info("uploading " + file + "..."); AwsUtils.upload(config.workS3BucketName, config.workS3BucketPrefix, config.localDir, file.getName()); logger.info("uploaded " + file); }
From source file:de.tudarmstadt.ukp.dkpro.core.mallet.lda.util.PrintTopicWordWeights.java
/** * Write the output for single file.//from w ww.j a va 2 s .c o m * * @param targetFile * the file into which the output is written * * @throws IOException * if an I/O error occurs while writing to the output file */ public void writeWords(File targetFile) throws IOException { targetFile.getParentFile().mkdirs(); LOGGER.info("Writing output to " + targetFile); BufferedWriter outputStream = new BufferedWriter(new FileWriter(targetFile)); /* iterate over topics */ for (TreeSet<IDSorter> topic : model.getSortedWords()) { int wordCount = 0; /* iterate over word IDs in topic (sorted by weight) */ for (IDSorter id : topic) { double weight = id.getWeight() / alphabet.size(); // normalize String word = ((String) alphabet.lookupObject(id.getID())).replaceAll("\r\n", " "); if (word.contains(FIELD_SEPARATOR)) { LOGGER.debug("Ignoring '" + word + "'."); } else { outputStream.write(String.format(LOCALE, "%s%s%f", word, FIELD_SEPARATOR, weight)); wordCount++; if (wordCount >= nWords) { break; // go to next topic } outputStream.write(FIELD_SEPARATOR); // FIXME: why is there a ',' at the end of // each line? } } outputStream.newLine(); } outputStream.close(); }
From source file:org.apache.ctakes.ytex.kernel.IntrinsicInfoContentEvaluatorImpl.java
/** * add/update icInfoMap entry for concept with the concept's subsumer count * // w w w .ja va2 s. c o m * @param concept * @param icInfoMap * @param subsumerMap * @param w * @throws IOException */ private void computeSubsumerCount(ConcRel concept, Map<String, IntrinsicICInfo> icInfoMap, Map<String, Set<String>> subsumerMap, short[] depthArray, BufferedWriter w) throws IOException { // see if we already computed this IntrinsicICInfo icInfo = icInfoMap.get(concept.getConceptID()); if (icInfo != null && icInfo.getSubsumerCount() > 0) { return; } // if not, figure it out if (icInfo == null) { icInfo = new IntrinsicICInfo(concept); icInfoMap.put(concept.getConceptID(), icInfo); } Set<String> subsumers = this.getSubsumers(concept, subsumerMap, depthArray); if (w != null) { w.write(concept.getConceptID()); w.write("\t"); w.write(Integer.toString(subsumers.size())); w.write("\t"); w.write(subsumers.toString()); w.newLine(); } icInfo.setSubsumerCount(subsumers.size()); // recursively compute the children's subsumer counts for (ConcRel child : concept.getChildren()) { computeSubsumerCount(child, icInfoMap, subsumerMap, depthArray, w); } }