List of usage examples for javax.xml.parsers ParserConfigurationException printStackTrace
public void printStackTrace()
From source file:Interface.MainJFrame.java
private void btnXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXMLActionPerformed // TODO add your handling code here: try {//from ww w .j a v a 2 s . com DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("Employees"); doc.appendChild(rootElement); // staff elements String empTitle = txtEmployeeType.getText().trim(); empTitle = empTitle.replace(" ", ""); Element staff = doc.createElement(empTitle); rootElement.appendChild(staff); // set attribute to staff element Attr attr = doc.createAttribute("ID"); attr.setValue(txtEmployeeID.getText().trim()); staff.setAttributeNode(attr); // shorten way // staff.setAttribute("id", "1"); // FullName elements Element FulllName = doc.createElement("FulllName"); FulllName.appendChild(doc.createTextNode(txtFullName.getText().trim())); staff.appendChild(FulllName); // Phone elements Element Phone = doc.createElement("PhoneNumber"); Phone.appendChild(doc.createTextNode(txtPhoneNumber.getText().trim())); staff.appendChild(Phone); // Address elements Element Address = doc.createElement("Address"); Address.appendChild(doc.createTextNode(txtAddress.getText().trim())); staff.appendChild(Address); // Title elements Element Title = doc.createElement("Tile"); Title.appendChild(doc.createTextNode(txtEmployeeType.getText().trim())); staff.appendChild(Title); // PayCategory elements Element PayCategory = doc.createElement("PayCategory"); PayCategory.appendChild(doc.createTextNode(txtPayCategory.getText().trim())); staff.appendChild(PayCategory); // Salary elements Element Salary = doc.createElement("Salary"); Salary.appendChild(doc.createTextNode(txtSalary.getText().trim())); staff.appendChild(Salary); // Hours elements String hours = txtHours.getText().trim(); if (txtHours.getText().equalsIgnoreCase("") || hours == null) { hours = "null"; } Element Hours = doc.createElement("Hours"); Hours.appendChild(doc.createTextNode(hours)); staff.appendChild(Hours); // Bonus elements Element Bonus = doc.createElement("Bonus"); Bonus.appendChild(doc.createTextNode(txtBonuses.getText().trim())); staff.appendChild(Bonus); // Total elements Element Total = doc.createElement("Total"); Total.appendChild(doc.createTextNode(txtTotal.getText().trim())); staff.appendChild(Total); // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("XMLOutput")); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } }
From source file:de.xplib.xdbm.util.Config.java
/** * /*from ww w.j a v a 2 s . co m*/ */ public void save() { Document doc = null; try { doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element config = (Element) doc.appendChild(doc.createElementNS(CONFIG_NS, "config")); config.setAttribute("xmlns", CONFIG_NS); Element ui = (Element) config.appendChild(doc.createElementNS(CONFIG_NS, "ui-settings")); Node lang = ui.appendChild(doc.createElementNS(CONFIG_NS, "language")); lang.appendChild(doc.createTextNode(this.locale.getLanguage())); Element drivers = (Element) config.appendChild(doc.createElementNS(CONFIG_NS, "drivers")); Iterator dIt = this.dbDrivers.keySet().iterator(); while (dIt.hasNext()) { String jar = (String) dIt.next(); Element driver = (Element) drivers.appendChild(doc.createElementNS(CONFIG_NS, "driver")); driver.setAttribute("jar", jar); driver.setAttribute("class", (String) this.dbDrivers.get(jar)); if (!this.dbUris.containsKey(jar)) { continue; } String value = ""; ArrayList uris = (ArrayList) this.dbUris.get(jar); for (int i = 0, l = uris.size(); i < l; i++) { value += uris.get(i) + "||"; } value = value.substring(0, value.length() - 2); driver.setAttribute("uris", value); } Element conns = (Element) config.appendChild(doc.createElementNS(CONFIG_NS, "connections")); for (int i = 0, s = this.connections.size(); i < s; i++) { Connection conn = (Connection) this.connections.get(i); Element conne = (Element) conns.appendChild(doc.createElementNS(CONFIG_NS, "connection")); conne.setAttribute("jar", conn.getJarFile()); conne.setAttribute("class", conn.getClassName()); conne.setAttribute("uri", conn.getUri()); } Element panels = (Element) config.appendChild(doc.createElementNS(CONFIG_NS, "plugins")); Iterator it = this.plugins.keySet().iterator(); while (it.hasNext()) { PluginFile pluginFile = (PluginFile) this.plugins.get(it.next()); Element elem = (Element) panels.appendChild(doc.createElementNS(CONFIG_NS, "plugin")); elem.setAttribute("jar", pluginFile.getJarFile()); elem.setAttribute("class", pluginFile.getClassName()); elem.setAttribute("id", pluginFile.getId()); elem.setAttribute("position", pluginFile.getPosition()); } } catch (ParserConfigurationException e) { e.printStackTrace(); } if (doc != null) { OutputFormat of = new OutputFormat(doc); of.setIndenting(true); of.setIndent(1); of.setStandalone(true); StringWriter sw = new StringWriter(); XMLSerializer xs = new XMLSerializer(sw, of); xs.setOutputCharStream(sw); try { xs.serialize(doc); sw.flush(); System.out.println(sw.toString()); sw.close(); } catch (IOException e1) { e1.printStackTrace(); } try { FileWriter fw = new FileWriter(this.cfgFile); fw.write(sw.toString()); fw.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:com.sixsq.slipstream.module.ModuleResource.java
@SuppressWarnings("unchecked") private Class<? extends Module> getModuleClass(String moduleAsXml) { String category = null;//from w ww .jav a2 s.c o m try { category = extractCategory(moduleAsXml); } catch (ParserConfigurationException e) { e.printStackTrace(); throwServerError("Failed to parse module"); } catch (SAXException e) { e.printStackTrace(); throwClientBadRequest("Invalid xml document"); } catch (IOException e) { e.printStackTrace(); throwServerError("Failed to parse module"); } String className = "com.sixsq.slipstream.persistence." + category + "Module"; Class<? extends Module> moduleClass = null; try { moduleClass = (Class<? extends Module>) Class.forName(className); } catch (ClassNotFoundException e) { throwClientBadRequest("Unknown category"); } return moduleClass; }
From source file:com.penbase.dma.Dalyo.HTTPConnection.DmaHttpClient.java
/** * Gets the resources of an application// ww w.j a v a2 s . c o m */ public void getResource(String urlRequest) { if (mSendResource) { StringBuffer getResources = new StringBuffer("act=getresources"); getResources.append(urlRequest); byte[] bytes = sendPost(getResources.toString()); SAXParserFactory spFactory = SAXParserFactory.newInstance(); SAXParser saxParser; try { saxParser = spFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); EventsHandler eventsHandler = new EventsHandler(urlRequest); xmlReader.setContentHandler(eventsHandler); xmlReader.parse(new InputSource(new ByteArrayInputStream(bytes))); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Common.streamToFile(bytes, mResources_XML, false); } else { SAXParserFactory spFactory = SAXParserFactory.newInstance(); SAXParser saxParser; try { saxParser = spFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); EventsHandler eventsHandler = new EventsHandler(urlRequest); xmlReader.setContentHandler(eventsHandler); xmlReader.parse(new InputSource(new FileInputStream(new File(mResources_XML)))); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:me.willowcheng.makerthings.ui.OpenHABWidgetListFragment.java
/** * Parse XML sitemap page and show it/*w ww .jav a 2 s. c o m*/ * * @param document XML Document * @return void */ public void processContent(String responseString, boolean longPolling) { // As we change the page we need to stop all videos on current page // before going to the new page. This is quite dirty, but is the only // way to do that... Log.d(TAG, "processContent() " + this.displayPageUrl); Log.d(TAG, "isAdded = " + isAdded()); openHABWidgetAdapter.stopVideoWidgets(); openHABWidgetAdapter.stopImageRefresh(); // If openHAB verion = 1 get page from XML if (mActivity.getOpenHABVersion() == 1) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = dbf.newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(responseString))); if (document != null) { Node rootNode = document.getFirstChild(); openHABWidgetDataSource.setSourceNode(rootNode); widgetList.clear(); for (OpenHABWidget w : openHABWidgetDataSource.getWidgets()) { // Remove frame widgets with no label text if (w.getType().equals("Frame") && TextUtils.isEmpty(w.getLabel())) continue; widgetList.add(w); } } else { Log.e(TAG, "Got a null response from openHAB"); showPage(displayPageUrl, false); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // Later versions work with JSON } else { try { JSONObject pageJson = new JSONObject(responseString); openHABWidgetDataSource.setSourceJson(pageJson); widgetList.clear(); for (OpenHABWidget w : openHABWidgetDataSource.getWidgets()) { // Remove frame widgets with no label text if (w.getType().equals("Frame") && TextUtils.isEmpty(w.getLabel())) continue; widgetList.add(w); } } catch (JSONException e) { e.printStackTrace(); } } openHABWidgetAdapter.notifyDataSetChanged(); if (!longPolling && isAdded()) { getListView().clearChoices(); Log.d(TAG, String.format("processContent selectedItem = %d", mCurrentSelectedItem)); if (mCurrentSelectedItem >= 0) getListView().setItemChecked(mCurrentSelectedItem, true); } if (getActivity() != null && mIsVisible) getActivity().setTitle(openHABWidgetDataSource.getTitle()); // } // Set widget list index to saved or zero position // This would mean we got widget and command from nfc tag, so we need to do some automatic actions! if (this.nfcWidgetId != null && this.nfcCommand != null) { Log.d(TAG, "Have widget and command, NFC action!"); OpenHABWidget nfcWidget = this.openHABWidgetDataSource.getWidgetById(this.nfcWidgetId); OpenHABItem nfcItem = nfcWidget.getItem(); // Found widget with id from nfc tag and it has an item if (nfcWidget != null && nfcItem != null) { // TODO: Perform nfc widget action here if (this.nfcCommand.equals("TOGGLE")) { if (nfcItem.getType().equals("RollershutterItem")) { if (nfcItem.getStateAsBoolean()) this.openHABWidgetAdapter.sendItemCommand(nfcItem, "UP"); else this.openHABWidgetAdapter.sendItemCommand(nfcItem, "DOWN"); } else { if (nfcItem.getStateAsBoolean()) this.openHABWidgetAdapter.sendItemCommand(nfcItem, "OFF"); else this.openHABWidgetAdapter.sendItemCommand(nfcItem, "ON"); } } else { this.openHABWidgetAdapter.sendItemCommand(nfcItem, this.nfcCommand); } } this.nfcWidgetId = null; this.nfcCommand = null; if (this.nfcAutoClose) { getActivity().finish(); } } showPage(displayPageUrl, true); }
From source file:org.openhab.habdroid.ui.OpenHABRoomSettingActivity.java
/** * Parse XML sitemap page and show it//from ww w . j a v a2s. co m * * @param content XML as a text * @return void */ public void processContent(String content) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = factory.newDocumentBuilder(); Document document; // TODO: fix crash with null content document = builder.parse(new ByteArrayInputStream(content.getBytes("UTF-8"))); Node rootNode = document.getFirstChild(); openHABWidgetDataSource.setSourceNode(rootNode); widgetList.clear(); // As we change the page we need to stop all videos on current page // before going to the new page. This is quite dirty, but is the only // way to do that... openHABWidgetAdapter.stopVideoWidgets(); openHABWidgetAdapter.stopImageRefresh(); if (isSitemap()) groupList.clear(); for (OpenHABWidget w : openHABWidgetDataSource.getWidgets()) { widgetList.add(w); if (isSitemap() && w.getType().equals("Group")) groupList.add(w); } openHABWidgetAdapter.notifyDataSetChanged(); setTitle(openHABWidgetDataSource.getTitle()); setProgressBarIndeterminateVisibility(false); getListView().setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.i(TAG, "Widget clicked " + String.valueOf(position)); OpenHABWidget openHABWidget = openHABWidgetAdapter.getItem(position); if (openHABWidget.hasLinkedPage()) { currPID = openHABWidget.getWidgetId(); tvtitle.setText(openHABWidget.getLabel()); pageStack.add(0, new OpenHABPage(displayPageUrl, OpenHABRoomSettingActivity.this.getListView().getFirstVisiblePosition())); displayPageUrl = openHABWidget.getLinkedPage().getLink(); showPage(openHABWidget.getLinkedPage().getLink(), false); } } }); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:betullam.xmlmodifier.XMLmodifier.java
private Set<File> getFilesToModify(String mdDirectory, String fileName, String condStructureType, String condMdName, String condMdValue) { Set<File> setFilesToModify = new HashSet<File>(); // Iterate over all files in the given directory and it's subdirectories. Works with "FileUtils" in Apache "commons-io" library. //for (File mdFile : FileUtils.listFiles(new File(mdDirectory), new WildcardFileFilter(new String[]{"meta.xml", "meta_anchor.xml"}, IOCase.INSENSITIVE), TrueFileFilter.INSTANCE)) { if (fileName.equals("meta") || fileName.equals("meta_anchor")) { for (File mdFile : FileUtils.listFiles(new File(mdDirectory), new WildcardFileFilter(fileName + ".xml", IOCase.INSENSITIVE), TrueFileFilter.INSTANCE)) { // DOM Parser: String filePath = mdFile.getAbsolutePath(); DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = null; Document xmlDoc = null; try { documentBuilder = documentFactory.newDocumentBuilder(); xmlDoc = documentBuilder.parse(filePath); // Only get files that match a certain condition (e. g. "AccessLicense" of a "Monograph" is "OpenAccess"). Only they should be modified. boolean isFileToModify = checkCondition(condStructureType, condMdName, condMdValue, xmlDoc); if (isFileToModify) { setFilesToModify.add(mdFile); }//from ww w . j a va 2 s. c o m } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } } } else { System.err.println("Name of meta files can only be \"meta\" or \"meta_anchor\"."); } return setFilesToModify; }
From source file:betullam.xmlmodifier.XMLmodifier.java
private Set<File> getFilesForInsertion(String condStructureElements, String mdDirectory) { Set<File> filesForInsertion = new HashSet<File>(); List<String> lstStructureElements = Arrays.asList(condStructureElements.split("\\s*,\\s*")); // Iterate over all files in the given directory and it's subdirectories. Works with "FileUtils" in Apache "commons-io" library. //for (File mdFile : FileUtils.listFiles(new File(mdDirectory), new WildcardFileFilter(new String[]{"meta.xml", "meta_anchor.xml"}, IOCase.INSENSITIVE), TrueFileFilter.INSTANCE)) { for (File mdFile : FileUtils.listFiles(new File(mdDirectory), new WildcardFileFilter("*.xml", IOCase.INSENSITIVE), TrueFileFilter.INSTANCE)) { // DOM Parser: String filePath = mdFile.getAbsolutePath(); DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = null; Document xmlDoc = null;/*from w w w .j av a 2 s. c o m*/ try { documentBuilder = documentFactory.newDocumentBuilder(); xmlDoc = documentBuilder.parse(filePath); // Only get files with a structure element that is listed in condStructureElements for (String structureElement : lstStructureElements) { String xPathString = "/mets/structMap[@TYPE='LOGICAL']//div[@TYPE='" + structureElement + "']"; XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPath = xPathFactory.newXPath(); XPathExpression xPathExpr = xPath.compile(xPathString); NodeList nodeList = (NodeList) xPathExpr.evaluate(xmlDoc, XPathConstants.NODESET); if (nodeList.getLength() > 0) { filesForInsertion.add(mdFile); } else { } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } } return filesForInsertion; }
From source file:betullam.xmlmodifier.XMLmodifier.java
public void add(String mdFolder, String condStructureElements, String elementNames, String attrNames, String attrValues, String textValue, boolean allowDuplicate) { // Get the files that should be modified: Set<File> filesForInsertion = getFilesForInsertion(condStructureElements, mdFolder); // Backup XML-files before modifing them: makeBackupFiles(filesForInsertion);// w ww. j a v a2s.c o m // Iterate over all files in given directory and it's subdirectories. Works with Apache commons-io library (FileUtils). for (File xmlFile : filesForInsertion) { // DOM Parser: String filePath = xmlFile.getAbsolutePath(); DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder; Document xmlDoc = null; try { documentBuilder = documentFactory.newDocumentBuilder(); xmlDoc = documentBuilder.parse(filePath); // Get the elements we want to add another element. The name-attribute of the <goobi:metadata ...>-tag is important. List<Element> elementsForInsertion = getElementsForInsertion(condStructureElements, xmlDoc); if (!elementsForInsertion.isEmpty()) { List<String> lstElementNames = Arrays.asList(elementNames.split("\\s*,\\s*")); List<String> lstAttrNames = Arrays.asList(attrNames.split("\\s*,\\s*")); List<String> lstAttrValues = Arrays.asList(attrValues.split("\\s*,\\s*")); if (!lstElementNames.isEmpty()) { int noOfElements = lstElementNames.size(); if ((noOfElements == lstAttrNames.size()) && (noOfElements == lstAttrValues.size())) { Element lastElement = null; Element newElement = null; for (String elementName : lstElementNames) { int index = lstElementNames.indexOf(elementName); newElement = xmlDoc.createElement(elementName); String attrName = lstAttrNames.get(index); String attrValue = lstAttrValues.get(index); // Set attribute name and value: if (!attrName.equals("null") && !attrValue.equals("null")) { if (!attrName.isEmpty() && !attrValue.isEmpty()) { newElement.setAttribute(attrName, attrValue); } } // Set text content to the inner-most element: if ((noOfElements - 1) == index) { newElement.setTextContent(textValue); } // Add element to document: if (newElement != null) { for (Element rootElement : elementsForInsertion) { if (index == 0) { // Append element to root node if (allowDuplicate == false) { // Add only if element with same value does not already exist. if (!hasDuplicate(rootElement, elementName, attrName, attrValue, textValue)) { rootElement.appendChild(newElement); } } else { rootElement.appendChild(newElement); } } else { // Append element to previous element if (allowDuplicate == false) { // Add only if element with same value does not already exist. if (!hasDuplicate(lastElement, elementName, attrName, attrValue, textValue)) { lastElement.appendChild(newElement); } } else { lastElement.appendChild(newElement); } } lastElement = newElement; } } } } else { System.err.println( "The number of attribute names and values must be the same as the number of element names. Use \"null\" for attribute name and values if you don't want to add them."); } } else { System.err.println("You have to supply at least one element name."); } DOMSource source = new DOMSource(xmlDoc); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StreamResult result = new StreamResult(filePath); transformer.transform(source, result); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } } }
From source file:com.esri.geoevent.solutions.adapter.cot.CoTAdapter.java
public CoTAdapter(AdapterDefinition adapterDefinition, String guid) throws ConfigurationException, ComponentException { super(adapterDefinition); this.guid = guid; messageParser = new MessageParser(null); saxFactory = SAXParserFactory.newInstance(); try {/*from ww w . java2s. c o m*/ saxParser = saxFactory.newSAXParser(); } catch (ParserConfigurationException e) { e.printStackTrace(); saxParser = null; } catch (SAXException e) { e.printStackTrace(); saxParser = null; } }