List of usage examples for java.util Properties store
public void store(OutputStream out, String comments) throws IOException
From source file:de.tudarmstadt.ukp.clarin.webanno.api.dao.RepositoryServiceDbData.java
@Override public <T> void saveHelpContents(T aConfigurationObject) throws IOException { BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(aConfigurationObject); Properties property = new Properties(); for (PropertyDescriptor value : wrapper.getPropertyDescriptors()) { if (wrapper.getPropertyValue(value.getName()) == null) { continue; }// w ww . ja va2s. co m property.setProperty(value.getName(), wrapper.getPropertyValue(value.getName()).toString()); } File helpFile = new File(dir.getAbsolutePath() + HELP_FILE); if (helpFile.exists()) { FileUtils.forceDeleteOnExit(helpFile); } else { helpFile.createNewFile(); } property.store(new FileOutputStream(helpFile), null); }
From source file:gtu._work.etc.EnglishTester.java
private void initGUI() { try {//from w ww .j a v a 2 s. c o m JCommonUtil.defaultToolTipDelay(); BorderLayout thisLayout = new BorderLayout(); getContentPane().setLayout(thisLayout); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); { jTabbedPane1 = new JTabbedPane(); getContentPane().add(jTabbedPane1, BorderLayout.CENTER); jTabbedPane1.setPreferredSize(new java.awt.Dimension(462, 259)); jTabbedPane1.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { // XXX // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx jTabbedPane1.requestFocus();// FOCUS TODO // XXX // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx } }); jTabbedPane1.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { System.out.println("2===" + evt.getKeyCode()); if (evt.getKeyCode() == 49) {// 0 jTabbedPane1.setSelectedIndex(0); } if (evt.getKeyCode() == 50) {// 1 jTabbedPane1.setSelectedIndex(1); } if (evt.getKeyCode() == 10) {// enter skipBtnAction(); } if (evt.getKeyCode() == 32) {// removeBtnAction(); } } }); { jPanel1 = new JPanel(); BorderLayout jPanel1Layout = new BorderLayout(); jPanel1.setLayout(jPanel1Layout); jTabbedPane1.addTab("english", null, jPanel1, null); { jScrollPane1 = new JScrollPane(); jPanel1.add(jScrollPane1, BorderLayout.CENTER); jScrollPane1.setPreferredSize(new java.awt.Dimension(420, 141)); { englishArea = new JTextArea(); jScrollPane1.setViewportView(englishArea); englishArea.setFont(new java.awt.Font("Microsoft JhengHei", 0, 22)); } } { jPanel5 = new JPanel(); jPanel1.add(jPanel5, BorderLayout.SOUTH); jPanel5.setPreferredSize(new java.awt.Dimension(402, 65)); { skipBtn = new JButton(); jPanel5.add(skipBtn); skipBtn.setText("skip"); skipBtn.setPreferredSize(new java.awt.Dimension(187, 24)); skipBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { skipBtnAction(); } }); } { removeBtn = new JButton(); jPanel5.add(removeBtn); removeBtn.setText("remove"); removeBtn.setPreferredSize(new java.awt.Dimension(180, 24)); removeBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { removeBtnAction(); } }); } { questionCountLabel = new JLabel(); jPanel5.add(questionCountLabel); questionCountLabel.setPreferredSize(new java.awt.Dimension(47, 21)); questionCountLabel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); questionCountLabel.setToolTipText(""); } { propCountLabel = new JLabel(); jPanel5.add(propCountLabel); propCountLabel.setPreferredSize(new java.awt.Dimension(45, 21)); propCountLabel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); propCountLabel.setToolTipText(""); } { googleSearchBtn = new JButton(); jPanel5.add(googleSearchBtn); googleSearchBtn.setText("<html>GPic</html>"); googleSearchBtn.setPreferredSize(new java.awt.Dimension(58, 24)); googleSearchBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { try { String word = currentWordIndex.trim(); ClipboardUtil.getInstance().setContents(word); word = word.replace(" ", "%20"); URI uri = new URI( "https://www.google.com.tw/search?num=10&hl=zh-TW&site=imghp&tbm=isch&source=hp&biw=1280&bih=696&q=" + word); //URI uri = new URI("http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=" + word); Desktop.getDesktop().browse(uri); } catch (Exception ex) { JCommonUtil.handleException(ex); } } }); } { yahooDicBtn = new JButton(); jPanel5.add(yahooDicBtn); yahooDicBtn.setText("<html>Dict</html>"); yahooDicBtn.setPreferredSize(new java.awt.Dimension(57, 24)); yahooDicBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { try { // URI uri = new // URI("http://tw.dictionary.yahoo.com/dictionary?p=" // + currentWord.trim()); URI uri = new URI("http://www.dreye.com/axis/ddict.jsp?ver=big5&dod=0102&w=" + currentWordIndex.trim() + "&x=0&y=0"); Desktop.getDesktop().browse(uri); } catch (Exception ex) { JCommonUtil.handleException(ex); } } }); } { pickBtn = new JButton(); jPanel5.add(pickBtn); pickBtn.setText("<html>+Pick</html>"); pickBtn.setPreferredSize(new java.awt.Dimension(60, 24)); pickBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { try { String key = currentWordIndex; String value = englishProp.getProperty(currentWordIndex); if (StringUtils.isEmpty(value)) { JCommonUtil._jOptionPane_showMessageDialog_error( "add pick failed : no such word => " + key); } else { pickProp.setProperty(key, value); JCommonUtil._jOptionPane_showMessageDialog_info( "key=" + key + "\nvalue=" + value + "\nsize=" + pickProp.size(), "??"); } } catch (Exception ex) { JCommonUtil.handleException(ex); } } }); } { scanPicBtn = new JButton(); scanPicBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); jPanel5.add(scanPicBtn); scanPicBtn.setPreferredSize(new java.awt.Dimension(46, 24)); scanPicBtn.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (picDir == null) { JCommonUtil._jOptionPane_showMessageDialog_error("picDir is null"); return; } if (picSet != null && picSet.size() > 0) { try { Desktop.getDesktop().open(picSet.iterator().next()); } catch (IOException e) { JCommonUtil.handleException(e); } return; } try { String text = currentWordIndex.trim().toLowerCase(); ClipboardUtil.getInstance().setContents(text); text = text.replace(" ", "%20"); URI uri = new URI( "https://www.google.com.tw/search?num=10&hl=zh-TW&site=imghp&tbm=isch&source=hp&biw=1280&bih=696&q=" + text); //URI uri = new URI("http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=" + text); Desktop.getDesktop().browse(uri); } catch (Exception ex) { JCommonUtil.handleException(ex); } } }); } { showChineseOption = new JCheckBox(); showChineseOption.setSelected(true); jPanel5.add(showChineseOption); } } } { jPanel2 = new JPanel(); BorderLayout jPanel2Layout = new BorderLayout(); jPanel2.setLayout(jPanel2Layout); jTabbedPane1.addTab("chinese", null, jPanel2, null); jPanel2.setPreferredSize(new java.awt.Dimension(420, 211)); { showEnglishText = new JTextField(); jPanel2.add(showEnglishText, BorderLayout.NORTH); showEnglishText.setEditable(false); } { jPanel10 = new JPanel(); jPanel2.add(jPanel10, BorderLayout.CENTER); } { answerBtn[0] = new JButton(); jPanel10.add(answerBtn[0]); answerBtn[0].setPreferredSize(new java.awt.Dimension(190, 110)); answerBtn[0].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { answerBtnClick(answerBtn[0]); } }); } { answerBtn[1] = new JButton(); jPanel10.add(answerBtn[1]); answerBtn[1].setPreferredSize(new java.awt.Dimension(190, 110)); answerBtn[1].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { answerBtnClick(answerBtn[1]); } }); } { answerBtn[2] = new JButton(); jPanel10.add(answerBtn[2]); answerBtn[2].setPreferredSize(new java.awt.Dimension(190, 110)); answerBtn[2].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { answerBtnClick(answerBtn[2]); } }); } { answerBtn[3] = new JButton(); jPanel10.add(answerBtn[3]); answerBtn[3].setPreferredSize(new java.awt.Dimension(190, 110)); answerBtn[3].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { answerBtnClick(answerBtn[3]); } }); } { for (int ii = 0; ii < 4; ii++) { answerBtn[ii].setFont(new java.awt.Font("", 0, 14)); } } } { jPanel3 = new JPanel(); BorderLayout jPanel3Layout = new BorderLayout(); jPanel3.setLayout(jPanel3Layout); jTabbedPane1.addTab("word", null, jPanel3, null); { jScrollPane3 = new JScrollPane(); jPanel3.add(jScrollPane3, BorderLayout.CENTER); jScrollPane3.setPreferredSize(new java.awt.Dimension(420, 187)); { propTable = new JTable(); jScrollPane3.setViewportView(propTable); JTableUtil.defaultSetting(propTable); propTable.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { JPopupMenuUtil.newInstance(propTable) .addJMenuItem(JTableUtil.newInstance(propTable).getDefaultJMenuItems()) .applyEvent(evt).show(); } }); } } { saveBtn = new JButton(); jPanel3.add(saveBtn, BorderLayout.SOUTH); saveBtn.setText("save table"); saveBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { DefaultTableModel model = JTableUtil.newInstance(propTable).getModel(); for (int ii = 0; ii < model.getRowCount(); ii++) { String key = (String) model.getValueAt(ii, 0); String value = (String) model.getValueAt(ii, 1); if (!englishProp.containsKey(key)) { englishProp.setProperty(key, value); } } try { englishProp.store(new FileOutputStream(englishFile), "comment"); } catch (Exception e) { e.printStackTrace(); } JCommonUtil._jOptionPane_showMessageDialog_info("save file ok! \n" + englishFile); } }); } { queryText = new JTextField(); jPanel3.add(queryText, BorderLayout.NORTH); queryText.getDocument() .addDocumentListener(JCommonUtil.getDocumentListener(new HandleDocumentEvent() { @Override public void process(DocumentEvent event) { String text = JCommonUtil.getDocumentText(event); Pattern pattern = Pattern.compile(text); Matcher matcher = null; DefaultTableModel propTableModel = JTableUtil.createModel(false, "english", "chinese"); for (Enumeration<?> enu = englishProp.propertyNames(); enu .hasMoreElements();) { String key = (String) enu.nextElement(); String value = englishProp.getProperty(key); if (key.contains(text)) { propTableModel.addRow(new Object[] { key, value }); continue; } matcher = pattern.matcher(key); if (matcher.find()) { propTableModel.addRow(new Object[] { key, value }); continue; } } propTable.setModel(propTableModel); } })); } } { jPanel4 = new JPanel(); jTabbedPane1.addTab("config", null, jPanel4, null); { savePickBtn = new JButton(); jPanel4.add(savePickBtn); savePickBtn.setText("save pick"); savePickBtn.setPreferredSize(new java.awt.Dimension(116, 40)); savePickBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if (englishFile == null) { File file = new File(// PropertiesUtil.getJarCurrentPath(EnglishTester.class), "temp.properties"); englishFile = file; } if (pickProp.isEmpty()) { JCommonUtil._jOptionPane_showMessageDialog_error("?!"); return; } String fileName = englishFile.getName().replaceAll("\\.properties", "_bak.properties"); File jarWhereFile = PropertiesUtil.getJarCurrentPath(EnglishTester.class); fileName = JCommonUtil._jOptionPane_showInputDialog("save target properties", fileName); if (StringUtils.isEmpty(fileName)) { JCommonUtil._jOptionPane_showMessageDialog_error("can't save!"); return; } if (fileName.equalsIgnoreCase(englishFile.getName())) { JCommonUtil._jOptionPane_showMessageDialog_error( "??englishFile???"); return; } if (!fileName.endsWith(".properties")) { fileName += ".properties"; } File newFile = new File(jarWhereFile, fileName); Properties oldProp = new Properties(); if (newFile.exists()) { try { oldProp.load(new FileInputStream(newFile)); } catch (Exception e) { e.printStackTrace(); } } oldProp.putAll(pickProp); try { oldProp.store(new FileOutputStream(newFile), "comment"); } catch (Exception e) { e.printStackTrace(); } JCommonUtil._jOptionPane_showMessageDialog_info("save file ok! \n" + newFile); } }); } { saveConfigBtn2 = new JButton(); jPanel4.add(saveConfigBtn2); saveConfigBtn2.setText("save config"); saveConfigBtn2.setPreferredSize(new java.awt.Dimension(108, 40)); saveConfigBtn2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { saveConfigBtnAction(); } }); } { startAllBtn = new JButton(); jPanel4.add(startAllBtn); startAllBtn.setText("start all"); startAllBtn.setPreferredSize(new java.awt.Dimension(101, 40)); startAllBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { Object[] files = fileList.getSelectedValues(); if (files == null || files.length == 0) { JCommonUtil ._jOptionPane_showMessageDialog_error("?properties"); return; } Properties allProp = new Properties(); Properties prop = new Properties(); for (Object ff : files) { try { prop.load(new FileInputStream((File) ff)); } catch (Exception e) { JCommonUtil.handleException(e); } allProp.putAll(prop); } englishProp = allProp; System.out.println("englishProp = " + englishProp.size()); startNow(); } }); } { startNow = new JButton(); jPanel4.add(startNow); startNow.setText("start now"); startNow.setPreferredSize(new java.awt.Dimension(101, 40)); startNow.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { startNow(); } }); } { picOnly = new JCheckBox(); jPanel4.add(picOnly); picOnly.setText("picOnly"); } { sortChkBox = new JCheckBox(); jPanel4.add(sortChkBox); sortChkBox.setText("sort"); } { showPicChkBox = new JCheckBox(); showPicChkBox.setSelected(true); jPanel4.add(showPicChkBox); showPicChkBox.setText("showPic"); } { JCommonUtil.defaultToolTipDelay(); fontSizeSliber = new JSlider(JSlider.HORIZONTAL); jPanel4.add(fontSizeSliber); fontSizeSliber.setPreferredSize(new java.awt.Dimension(419, 35)); fontSizeSliber.setValue(22); fontSizeSliber.setMinimum(22); fontSizeSliber.setMaximum(300); fontSizeSliber.setMajorTickSpacing(30); fontSizeSliber.setMinorTickSpacing(5); fontSizeSliber.setCursor(new Cursor(Cursor.HAND_CURSOR)); fontSizeSliber.setPaintTicks(false); fontSizeSliber.setPaintLabels(true); { picFolderDirText = new JTextField(); JCommonUtil.jTextFieldSetFilePathMouseEvent(picFolderDirText, true); jPanel4.add(picFolderDirText); picFolderDirText.setColumns(20); } fontSizeSliber.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { int size = fontSizeSliber.getValue(); fontSizeSliber.setToolTipText("" + size); englishArea.setFont(new java.awt.Font("Microsoft JhengHei", 0, size)); } }); } } { jPanel6 = new JPanel(); jTabbedPane1.addTab("files", null, jPanel6, null); BorderLayout jPanel6Layout = new BorderLayout(); jPanel6.setLayout(jPanel6Layout); { jScrollPane4 = new JScrollPane(); jPanel6.add(jScrollPane4, BorderLayout.CENTER); jScrollPane4.setPreferredSize(new java.awt.Dimension(420, 211)); { fileList = new JList(); reloadFileList(); jScrollPane4.setViewportView(fileList); fileList.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { final File file = JListUtil.getLeadSelectionObject(fileList); if (JMouseEventUtil.buttonRightClick(1, evt)) { JPopupMenuUtil.newInstance(EnglishTester.this.fileList).applyEvent(evt)// .addJMenuItem("reload", new ActionListener() { @Override public void actionPerformed(ActionEvent e) { reloadFileList(); } })// .addJMenuItem("delete : " + file.getName(), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean result = JCommonUtil ._JOptionPane_showConfirmDialog_yesNoOption( "delete : " + file.getName() + " ?", "confirm"); if (result) { file.delete(); reloadFileList(); } }// }).show(); return; } if (evt.getClickCount() == 1) { return; } if (JCommonUtil._JOptionPane_showConfirmDialog_yesNoOption( "?,?\n" + file.getName(), "")) { loadEnglishFile(file); } } }); fileList.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { JListUtil.newInstance(fileList).defaultJListKeyPressed(evt); } }); } } } { jPanel9 = new JPanel(); jTabbedPane1.addTab("pic", null, jPanel9, null); { picCheckText = new JTextField(); jPanel9.add(picCheckText); picCheckText.setPreferredSize(new java.awt.Dimension(177, 39)); } { picCheckBtn = new JButton(); jPanel9.add(picCheckBtn); picCheckBtn.setText("check"); picCheckBtn.setPreferredSize(new java.awt.Dimension(98, 43)); { jPanel11 = new JPanel(); jTabbedPane1.addTab("", null, jPanel11, null); jPanel11.setLayout(new BorderLayout(0, 0)); { inputTestArea2 = new JTextArea(); inputTestArea2.setFont(new Font("", Font.PLAIN, 12)); inputTestArea2.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { inputTestTrainer.keyin(e); } }); jPanel11.add(inputTestArea2, BorderLayout.SOUTH); } { inputTestArea1 = new JTextArea(); JTextAreaUtil.setWrapTextArea(inputTestArea1); inputTestArea1.setFont(new Font("", Font.PLAIN, 22)); jPanel11.add(inputTestArea1, BorderLayout.CENTER); } { panel = new JPanel(); jPanel11.add(panel, BorderLayout.NORTH); { inputTestLabel = new JLabel(""); panel.add(inputTestLabel); } { inputTestChk = new JCheckBox(""); inputTestChk.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { inputTestTrainer.initQuestion(); } }); panel.add(inputTestChk); } } } picCheckBtn.addActionListener(new ActionListener() { void scanPic(String searchWord, File file, Set<File> findFile) { if (file.isDirectory()) { File[] list = null; if ((list = file.listFiles()) != null) { for (File f : list) { scanPic(searchWord, f, findFile); } } } else { String text = searchWord; String name = file.getName().toLowerCase(); if (isMatch(name, text)) { findFile.add(file); } } } public void actionPerformed(ActionEvent evt) { picDir = new File(picFolderDirText.getText()); if (picDir == null) { JCommonUtil._jOptionPane_showMessageDialog_error("picDir is null"); return; } if (!picDir.exists() || !picDir.isDirectory()) { JCommonUtil._jOptionPane_showMessageDialog_error("picDir "); return; } picCheckBtn.setText("search.."); String searchWord = picCheckText.getText().toLowerCase().trim(); Set<File> picSet2 = new HashSet<File>(); scanPic(searchWord, picDir, picSet2); if (picSet2 != null && picSet2.size() > 0) { picCheckBtn.setText("" + picSet2.size()); try { Desktop.getDesktop().open(picSet2.iterator().next()); } catch (IOException e) { JCommonUtil.handleException(e); } } else { picCheckBtn.setText("0"); } } }); } } } JCommonUtil.setJFrameIcon(this, "resource/images/ico/english_tester.ico"); pack(); this.setSize(423, 314); configHelper.init(); } catch (Exception e) { // add your error handling code here e.printStackTrace(); } }
From source file:Manifest.java
/** * This method creates a manifest file with the specified name, for the * specified vector of files, using the named message digest algorithm. If * signername is non-null, it adds a digital signature to the manifest, * using the named signature algorithm. This method can throw a bunch of * exceptions./*w w w . j av a 2 s . c o m*/ */ public static void create(String manifestfile, String digestAlgorithm, String signername, String signatureAlgorithm, KeyStore keystore, String password, List filelist) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, KeyStoreException, UnrecoverableKeyException, IOException { // For computing a signature, we have to process the files in a fixed, // repeatable order, so sort them alphabetically. Collections.sort(filelist); int numfiles = filelist.size(); Properties manifest = new Properties(), metadata = new Properties(); MessageDigest md = MessageDigest.getInstance(digestAlgorithm); Signature signature = null; byte[] digest; // If a signer name was specified, then prepare to sign the manifest if (signername != null) { // Get a Signature object signature = Signature.getInstance(signatureAlgorithm); // Look up the private key of the signer from the keystore PrivateKey key = (PrivateKey) keystore.getKey(signername, password.toCharArray()); // No prepare to create a signature for the specified signer signature.initSign(key); } // Now, loop through the files, in a well-known alphabetical order System.out.print("Computing message digests"); for (int i = 0; i < numfiles; i++) { String filename = (String) filelist.get(i); // Compute the digest for each, and skip files that don't exist. try { digest = getFileDigest(filename, md); } catch (IOException e) { System.err.println("\nSkipping " + filename + ": " + e); continue; } // If we're computing a signature, use the bytes of the filename // and of the digest as part of the data to sign. if (signature != null) { signature.update(filename.getBytes()); signature.update(digest); } // Store the filename and the encoded digest bytes in the manifest manifest.put(filename, hexEncode(digest)); System.out.print('.'); System.out.flush(); } // If a signer was specified, compute signature for the manifest byte[] signaturebytes = null; if (signature != null) { System.out.print("done\nComputing digital signature..."); System.out.flush(); // Compute the digital signature by encrypting a message digest of // all the bytes passed to the update() method using the private // key of the signer. This is a time consuming operation. signaturebytes = signature.sign(); } // Tell the user what comes next System.out.print("done\nWriting manifest..."); System.out.flush(); // Store some metadata about this manifest, including the name of the // message digest algorithm it uses metadata.put("__META.DIGESTALGORITHM", digestAlgorithm); // If we're signing the manifest, store some more metadata if (signername != null) { // Store the name of the signer metadata.put("__META.SIGNER", signername); // Store the name of the algorithm metadata.put("__META.SIGNATUREALGORITHM", signatureAlgorithm); // And generate the signature, encode it, and store it metadata.put("__META.SIGNATURE", hexEncode(signaturebytes)); } // Now, save the manifest data and the metadata to the manifest file FileOutputStream f = new FileOutputStream(manifestfile); manifest.store(f, "Manifest message digests"); metadata.store(f, "Manifest metadata"); System.out.println("done"); }
From source file:jeplus.JEPlusConfig.java
/** * Save configuration to file in java property format * @param comment Comment line to be added to the file * @return Save successful or not/* w w w. ja v a 2 s .c om*/ */ public boolean saveToFile(String comment) { Properties prop = new Properties(); try { prop.setProperty("EPlusBinDir", EPlusBinDir); prop.setProperty("EPlusEPMacroEXE", EPlusEPMacroEXE); prop.setProperty("EPlusExpandObjectsEXE", EPlusExpandObjectsEXE); prop.setProperty("EPlusEXE", EPlusEXE); prop.setProperty("EPlusReadVarsEXE", EPlusReadVarsEXE); prop.setProperty("TRNSYSBinDir", TRNSYSBinDir); prop.setProperty("TRNSYSEXE", TRNSYSEXE); prop.setProperty("InselBinDir", InselBinDir); prop.setProperty("InselEXE", InselEXEC); if (ScreenFile != null) { prop.setProperty("ScreenFile", ScreenFile); } if (EPlusVerConvDir != null) { prop.setProperty("EPlusVerConvDir", EPlusVerConvDir); } if (Python2EXE != null) { prop.setProperty("Python2EXE", Python2EXE); } if (Python3EXE != null) { prop.setProperty("Python3EXE", Python3EXE); } if (PythonArgv != null) { prop.setProperty("PythonArgv", PythonArgv); } if (PythonScript != null) { prop.setProperty("PythonScript", PythonScript); } if (JESSClientDir != null) { prop.setProperty("JESSClientDir", JESSClientDir); } if (JEPlusEADir != null) { prop.setProperty("JEPlusEADir", JEPlusEADir); } if (RadianceBinDir != null) { prop.setProperty("RadianceBinDir", RadianceBinDir); } if (RadianceLibDir != null) { prop.setProperty("RadianceLibDir", RadianceLibDir); } if (DaySimBinDir != null) { prop.setProperty("DaySimBinDir", DaySimBinDir); } if (DaySimLibDir != null) { prop.setProperty("DaySimLibDir", DaySimLibDir); } for (int i = 0; i < Math.min(NRecentProjs, RecentProjects.size()); i++) { if (RecentProjects.get(i) != null) prop.setProperty("RecentProject" + i, RecentProjects.get(i)); } prop.store(new FileWriter(this.CurrentConfigFile), comment); } catch (Exception ex) { logger.error("Error saving configuration to " + CurrentConfigFile, ex); return false; } return true; }
From source file:annis.dao.SpringAnnisDao.java
@Override public void setCorpusConfiguration(String toplevelCorpusName, Properties props) { long corpusID = mapCorpusNameToId(toplevelCorpusName); String sql = "SELECT filename FROM media_files " + "WHERE corpus_ref=" + corpusID + " AND title = " + "'corpus.properties'"; String fileName = getJdbcTemplate().query(sql, new ResultSetExtractor<String>() { @Override/* ww w .j a v a 2s . c o m*/ public String extractData(ResultSet rs) throws SQLException, DataAccessException { while (rs.next()) { return rs.getString("filename"); } return null; } }); File dir = getRealDataDir(); if (!dir.exists()) { if (dir.mkdirs()) { log.info("Created directory " + dir); } else { log.error("Directory " + dir + " doesn't exist and cannot be created"); } } if (fileName == null) { fileName = "corpus_" + CommonHelper.getSafeFileName(toplevelCorpusName) + "_" + UUID.randomUUID() + ".properties"; getJdbcTemplate().update("INSERT INTO media_files VALUES ('" + fileName + "','" + corpusID + "', 'application/text+plain', 'corpus.properties')"); } log.info("write config file: " + dir + "/" + fileName); try (FileOutputStream fStream = new FileOutputStream(new File(dir.getCanonicalPath() + "/" + fileName)); OutputStreamWriter writer = new OutputStreamWriter(fStream, Charsets.UTF_8)) { props.store(writer, ""); } catch (IOException ex) { log.error("error: write back the corpus.properties configuration", ex); } }
From source file:org.bibalex.wamcp.storage.WAMCPIndexedStorage.java
public void writeIndexFieldsToFile(ActionEvent ev) throws WAMCPException, WFSVNException, SVNException, XSAException {//from w w w. j a va2s .co m Properties ixedFieldsNameType = new Properties(); for (String key : this.getAllFieldNames()) { String value = this.getSolrTypeForField(key); if (!key.startsWith("All")) { // catch all fields don't have an XPath Set<Entry<XSAInstance, String>> entriesToSearch; if (key.indexOf('_') == -1) { entriesToSearch = this.advSearchFieldsNames.entrySet(); } else { entriesToSearch = this.ixedFieldsNames.entrySet(); } for (Entry<XSAInstance, String> mapping : entriesToSearch) { if (key.equals(mapping.getValue())) { String fieldXPathStr = mapping.getKey().getXPathToAllOccsInAllBaseShifts(); value += "," + fieldXPathStr; // A field can take values from more than one XPath break; } } } ixedFieldsNameType.setProperty(key, value); } try { File ixedFieldesNameTypeTempFile = new File(this.getUserDir().getCanonicalPath() + File.separator + "ixedFieldesNameType.properties"); FileOutputStream ixedFieldesNameTypeTempStream = new FileOutputStream( ixedFieldesNameTypeTempFile); ixedFieldsNameType.store(ixedFieldesNameTypeTempStream, ""); ixedFieldesNameTypeTempStream.flush(); ixedFieldesNameTypeTempStream.close(); String targetPathAbs = ixedFieldesNameTypeTempFile.getCanonicalPath(); ServletContext sltCtx = (ServletContext) FacesContext.getCurrentInstance() .getExternalContext().getContext(); String filePathAbs = sltCtx.getRealPath(""); String filePathRel = targetPathAbs.substring(filePathAbs.length()); filePathRel = filePathRel.replace('\\', '/'); String fileURL = sltCtx.getContextPath() + filePathRel; this.setQuickMessage("Index fields file created: <a href='" + fileURL + "'>" + " Click to download! </a>"); } catch (IOException e) { throw new WAMCPException(e); } }
From source file:com.powers.wsexplorer.gui.WSExplorer.java
private void saveStateToFile(Map<String, Scrollable> itemsToSave, String filename) { if (itemsToSave == null || StringUtils.isBlank(filename)) { return;/*from w ww. j ava 2s.c o m*/ } Properties props = new Properties(); Scrollable s = null; Text text = null; StyledText styledText = null; Combo combo = null; String value = null; Set<String> keys = itemsToSave.keySet(); for (String str : keys) { if (StringUtils.isBlank(str)) { continue; } s = itemsToSave.get(str); if (s instanceof Text) { text = (Text) s; } else if (s instanceof StyledText) { styledText = (StyledText) s; } else if (s instanceof Combo) { combo = (Combo) s; } // get the text out of the widget if (text != null) { value = text.getText(); } else if (styledText != null) { value = styledText.getText(); } else if (combo != null) { value = combo.getText(); } if (StringUtils.isNotBlank(value)) { props.put(str, value); } text = null; combo = null; styledText = null; } FileOutputStream fos = null; try { fos = new FileOutputStream(new File(filename)); props.store(fos, "State Saved"); } catch (Exception e) { log("Unable to save state", e); } }
From source file:br.com.ingenieux.mojo.beanstalk.env.DumpEnvironmentSettings.java
protected Object executeInternal() throws Exception { DescribeConfigurationOptionsResult configOptions = getService() .describeConfigurationOptions(new DescribeConfigurationOptionsRequest() .withApplicationName(applicationName).withEnvironmentName(curEnv.getEnvironmentName())); for (ConfigurationOptionDescription o : configOptions.getOptions()) { String key = String.format("beanstalk.env.%s.%s", o.getNamespace().replace(":", "."), o.getName()); for (Map.Entry<String, ConfigurationOptionSetting> entry : COMMON_PARAMETERS.entrySet()) { ConfigurationOptionSetting cos = entry.getValue(); if (cos.getNamespace().equals(o.getNamespace()) && cos.getOptionName().equals(o.getName())) { key = entry.getKey();// w w w . j a v a 2 s . c o m break; } } defaultSettings.put(key, o); } DescribeConfigurationSettingsResult configurationSettings = getService() .describeConfigurationSettings(new DescribeConfigurationSettingsRequest() .withApplicationName(applicationName).withEnvironmentName(curEnv.getEnvironmentName())); Properties newProperties = new Properties(); if (configurationSettings.getConfigurationSettings().isEmpty()) { throw new IllegalStateException("No Configuration Settings received"); } ConfigurationSettingsDescription configSettings = configurationSettings.getConfigurationSettings().get(0); Map<String, ConfigurationOptionSetting> keyMap = new LinkedHashMap<String, ConfigurationOptionSetting>(); for (ConfigurationOptionSetting d : configSettings.getOptionSettings()) { String key = String.format("beanstalk.env.%s.%s", d.getNamespace().replaceAll(":", "."), d.getOptionName()); String defaultValue = ""; String outputKey = key; keyMap.put(key, d); for (Map.Entry<String, ConfigurationOptionSetting> cosEntry : COMMON_PARAMETERS.entrySet()) { ConfigurationOptionSetting v = cosEntry.getValue(); boolean match = v.getNamespace().equals(d.getNamespace()) && v.getOptionName().equals(d.getOptionName()); if (match) { outputKey = cosEntry.getKey(); break; } } if (defaultSettings.containsKey(outputKey)) { defaultValue = StringUtils.defaultString(defaultSettings.get(outputKey).getDefaultValue()); } String value = d.getValue(); if (null == value || StringUtils.isBlank("" + value)) { continue; } if (!defaultValue.equals(value)) { if (!value.contains(curEnv.getEnvironmentId())) { getLog().info("Adding property " + key); if (changedOnly) { String curValue = project.getProperties().getProperty(outputKey); if (!value.equals(curValue)) { newProperties.put(outputKey, value); } } else { newProperties.put(outputKey, value); } } else { getLog().info("Ignoring property " + outputKey + "(value=" + value + ") due to containing references to the environment id"); } } else { getLog().debug("Ignoring property " + key + " (defaulted)"); } } if ("properties".equals(this.outputFileFormat)) { String comment = "elastic beanstalk environment properties for " + curEnv.getEnvironmentName(); if (null != outputFile) { newProperties.store(new FileOutputStream(outputFile), comment); } else { newProperties.store(System.out, comment); } } else if ("yaml".equals(this.outputFileFormat)) { PrintStream printStream = System.out; if (null != outputFile) { printStream = new PrintStream(outputFile); } printStream.println("option_settings:"); for (Map.Entry<Object, Object> e : newProperties.entrySet()) { ConfigurationOptionSetting c = keyMap.get("" + e.getKey()); String value = "" + e.getValue(); printStream.println(" - namespace: " + c.getNamespace()); printStream.println(" option_name: " + c.getOptionName()); printStream.println(" value: " + value); } printStream.close(); } return null; }
From source file:com.photon.phresco.framework.rest.api.ParameterService.java
@POST @Path("/sonarParam/save") @Produces(MediaType.APPLICATION_JSON)/*from w ww.j a v a 2 s . co m*/ public Response setSonarConfiguration(SonarParams sonarparams) throws PhrescoException { ResponseInfo<String> responseData = new ResponseInfo<String>(); Properties sonarConfig = new Properties(); OutputStream outputStream = null; InputStream inputstream = null; try { inputstream = this.getClass().getClassLoader().getResourceAsStream("framework.config"); sonarConfig.load(inputstream); sonarConfig.setProperty("phresco.code.sonar.url", sonarparams.getSonarUrl()); sonarConfig.setProperty("phresco.code.sonar.jdbc.url", sonarparams.getSonarJdbcUrl()); sonarConfig.setProperty("phresco.code.sonar.username", sonarparams.getUsername()); sonarConfig.setProperty("phresco.code.sonar.password", sonarparams.getPassword()); sonarConfig.setProperty("phresco.code.remote.sonar", sonarparams.getRemoteSonar()); inputstream.close(); URL resource = this.getClass().getClassLoader().getResource("framework.config"); String filePath = resource.getPath(); File configFile = new File(filePath); if (configFile.exists()) { outputStream = new FileOutputStream(configFile); sonarConfig.store(outputStream, null); } ResponseInfo<String> finalOutput = responseDataEvaluation(responseData, null, null, RESPONSE_STATUS_SUCCESS, PHR500006); return Response.ok(finalOutput).header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER).build(); } catch (IOException e) { ResponseInfo<String> finalOutput = responseDataEvaluation(responseData, e, null, RESPONSE_STATUS_ERROR, PHR510012); return Response.status(Status.OK).entity(finalOutput).header(ACCESS_CONTROL_ALLOW_ORIGIN, ALL_HEADER) .build(); } finally { Utility.closeStream(outputStream); } }
From source file:me.mast3rplan.phantombot.PhantomBot.java
public void updateGameWispTokens(String[] newTokens) { Properties outputProperties = new Properties() { @Override/*from w w w . ja va 2s. c o m*/ public synchronized Enumeration<Object> keys() { return Collections.enumeration(new TreeSet<>(super.keySet())); } }; gameWispOAuth = newTokens[0]; gameWispRefresh = newTokens[1]; pbProperties.setProperty("gamewispauth", newTokens[0]); pbProperties.setProperty("gamewisprefresh", newTokens[1]); try { try (FileOutputStream outputStream = new FileOutputStream("botlogin.txt")) { outputProperties.putAll(pbProperties); outputProperties.store(outputStream, "PhantomBot Configuration File"); } print("GameWisp Token has been refreshed."); } catch (IOException ex) { com.gmt2001.Console.err.println( "!!!! CRITICAL !!!! Failed to update GameWisp Refresh Tokens into botlogin.txt! Must manually add!"); com.gmt2001.Console.err.println( "!!!! CRITICAL !!!! gamewispauth = " + newTokens[0] + " gamewisprefresh = " + newTokens[1]); } SingularityAPI.instance().setAccessToken(gameWispOAuth); }