List of usage examples for org.w3c.dom Document getFirstChild
public Node getFirstChild();
From source file:ch.entwine.weblounge.common.impl.site.SiteImpl.java
/** * Loads and registers the integration tests that are found in the bundle at * the given location./*from w w w .j a va2 s . co m*/ * * @param dir * the directory containing the test files */ private List<IntegrationTest> loadIntegrationTestDefinitions(String dir) { Enumeration<?> entries = bundleContext.getBundle().findEntries(dir, "*.xml", true); // Schema validator setup SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); URL schemaUrl = SiteImpl.class.getResource("/xsd/test.xsd"); Schema testSchema = null; try { testSchema = schemaFactory.newSchema(schemaUrl); } catch (SAXException e) { logger.error("Error loading XML schema for test definitions: {}", e.getMessage()); return Collections.emptyList(); } // Module.xml document builder setup DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setSchema(testSchema); docBuilderFactory.setNamespaceAware(true); // The list of tests List<IntegrationTest> tests = new ArrayList<IntegrationTest>(); while (entries != null && entries.hasMoreElements()) { URL entry = (URL) entries.nextElement(); // Validate and read the module descriptor ValidationErrorHandler errorHandler = new ValidationErrorHandler(entry); DocumentBuilder docBuilder; try { docBuilder = docBuilderFactory.newDocumentBuilder(); docBuilder.setErrorHandler(errorHandler); Document doc = docBuilder.parse(entry.openStream()); if (errorHandler.hasErrors()) { logger.warn("Error parsing integration test {}: XML validation failed", entry); continue; } IntegrationTestGroup test = IntegrationTestParser.fromXml(doc.getFirstChild()); test.setSite(this); test.setGroup(getName()); tests.add(test); } catch (SAXException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new IllegalStateException(e); } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } } return tests; }
From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java
@Override public String newElementIdByPath(String path, final String xmlData) throws SAXException, IOException, XPathExpressionException { Assert.hasText(path);/* w ww.j a v a2s . c o m*/ Assert.hasText(xmlData); Document finalDom = parse(xmlData); XPathExpression xPathExpression = null; XPath xPath = getXPathInstance(); xPathExpression = xPath.compile(path); NodeList nodeList = (NodeList) (xPathExpression.evaluate(finalDom, XPathConstants.NODESET)); int l = nodeList.getLength(); Element currentElement = null; for (int i = 0; i < l; i++) { if (nodeList.item(i) == null) continue; String id = UUID.randomUUID().toString(); currentElement = (Element) nodeList.item(i); currentElement.setAttribute("id", id); } return DomUtils.elementToString(finalDom.getFirstChild()); }
From source file:net.sourceforge.eclipsetrader.core.internal.XMLRepository.java
private History loadHistory(Integer id) { History barData = new History(id); File file = new File(Platform.getLocation().toFile(), "history/" + String.valueOf(id) + ".xml"); //$NON-NLS-1$ //$NON-NLS-2$ $NON-NLS-2$ if (file.exists() == true) { try {/* w w w . j av a2 s. co m*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(errorHandler); Document document = builder.parse(file); barData.addAll(decodeBarData(document.getFirstChild().getChildNodes())); } catch (Exception e) { log.error(e.toString(), e); } } barData.clearChanged(); return barData; }
From source file:net.sourceforge.eclipsetrader.core.internal.XMLRepository.java
public IntradayHistory loadIntradayHistory(Integer id) { IntradayHistory barData = new IntradayHistory(id); File file = new File(Platform.getLocation().toFile(), "intraday/" + String.valueOf(id) + ".xml"); //$NON-NLS-1$ //$NON-NLS-2$ if (file.exists() == true) { try {/* www . ja va 2 s . c o m*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(errorHandler); Document document = builder.parse(file); barData.addAll(decodeBarData(document.getFirstChild().getChildNodes())); } catch (Exception e) { log.error(e.toString(), e); } } barData.clearChanged(); return barData; }
From source file:eu.apenet.dpt.standalone.gui.DataPreparationToolGUI.java
private void wireUp() { fileItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { if (actionEvent.getSource() == fileItem) { currentLocation = new File(retrieveFromDb.retrieveOpenLocation()); fileChooser.setCurrentDirectory(currentLocation); int returnedVal = fileChooser.showOpenDialog(getParent()); if (returnedVal == JFileChooser.APPROVE_OPTION) { currentLocation = fileChooser.getCurrentDirectory(); retrieveFromDb.saveOpenLocation(currentLocation.getAbsolutePath()); RootPaneContainer root = (RootPaneContainer) getRootPane().getTopLevelAncestor(); root.getGlassPane().setCursor(WAIT_CURSOR); root.getGlassPane().setVisible(true); File[] files = fileChooser.getSelectedFiles(); for (File file : files) { if (file.isDirectory()) { File[] fileArray = file.listFiles(); Arrays.sort(fileArray, new FileNameComparator()); for (File children : fileArray) { if (isCorrect(children)) { xmlEadListModel.addFile(children); }/*from ww w . j a v a2s. c o m*/ } } else { if (isCorrect(file)) { xmlEadListModel.addFile(file); } } } root.getGlassPane().setCursor(DEFAULT_CURSOR); root.getGlassPane().setVisible(false); } } } }); repositoryCodeItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createOptionPaneForRepositoryCode(); } }); countryCodeItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createOptionPaneForCountryCode(); } }); checksLoadingFilesItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { createOptionPaneForChecksLoadingFiles(); } }); createEag2012FromExistingEag2012.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser eagFileChooser = new JFileChooser(); eagFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); eagFileChooser.setMultiSelectionEnabled(false); eagFileChooser.setCurrentDirectory(new File(retrieveFromDb.retrieveOpenLocation())); if (eagFileChooser.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION) { currentLocation = eagFileChooser.getCurrentDirectory(); retrieveFromDb.saveOpenLocation(currentLocation.getAbsolutePath()); File eagFile = eagFileChooser.getSelectedFile(); if (!Eag2012Frame.isUsed()) { try { if (ReadXml.isXmlFile(eagFile, "eag")) { new Eag2012Frame(eagFile, getContentPane().getSize(), (ProfileListModel) getXmlEadList().getModel(), labels); } else { JOptionPane.showMessageDialog(rootPane, labels.getString("eag2012.errors.notAnEagFile")); } } catch (SAXException ex) { if (ex instanceof SAXParseException) { JOptionPane.showMessageDialog(rootPane, labels.getString("eag2012.errors.notAnEagFile")); } java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } catch (IOException ex) { java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } catch (Exception ex) { try { JOptionPane.showMessageDialog(rootPane, labels.getString(ex.getMessage())); } catch (Exception ex1) { JOptionPane.showMessageDialog(rootPane, "Error..."); } } } } } }); createEag2012FromScratch.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!Eag2012Frame.isUsed()) { new Eag2012Frame(getContentPane().getSize(), (ProfileListModel) getXmlEadList().getModel(), labels, retrieveFromDb.retrieveCountryCode(), retrieveFromDb.retrieveRepositoryCode()); } } }); digitalObjectTypeItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!DigitalObjectAndRightsOptionFrame.isInUse()) { JFrame DigitalObjectAndRightsOptionFrame = new DigitalObjectAndRightsOptionFrame(labels, retrieveFromDb); DigitalObjectAndRightsOptionFrame.setPreferredSize(new Dimension( getContentPane().getWidth() * 3 / 8, getContentPane().getHeight() * 3 / 4)); DigitalObjectAndRightsOptionFrame.setLocation(getContentPane().getWidth() / 8, getContentPane().getHeight() / 8); DigitalObjectAndRightsOptionFrame.pack(); DigitalObjectAndRightsOptionFrame.setVisible(true); } } }); defaultSaveFolderItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { JFileChooser defaultSaveFolderChooser = new JFileChooser(); defaultSaveFolderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); defaultSaveFolderChooser.setMultiSelectionEnabled(false); defaultSaveFolderChooser.setCurrentDirectory(new File(retrieveFromDb.retrieveDefaultSaveFolder())); if (defaultSaveFolderChooser.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION) { File directory = defaultSaveFolderChooser.getSelectedFile(); if (directory.canWrite() && DirectoryPermission.canWrite(directory)) { retrieveFromDb.saveDefaultSaveFolder(directory + "/"); } else { createErrorOrWarningPanel(new Exception(labels.getString("error.directory.nowrites")), false, labels.getString("error.directory.nowrites"), getContentPane()); } } } }); listDateConversionRulesItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { JDialog dateConversionRulesDialog = new DateConversionRulesDialog(labels, retrieveFromDb); dateConversionRulesDialog.setPreferredSize( new Dimension(getContentPane().getWidth() * 3 / 8, getContentPane().getHeight() * 7 / 8)); dateConversionRulesDialog.setLocation(getContentPane().getWidth() / 8, getContentPane().getHeight() / 8); dateConversionRulesDialog.pack(); dateConversionRulesDialog.setVisible(true); } }); edmGeneralOptionsItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (!EdmGeneralOptionsFrame.isInUse()) { JFrame edmGeneralOptionsFrame = new EdmGeneralOptionsFrame(labels, retrieveFromDb); edmGeneralOptionsFrame.setPreferredSize(new Dimension(getContentPane().getWidth() * 3 / 8, getContentPane().getHeight() * 3 / 8)); edmGeneralOptionsFrame.setLocation(getContentPane().getWidth() / 8, getContentPane().getHeight() / 8); edmGeneralOptionsFrame.pack(); edmGeneralOptionsFrame.setVisible(true); } } }); closeSelectedItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { xmlEadListModel.removeFiles(xmlEadList.getSelectedValues()); } }); saveSelectedItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String defaultOutputDirectory = retrieveFromDb.retrieveDefaultSaveFolder(); boolean isMultipleFiles = xmlEadList.getSelectedIndices().length > 1; RootPaneContainer root = (RootPaneContainer) getRootPane().getTopLevelAncestor(); root.getGlassPane().setCursor(WAIT_CURSOR); root.getGlassPane().setVisible(true); for (Object selectedValue : xmlEadList.getSelectedValues()) { File selectedFile = (File) selectedValue; String filename = selectedFile.getName(); FileInstance fileInstance = fileInstances.get(filename); String filePrefix = fileInstance.getFileType().getFilePrefix(); //todo: do we really need this? filename = filename.startsWith("temp_") ? filename.replace("temp_", "") : filename; filename = !filename.endsWith(".xml") ? filename + ".xml" : filename; if (!fileInstance.isValid()) { filePrefix = "NOT_" + filePrefix; } if (fileInstance.getLastOperation().equals(FileInstance.Operation.EDIT_TREE)) { TreeTableModel treeTableModel = tree.getTreeTableModel(); Document document = (Document) treeTableModel.getRoot(); try { File file2 = new File(defaultOutputDirectory + filePrefix + "_" + filename); File filetemp = new File(Utilities.TEMP_DIR + "temp_" + filename); TransformerFactory tf = TransformerFactory.newInstance(); Transformer output = tf.newTransformer(); output.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes"); output.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); DOMSource domSource = new DOMSource(document.getFirstChild()); output.transform(domSource, new StreamResult(filetemp)); output.transform(domSource, new StreamResult(file2)); fileInstance.setLastOperation(FileInstance.Operation.SAVE); fileInstance.setCurrentLocation(filetemp.getAbsolutePath()); } catch (Exception ex) { createErrorOrWarningPanel(ex, true, labels.getString("errorSavingTreeXML"), getContentPane()); } } else if (fileInstance.isConverted()) { try { File newFile = new File(defaultOutputDirectory + filePrefix + "_" + filename); FileUtils.copyFile(new File(fileInstance.getCurrentLocation()), newFile); fileInstance.setLastOperation(FileInstance.Operation.SAVE); // fileInstance.setCurrentLocation(newFile.getAbsolutePath()); } catch (IOException ioe) { LOG.error("Error when saving file", ioe); } } else { try { File newFile = new File(defaultOutputDirectory + filePrefix + "_" + filename); FileUtils.copyFile(selectedFile, newFile); fileInstance.setLastOperation(FileInstance.Operation.SAVE); // fileInstance.setCurrentLocation(newFile.getAbsolutePath()); } catch (IOException ioe) { LOG.error("Error when saving file", ioe); } } } root.getGlassPane().setCursor(DEFAULT_CURSOR); root.getGlassPane().setVisible(false); if (isMultipleFiles) { JOptionPane.showMessageDialog(getContentPane(), MessageFormat.format(labels.getString("filesInOutput"), defaultOutputDirectory) + ".", labels.getString("fileSaved"), JOptionPane.INFORMATION_MESSAGE, Utilities.icon); } else { JOptionPane.showMessageDialog(getContentPane(), MessageFormat.format(labels.getString("fileInOutput"), defaultOutputDirectory) + ".", labels.getString("fileSaved"), JOptionPane.INFORMATION_MESSAGE, Utilities.icon); } xmlEadList.updateUI(); } }); saveMessageReportItem.addActionListener( new MessageReportActionListener(retrieveFromDb, this, fileInstances, labels, this)); sendFilesWebDAV.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { throw new UnsupportedOperationException("Not supported yet."); } }); quitItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); xsltItem.addActionListener(new XsltAdderActionListener(this, labels)); xsdItem.addActionListener(new XsdAdderActionListener(this, labels, retrieveFromDb)); if (Utilities.isDev) { databaseItem.addActionListener(new DatabaseCheckerActionListener(retrieveFromDb, getContentPane())); } xmlEadList.addMouseListener(new ListMouseAdapter(xmlEadList, xmlEadListModel, deleteFileItem, this)); xmlEadList.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { if (xmlEadList.getSelectedValues() != null && xmlEadList.getSelectedValues().length != 0) { if (xmlEadList.getSelectedValues().length > 1) { // convertAndValidateBtn.setEnabled(true); // validateSelectionBtn.setEnabled(true); // if (isValidated(xmlEadList)) { // convertEdmSelectionBtn.setEnabled(true); // } else { // convertEdmSelectionBtn.setEnabled(false); // } // disableAllBtnAndItems(); saveMessageReportItem.setEnabled(true); changeInfoInGUI(""); } else { // convertAndValidateBtn.setEnabled(false); // validateSelectionBtn.setEnabled(false); // convertEdmSelectionBtn.setEnabled(false); changeInfoInGUI(((File) xmlEadList.getSelectedValue()).getName()); if (apePanel.getApeTabbedPane().getSelectedIndex() == APETabbedPane.TAB_EDITION) { apePanel.getApeTabbedPane() .createEditionTree(((File) xmlEadList.getSelectedValue())); if (tree != null) { FileInstance fileInstance = fileInstances .get(((File) getXmlEadList().getSelectedValue()).getName()); tree.addMouseListener(new PopupMouseListener(tree, getDataPreparationToolGUI(), getContentPane(), fileInstance)); } } disableTabFlashing(); } checkHoldingsGuideButton(); } else { // convertAndValidateBtn.setEnabled(false); // validateSelectionBtn.setEnabled(false); // convertEdmSelectionBtn.setEnabled(false); createHGBtn.setEnabled(false); analyzeControlaccessBtn.setEnabled(false); changeInfoInGUI(""); } } } private boolean isValidated(JList xmlEadList) { for (Object selectedValue : xmlEadList.getSelectedValues()) { File selectedFile = (File) selectedValue; String filename = selectedFile.getName(); FileInstance fileInstance = fileInstances.get(filename); if (!fileInstance.isValid()) { return false; } } return true; } }); summaryWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_SUMMARY)); validationWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_VALIDATION)); conversionWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_CONVERSION)); edmConversionWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_EDM)); editionWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_EDITION)); internetApexItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { BareBonesBrowserLaunch.openURL("http://www.apex-project.eu/"); } }); /** * Option Edit apeEAC-CPF file in the menu */ this.editEacCpfFile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser eacFileChooser = new JFileChooser(); eacFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); eacFileChooser.setMultiSelectionEnabled(false); eacFileChooser.setCurrentDirectory(new File(retrieveFromDb.retrieveOpenLocation())); if (eacFileChooser.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION) { currentLocation = eacFileChooser.getCurrentDirectory(); retrieveFromDb.saveOpenLocation(currentLocation.getAbsolutePath()); File eacFile = eacFileChooser.getSelectedFile(); if (!EacCpfFrame.isUsed()) { try { if (ReadXml.isXmlFile(eacFile, "eac-cpf")) { new EacCpfFrame(eacFile, true, getContentPane().getSize(), (ProfileListModel) getXmlEadList().getModel(), labels); } else { JOptionPane.showMessageDialog(rootPane, labels.getString("eaccpf.error.notAnEacCpfFile")); } } catch (SAXException ex) { if (ex instanceof SAXParseException) { JOptionPane.showMessageDialog(rootPane, labels.getString("eaccpf.error.notAnEacCpfFile")); } java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } catch (IOException ex) { java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } catch (Exception ex) { try { JOptionPane.showMessageDialog(rootPane, labels.getString(ex.getMessage())); } catch (Exception ex1) { JOptionPane.showMessageDialog(rootPane, "Error..."); } } } } } }); /** * Option Create apeEAC-CPF in the menu */ this.createEacCpf.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!EacCpfFrame.isUsed()) { EacCpfFrame eacCpfFrame = new EacCpfFrame(getContentPane().getSize(), (ProfileListModel) getXmlEadList().getModel(), labels, retrieveFromDb.retrieveCountryCode(), retrieveFromDb.retrieveRepositoryCode(), null, null, null); } } }); }
From source file:net.sourceforge.eclipsetrader.core.internal.XMLRepository.java
private Chart loadChart(Integer id) { Chart chart = new Chart(id); chart.setRepository(this); chart.setSecurity((Security) load(Security.class, id)); File file = new File(Platform.getLocation().toFile(), "charts/" + String.valueOf(id) + ".xml"); //$NON-NLS-1$ //$NON-NLS-2$ if (file.exists() == false) file = new File(Platform.getLocation().toFile(), "charts/default.xml"); //$NON-NLS-1$ if (file.exists() == true) { try {//from ww w.j a v a 2s . c o m DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(errorHandler); Document document = builder.parse(file); NodeList firstNode = document.getFirstChild().getChildNodes(); for (int r = 0; r < firstNode.getLength(); r++) { Node item = firstNode.item(r); Node valueNode = item.getFirstChild(); String nodeName = item.getNodeName(); if (valueNode != null) { if (nodeName.equalsIgnoreCase("compression") == true) //$NON-NLS-1$ chart.setCompression(Integer.parseInt(valueNode.getNodeValue())); else if (nodeName.equalsIgnoreCase("period") == true) //$NON-NLS-1$ chart.setPeriod(Integer.parseInt(valueNode.getNodeValue())); else if (nodeName.equalsIgnoreCase("autoScale") == true) //$NON-NLS-1$ chart.setAutoScale(new Boolean(valueNode.getNodeValue()).booleanValue()); else if (nodeName.equalsIgnoreCase("begin") == true) //$NON-NLS-1$ { try { chart.setBeginDate(dateTimeFormat.parse(valueNode.getNodeValue())); } catch (Exception e) { log.warn(e.toString()); } } else if (nodeName.equalsIgnoreCase("end") == true) //$NON-NLS-1$ { try { chart.setEndDate(dateTimeFormat.parse(valueNode.getNodeValue())); } catch (Exception e) { log.warn(e.toString()); } } } if (nodeName.equalsIgnoreCase("row")) //$NON-NLS-1$ { ChartRow row = new ChartRow(new Integer(r)); row.setRepository(this); row.setParent(chart); NodeList tabList = item.getChildNodes(); for (int t = 0; t < tabList.getLength(); t++) { item = tabList.item(t); nodeName = item.getNodeName(); if (nodeName.equalsIgnoreCase("tab")) //$NON-NLS-1$ { ChartTab tab = new ChartTab(new Integer(t)); tab.setRepository(this); tab.setParent(row); tab.setLabel(((Node) item).getAttributes().getNamedItem("label").getNodeValue()); //$NON-NLS-1$ NodeList indicatorList = item.getChildNodes(); for (int i = 0; i < indicatorList.getLength(); i++) { item = indicatorList.item(i); nodeName = item.getNodeName(); if (nodeName.equalsIgnoreCase("indicator")) //$NON-NLS-1$ { ChartIndicator indicator = new ChartIndicator(new Integer(i)); indicator.setRepository(this); indicator.setParent(tab); indicator.setPluginId(((Node) item).getAttributes().getNamedItem("pluginId") //$NON-NLS-1$ .getNodeValue()); NodeList parametersList = item.getChildNodes(); for (int p = 0; p < parametersList.getLength(); p++) { item = parametersList.item(p); nodeName = item.getNodeName(); if (nodeName.equalsIgnoreCase("param")) //$NON-NLS-1$ { String key = ((Node) item).getAttributes().getNamedItem("key") //$NON-NLS-1$ .getNodeValue(); String value = ((Node) item).getAttributes().getNamedItem("value") //$NON-NLS-1$ .getNodeValue(); indicator.getParameters().put(key, value); } } tab.getIndicators().add(indicator); } else if (nodeName.equalsIgnoreCase("object")) //$NON-NLS-1$ { ChartObject object = new ChartObject(new Integer(i)); object.setRepository(this); object.setParent(tab); object.setPluginId(((Node) item).getAttributes().getNamedItem("pluginId") //$NON-NLS-1$ .getNodeValue()); NodeList parametersList = item.getChildNodes(); for (int p = 0; p < parametersList.getLength(); p++) { item = parametersList.item(p); nodeName = item.getNodeName(); if (nodeName.equalsIgnoreCase("param")) //$NON-NLS-1$ { String key = ((Node) item).getAttributes().getNamedItem("key") //$NON-NLS-1$ .getNodeValue(); String value = ((Node) item).getAttributes().getNamedItem("value") //$NON-NLS-1$ .getNodeValue(); object.getParameters().put(key, value); } } tab.getObjects().add(object); } } row.getTabs().add(tab); } } chart.getRows().add(row); } } } catch (Exception e) { log.error(e.toString(), e); } } if (chart.getTitle().length() == 0) chart.setTitle(chart.getSecurity().getDescription()); chart.clearChanged(); return chart; }
From source file:net.sourceforge.eclipsetrader.core.internal.XMLRepository.java
public XMLRepository() { File file = new File(Platform.getLocation().toFile(), "securities.xml"); //$NON-NLS-1$ if (file.exists() == true) { log.info("Loading securities"); //$NON-NLS-1$ try {/*from ww w . j av a2 s . co m*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(errorHandler); Document document = builder.parse(file); Node firstNode = document.getFirstChild(); securitiesNextId = new Integer(firstNode.getAttributes().getNamedItem("nextId").getNodeValue()); //$NON-NLS-1$ if (firstNode.getAttributes().getNamedItem("nextGroupId") != null) //$NON-NLS-1$ securitiesGroupNextId = new Integer( firstNode.getAttributes().getNamedItem("nextGroupId").getNodeValue()); //$NON-NLS-1$ NodeList childNodes = firstNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node item = childNodes.item(i); String nodeName = item.getNodeName(); if (nodeName.equalsIgnoreCase("security")) //$NON-NLS-1$ { Security obj = loadSecurity(item.getChildNodes()); obj.setRepository(this); securitiesMap.put(obj.getId(), obj); allSecurities().add(obj); } else if (nodeName.equalsIgnoreCase("group")) //$NON-NLS-1$ { SecurityGroup obj = loadSecurityGroup(item.getChildNodes()); obj.setRepository(this); allSecurityGroups().add(obj); } } } catch (Exception e) { log.error(e.toString(), e); } } file = new File(Platform.getLocation().toFile(), "watchlists.xml"); //$NON-NLS-1$ if (file.exists() == true) { log.info("Loading watchlists"); //$NON-NLS-1$ try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(errorHandler); Document document = builder.parse(file); Node firstNode = document.getFirstChild(); watchlistsNextId = new Integer(firstNode.getAttributes().getNamedItem("nextId").getNodeValue()); //$NON-NLS-1$ NodeList childNodes = firstNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node item = childNodes.item(i); String nodeName = item.getNodeName(); if (nodeName.equalsIgnoreCase("watchlist")) //$NON-NLS-1$ { Watchlist obj = loadWatchlist(item.getChildNodes()); obj.setRepository(this); watchlistsMap.put(obj.getId(), obj); allWatchlists().add(obj); } } } catch (Exception e) { log.error(e.toString(), e); } } file = new File(Platform.getLocation().toFile(), "charts.xml"); //$NON-NLS-1$ if (file.exists() == true) { log.info("Loading charts"); //$NON-NLS-1$ try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(errorHandler); Document document = builder.parse(file); Node firstNode = document.getFirstChild(); chartsNextId = new Integer(firstNode.getAttributes().getNamedItem("nextId").getNodeValue()); //$NON-NLS-1$ NodeList childNodes = firstNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node item = childNodes.item(i); String nodeName = item.getNodeName(); if (nodeName.equalsIgnoreCase("chart")) //$NON-NLS-1$ { Chart obj = loadChart(item.getChildNodes()); if (obj.getSecurity() != null) { obj.setRepository(this); chartsMap.put(obj.getId(), obj); allCharts().add(obj); } } } } catch (Exception e) { log.error(e.toString(), e); } } boolean needToSave = false; for (Iterator iter = allSecurities().iterator(); iter.hasNext();) { Security security = (Security) iter.next(); file = new File(Platform.getLocation().toFile(), "charts/" + String.valueOf(security.getId()) + ".xml"); //$NON-NLS-1$ //$NON-NLS-2$ if (file.exists()) { Chart obj = loadChart(security.getId()); if (obj.getSecurity() != null) { if (obj.getId().intValue() > chartsNextId.intValue()) chartsNextId = getNextId(obj.getId()); obj.setRepository(this); chartsMap.put(obj.getId(), obj); allCharts().add(obj); file.delete(); needToSave = true; } } } if (needToSave) saveCharts(); file = new File(Platform.getLocation().toFile(), "news.xml"); //$NON-NLS-1$ if (file.exists() == true) { log.info("Loading news"); //$NON-NLS-1$ try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(errorHandler); Document document = builder.parse(file); Calendar limit = Calendar.getInstance(); limit.add(Calendar.DATE, -CorePlugin.getDefault().getPreferenceStore().getInt(CorePlugin.PREFS_NEWS_DATE_RANGE)); Node firstNode = document.getFirstChild(); NodeList childNodes = firstNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node item = childNodes.item(i); String nodeName = item.getNodeName(); if (nodeName.equalsIgnoreCase("news")) //$NON-NLS-1$ { NewsItem obj = loadNews(item.getChildNodes()); if (obj.getDate().before(limit.getTime())) continue; obj.setRepository(this); allNews().add(obj); } } } catch (Exception e) { log.error(e.toString(), e); } } file = new File(Platform.getLocation().toFile(), "accounts.xml"); //$NON-NLS-1$ if (file.exists() == true) { log.info("Loading accounts"); //$NON-NLS-1$ try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(errorHandler); Document document = builder.parse(file); Node firstNode = document.getFirstChild(); accountNextId = new Integer(firstNode.getAttributes().getNamedItem("nextId").getNodeValue()); //$NON-NLS-1$ accountGroupNextId = new Integer( firstNode.getAttributes().getNamedItem("nextGroupId").getNodeValue()); //$NON-NLS-1$ NodeList childNodes = firstNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node item = childNodes.item(i); String nodeName = item.getNodeName(); if (nodeName.equalsIgnoreCase("account")) //$NON-NLS-1$ { Account obj = loadAccount(item.getChildNodes(), null); obj.setRepository(this); } else if (nodeName.equalsIgnoreCase("group")) //$NON-NLS-1$ { AccountGroup obj = loadAccountGroup(item.getChildNodes(), null); obj.setRepository(this); } } } catch (Exception e) { log.error(e.toString(), e); } } file = new File(Platform.getLocation().toFile(), "events.xml"); //$NON-NLS-1$ if (file.exists() == true) { log.info("Loading events"); //$NON-NLS-1$ try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(errorHandler); Document document = builder.parse(file); Node firstNode = document.getFirstChild(); NodeList childNodes = firstNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node item = childNodes.item(i); String nodeName = item.getNodeName(); if (nodeName.equalsIgnoreCase("event")) //$NON-NLS-1$ { Event obj = loadEvent(item.getChildNodes()); obj.setRepository(this); allEvents().add(obj); } } } catch (Exception e) { log.error(e.toString(), e); } } file = new File(Platform.getLocation().toFile(), "orders.xml"); //$NON-NLS-1$ if (file.exists() == true) { log.info("Loading orders"); //$NON-NLS-1$ try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(errorHandler); Document document = builder.parse(file); Node firstNode = document.getFirstChild(); orderNextId = new Integer(firstNode.getAttributes().getNamedItem("nextId").getNodeValue()); //$NON-NLS-1$ NodeList childNodes = firstNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node item = childNodes.item(i); String nodeName = item.getNodeName(); if (nodeName.equalsIgnoreCase("order")) //$NON-NLS-1$ { Order obj = loadOrder(item.getChildNodes()); obj.setRepository(this); allOrders().add(obj); } } } catch (Exception e) { log.error(e.toString(), e); } } eventNextId = new Integer(allEvents().size() + 1); tradingRepository = new TradingSystemRepository(this); }
From source file:ch.entwine.weblounge.common.impl.site.SiteImpl.java
/** * Initializes the site components like modules, templates, actions etc. * /*from w w w . j a v a 2 s . c om*/ * @throws Exception * if initialization fails */ private void initializeSiteComponents() throws Exception { logger.debug("Initializing site '{}'", this); final Bundle bundle = bundleContext.getBundle(); // Load i18n dictionary Enumeration<URL> i18nEnum = bundle.findEntries("site/i18n", "*.xml", true); while (i18nEnum != null && i18nEnum.hasMoreElements()) { i18n.addDictionary(i18nEnum.nextElement()); } // Prepare schema validator SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); URL schemaUrl = SiteImpl.class.getResource("/xsd/module.xsd"); Schema moduleSchema = schemaFactory.newSchema(schemaUrl); // Set up the document builder DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setSchema(moduleSchema); docBuilderFactory.setNamespaceAware(true); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); // Load the modules final Enumeration<URL> e = bundle.findEntries("site", "module.xml", true); if (e != null) { while (e.hasMoreElements()) { URL moduleXmlUrl = e.nextElement(); int endIndex = moduleXmlUrl.toExternalForm().lastIndexOf('/'); URL moduleUrl = new URL(moduleXmlUrl.toExternalForm().substring(0, endIndex)); logger.debug("Loading module '{}' for site '{}'", moduleXmlUrl, this); // Load and validate the module descriptor ValidationErrorHandler errorHandler = new ValidationErrorHandler(moduleXmlUrl); docBuilder.setErrorHandler(errorHandler); Document moduleXml = docBuilder.parse(moduleXmlUrl.openStream()); if (errorHandler.hasErrors()) { logger.error("Errors found while validating module descriptor {}. Site '{}' is not loaded", moduleXml, this); throw new IllegalStateException("Errors found while validating module descriptor " + moduleXml); } // We need the module id even if the module initialization fails to log // a proper error message Node moduleNode = moduleXml.getFirstChild(); String moduleId = moduleNode.getAttributes().getNamedItem("id").getNodeValue(); Module module; try { module = ModuleImpl.fromXml(moduleNode); logger.debug("Module '{}' loaded for site '{}'", module, this); } catch (Throwable t) { logger.error("Error loading module '{}' of site {}", moduleId, identifier); if (t instanceof Exception) throw (Exception) t; throw new Exception(t); } // If module is disabled, don't add it to the site if (!module.isEnabled()) { logger.info("Found disabled module '{}' in site '{}'", module, this); continue; } // Make sure there is only one module with this identifier if (modules.containsKey(module.getIdentifier())) { logger.warn("A module with id '{}' is already registered in site '{}'", module.getIdentifier(), identifier); logger.error("Module '{}' is not registered due to conflicting identifier", module.getIdentifier()); continue; } // Check inter-module compatibility for (Module m : modules.values()) { // Check actions for (Action a : m.getActions()) { for (Action action : module.getActions()) { if (action.getIdentifier().equals(a.getIdentifier())) { logger.warn("Module '{}' of site '{}' already defines an action with id '{}'", new String[] { m.getIdentifier(), identifier, a.getIdentifier() }); } else if (action.getPath().equals(a.getPath())) { logger.warn("Module '{}' of site '{}' already defines an action at '{}'", new String[] { m.getIdentifier(), identifier, a.getPath() }); logger.error( "Module '{}' of site '{}' is not registered due to conflicting mountpoints", m.getIdentifier(), identifier); continue; } } } // Check image styles for (ImageStyle s : m.getImageStyles()) { for (ImageStyle style : module.getImageStyles()) { if (style.getIdentifier().equals(s.getIdentifier())) { logger.warn("Module '{}' of site '{}' already defines an image style with id '{}'", new String[] { m.getIdentifier(), identifier, s.getIdentifier() }); } } } // Check jobs for (Job j : m.getJobs()) { for (Job job : module.getJobs()) { if (job.getIdentifier().equals(j.getIdentifier())) { logger.warn("Module '{}' of site '{}' already defines a job with id '{}'", new String[] { m.getIdentifier(), identifier, j.getIdentifier() }); } } } } addModule(module); // Do this as last step since we don't want to have i18n dictionaries of // an invalid or disabled module in the site String i18nPath = UrlUtils.concat(moduleUrl.getPath(), "i18n"); i18nEnum = bundle.findEntries(i18nPath, "*.xml", true); while (i18nEnum != null && i18nEnum.hasMoreElements()) { i18n.addDictionary(i18nEnum.nextElement()); } } } else { logger.debug("Site '{}' has no modules", this); } // Look for a job scheduler logger.debug("Signing up for a job scheduling services"); schedulingServiceTracker = new SchedulingServiceTracker(bundleContext, this); schedulingServiceTracker.open(); // Load the tests if (!Environment.Production.equals(environment)) integrationTests = loadIntegrationTests(); else logger.info("Skipped loading of integration tests due to environment '{}'", environment); siteInitialized = true; logger.info("Site '{}' initialized", this); }
From source file:de.fuberlin.wiwiss.marbles.MarblesServlet.java
/** * Enhances source data with consistently colored icons; * adds detailed source list to Fresnel output * //w ww. java 2 s . c o m * @param doc The Fresnel tree */ private void addSources(Document doc, List<org.apache.commons.httpclient.URI> retrievedURLs) { int colorIndex = 0; HashMap<String, Source> sources = new HashMap<String, Source>(); NodeList nodeList = doc.getElementsByTagName("source"); int numNodes = nodeList.getLength(); for (int i = 0; i < numNodes; i++) { Node node = nodeList.item(i); String uri = node.getFirstChild().getFirstChild().getNodeValue(); Source source; /* Get source, create it if necessary */ if (null == (source = sources.get(uri))) { source = new Source(uri); colorIndex = source.determineIcon(colorIndex); sources.put(uri, source); } /* Enhance source reference with icon */ Element sourceIcon = doc.createElementNS(Constants.nsFresnelView, "sourceIcon"); sourceIcon.appendChild(doc.createTextNode(source.getIcon())); node.appendChild(sourceIcon); } /* Supplement source list with retrieved URLs */ if (retrievedURLs != null) for (org.apache.commons.httpclient.URI uri : retrievedURLs) { Source source; if (null == (source = sources.get(uri.toString()))) { source = new Source(uri.toString()); colorIndex = source.determineIcon(colorIndex); sources.put(uri.toString(), source); } } /* Provide list of sources */ RepositoryConnection metaDataConn = null; try { metaDataConn = metaDataRepository.getConnection(); Element sourcesElement = doc.createElementNS(Constants.nsFresnelView, "sources"); for (String uri : sources.keySet()) { Source source = sources.get(uri); sourcesElement.appendChild(source.toElement(doc, cacheController, metaDataConn)); } Node results = doc.getFirstChild(); results.appendChild(sourcesElement); } catch (RepositoryException e) { e.printStackTrace(); } finally { try { if (metaDataConn != null) metaDataConn.close(); } catch (RepositoryException e) { e.printStackTrace(); } } }
From source file:org.gvnix.web.report.roo.addon.addon.ReportMetadata.java
/** * Add a new <bean/> to jasper-views.xml file with the name of the new * report/* w w w .j av a2 s . c om*/ * * @param reportName the name of the report * @return jasperReportBeanId */ private void addNewJasperReportBean(JavaType entity, String reportName, String format) { PathResolver pathResolver = projectOperations.getPathResolver(); // Install CustomJasperReportsMultiFormatView into // top.level.package.<web controllers // sub-package>.servlet.view.jasperreports // if it is not already installed String classMultiFormatView = installCustomJasperReportMultiFormatView(); // The bean id will be entity_reportName String reportBeanId = entity.getSimpleTypeName().toLowerCase().concat("_").concat(reportName.toLowerCase()); // Add config to jasper-views.xml String jasperReportsConfig = pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), "WEB-INF/spring/jasper-views.xml"); MutableFile mutableJasperViewsConfigFile = fileManager.updateFile(jasperReportsConfig); Document jasperViewsConfigDocument; try { jasperViewsConfigDocument = XmlUtils.getDocumentBuilder() .parse(mutableJasperViewsConfigFile.getInputStream()); } catch (Exception ex) { throw new IllegalStateException( "Could not open jasper-views.xml config file '".concat(jasperReportsConfig).concat("'"), ex); } Element beans = jasperViewsConfigDocument.getDocumentElement(); if (null != XmlUtils.findFirstElement("/beans/bean[@id='".concat(reportBeanId).concat("']"), beans)) { // logger.warning("A report with the name " + reportBeanId + // " is already defined"); return; // There is a bean with the reportName already // defined, nothing to do } // Create a DOM element defining the new bean for the JasperReport view InputStream templateInputStream = null; OutputStream jasperViewsConfigOutStream = null; try { templateInputStream = FileUtils.getInputStream(getClass(), "jasperreports-bean-config-template.xml"); Document reportBeanConfigDocument; try { reportBeanConfigDocument = XmlUtils.getDocumentBuilder().parse(templateInputStream); } catch (Exception ex) { throw new IllegalStateException("Could not open jasperreports-bean-config-template.xml file", ex); } Element configElement = (Element) reportBeanConfigDocument.getDocumentElement(); Element bean = XmlUtils.findFirstElement("/config/bean", configElement); // Set the right attributes dynamically bean.setAttribute("id", reportBeanId); bean.setAttribute("class", classMultiFormatView); bean.setAttribute("p:url", "/WEB-INF/reports/".concat(reportBeanId).concat(".jrxml")); bean.setAttribute("p:reportDataKey", reportName.concat("List")); // Add the new bean handling the new report view Element rootElement = (Element) jasperViewsConfigDocument.getFirstChild(); Node importedBean = jasperViewsConfigDocument.importNode(bean, true); rootElement.appendChild(importedBean); jasperViewsConfigOutStream = mutableJasperViewsConfigFile.getOutputStream(); XmlUtils.writeXml(jasperViewsConfigOutStream, jasperViewsConfigDocument); } finally { IOUtils.closeQuietly(templateInputStream); IOUtils.closeQuietly(jasperViewsConfigOutStream); } fileManager.scan(); }