List of usage examples for javax.xml.parsers ParserConfigurationException getLocalizedMessage
public String getLocalizedMessage()
From source file:Main.java
public static boolean creteEntity(Object entity, String fileName) { boolean flag = false; try {/*from ww w . ja va2 s.com*/ DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(fileName); Class clazz = entity.getClass(); Field[] fields = clazz.getDeclaredFields(); Node EntityElement = document.getElementsByTagName(clazz.getSimpleName() + "s").item(0); Element newEntity = document.createElement(clazz.getSimpleName()); EntityElement.appendChild(newEntity); for (Field field : fields) { field.setAccessible(true); Element element = document.createElement(field.getName()); element.appendChild(document.createTextNode(field.get(entity).toString())); newEntity.appendChild(element); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource domSource = new DOMSource(document); StreamResult streamResult = new StreamResult(new File(fileName)); transformer.transform(domSource, streamResult); flag = true; } catch (ParserConfigurationException pce) { System.out.println(pce.getLocalizedMessage()); pce.printStackTrace(); } catch (TransformerException te) { System.out.println(te.getLocalizedMessage()); te.printStackTrace(); } catch (IOException ioe) { System.out.println(ioe.getLocalizedMessage()); ioe.printStackTrace(); } catch (SAXException sae) { System.out.println(sae.getLocalizedMessage()); sae.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return flag; }
From source file:com.pentaho.repository.importexport.PDIImportUtil.java
/** * @return instance of {@link Document}, if xml is loaded successfully null in case any error occurred during loading *///from ww w . j av a2s .c om public static Document loadXMLFrom(InputStream is) { DocumentBuilderFactory factory; try { factory = XMLParserFactoryProducer.createSecureDocBuilderFactory(); } catch (ParserConfigurationException e) { log.logError(e.getLocalizedMessage()); factory = DocumentBuilderFactory.newInstance(); } DocumentBuilder builder = null; Document doc = null; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException ex) { // ignore } try { File file = File.createTempFile("tempFile", "temp"); file.deleteOnExit(); FileOutputStream fous = new FileOutputStream(file); IOUtils.copy(is, fous); fous.flush(); fous.close(); doc = builder.parse(file); } catch (IOException | SAXException e) { log.logError(e.getLocalizedMessage()); } finally { try { is.close(); } catch (IOException e) { // nothing to do here } } return doc; }
From source file:com.grameenfoundation.ictc.controllers.SaleforceIntegrationController.java
public static Document parseXmlText(InputSource input_data) { //get the factory DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try {/*from ww w . ja va 2 s . c om*/ //Using factory get an instance of document builder DocumentBuilder db = dbf.newDocumentBuilder(); //InputSource is = new InputSource(); //is.setCharacterStream(new StringReader(data)); //parse using builder to get DOM representation of the data Document doc = db.parse(input_data); // normalize text representation doc.getDocumentElement().normalize(); System.out.println("Root element of the doc is " + doc.getDocumentElement().getNodeName()); return doc; } catch (ParserConfigurationException pce) { System.out.println("Exception is " + pce.getLocalizedMessage()); pce.printStackTrace(); return null; } catch (SAXException se) { System.out.println("Exception is " + se.getLocalizedMessage()); System.out.println("line " + se.getMessage()); se.printStackTrace(); return null; } catch (IOException ioe) { System.out.println("Exception is " + ioe.getLocalizedMessage()); ioe.printStackTrace(); return null; } catch (Exception ex) { System.out.println("Exception is " + ex.getLocalizedMessage()); // ioe.printStackTrace(); return null; } }
From source file:com.wooki.services.ImportServiceImpl.java
public Book importDocbook(InputStream generatedXhtml) { HTMLParser handler = new HTMLParser(); SAXParserFactory factory = SAXParserFactory.newInstance(); // cration d'un parseur SAX SAXParser parser;/*w ww . ja v a 2 s .c o m*/ try { parser = factory.newSAXParser(); parser.parse(new InputSource(generatedXhtml), handler); } catch (ParserConfigurationException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); return null; } catch (SAXException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); return null; } catch (IOException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); return null; } Book book = handler.getBook(); Book toReturn = getBookManager().create(book.getTitle()); return toReturn; }
From source file:net.sf.jabref.importer.fileformat.BibTeXMLImporter.java
@Override public ParserResult importDatabase(BufferedReader reader) throws IOException { Objects.requireNonNull(reader); List<BibEntry> bibItems = new ArrayList<>(); // Obtain a factory object for creating SAX parsers SAXParserFactory parserFactory = SAXParserFactory.newInstance(); // Configure the factory object to specify attributes of the parsers it // creates/*from w w w. j a v a 2 s . co m*/ // parserFactory.setValidating(true); parserFactory.setNamespaceAware(true); // Now create a SAXParser object try { SAXParser parser = parserFactory.newSAXParser(); //May throw exceptions BibTeXMLHandler handler = new BibTeXMLHandler(); // Start the parser. It reads the file and calls methods of the handler. parser.parse(new InputSource(reader), handler); // When you're done, report the results stored by your handler object bibItems.addAll(handler.getItems()); } catch (javax.xml.parsers.ParserConfigurationException e) { LOGGER.error("Error with XML parser configuration", e); return ParserResult.fromErrorMessage(e.getLocalizedMessage()); } catch (org.xml.sax.SAXException e) { LOGGER.error("Error during XML parsing", e); return ParserResult.fromErrorMessage(e.getLocalizedMessage()); } catch (IOException e) { LOGGER.error("Error during file import", e); return ParserResult.fromErrorMessage(e.getLocalizedMessage()); } return new ParserResult(bibItems); }
From source file:de.crowdcode.movmvn.plugin.general.GeneralPlugin.java
private void createPomFile() { context.logInfo("Create POM file..."); try {// ww w. jav a 2 s. c om String projectWorkDir = context.getProjectTargetName(); Document doc = createDocument(); // Root project Element rootElement = createPomRootAndTitle(doc); createPomProperties(doc, rootElement); createPomDependencies(doc, rootElement); createPomBuild(doc, rootElement); // Write the content into xml file writeToFile(projectWorkDir, doc); context.logInfo("POM file saved!"); } catch (ParserConfigurationException e) { log.log(Level.SEVERE, e.getLocalizedMessage(), e); } catch (TransformerException e) { log.log(Level.SEVERE, e.getLocalizedMessage(), e); } }
From source file:com.freedomotic.plugins.devices.ethrly.DevantechEthRly.java
private Document getXMLStatusFile(Board board) { //get the xml file from the socket connection DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = null; try {/*from w w w.j a va 2 s . c o m*/ dBuilder = dbFactory.newDocumentBuilder(); } catch (ParserConfigurationException ex) { LOG.error(ex.getLocalizedMessage()); } Document doc = null; URL url = null; try { String authString = board.getUsername() + ":" + board.getPassword(); byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); //Create a URL for the desired page url = new URL("http://" + board.getIpAddress() + ":" + Integer.toString(board.getPort()) + "/" + GET_STATUS_URL); URLConnection urlConnection = url.openConnection(); // if required set the authentication if (board.getHttpAuthentication().equalsIgnoreCase("true")) { urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc); } LOG.info("Devantech Eth-Rly gets relay status from file {}", url); doc = dBuilder.parse(urlConnection.getInputStream()); doc.getDocumentElement().normalize(); } catch (ConnectException connEx) { disconnect(); this.stop(); this.setDescription("Connection timed out, no reply from the board at " + url); } catch (SAXException ex) { disconnect(); this.stop(); LOG.error(Freedomotic.getStackTraceInfo(ex)); } catch (Exception ex) { disconnect(); this.stop(); setDescription("Unable to connect to " + url); LOG.error(Freedomotic.getStackTraceInfo(ex)); } return doc; }
From source file:it.ciroppina.idol.generic.tunnel.IdolOEMTunnel.java
private Document getDocumentFrom(String xml) { DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; Document document = null;/*from w w w.java2s.c o m*/ try { InputStream is = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); builder = documentFactory.newDocumentBuilder(); document = builder.parse(is); } catch (ParserConfigurationException e) { System.out.println(e.getLocalizedMessage()); } catch (SAXException e) { System.out.println(e.getLocalizedMessage()); } catch (IOException e) { System.out.println(e.getLocalizedMessage()); } return document; }
From source file:edu.wpi.margrave.MCommunicator.java
public static void handleXMLCommand(InputStream commandStream) { DocumentBuilder docBuilder = null; DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); try {// w ww. j ava2 s . co m docBuilder = docFactory.newDocumentBuilder(); } catch (ParserConfigurationException ex) { Logger.getLogger(MCommunicator.class.getName()).log(Level.SEVERE, null, ex); writeToLog( "\nParserConfigurationException at beginning of handleXMLCommand: " + ex.getLocalizedMessage()); writeToLog("\nTerminating engine..."); System.exit(200); } // Save this command for use in exception messages //MEnvironment.lastCommandReceived = command.trim(); Document inputXMLDoc = null; try { // doc = docBuilder.parse(new InputSource(new StringReader(command))); writeToLog("========================================\n========================================\n"); writeToLog("\n" + commandStream.available()); StringBuffer inputStringBuffer = new StringBuffer(); while (true) { // if available=0; we want to block. But don't want to allocate too much room: if (commandStream.available() < 1) { int b = commandStream.read(); inputStringBuffer.append((char) b); //writeToLog("\n(Blocked and then got) character: `"+(char)b+"`"); } else { byte[] inputBytes = new byte[commandStream.available()]; @SuppressWarnings("unused") int bytesRead = commandStream.read(inputBytes); String block = new String(inputBytes); inputStringBuffer.append(block); //writeToLog("\n(Didn't block for) String: `"+block+"`"); } // Bad kludge. Couldn't get proper XML parse function working, so // did this. Should re-write (preferably with correct XML handling functions!) // The trim() call below is especially egregious... - TN String sMargraveCommandEnding = "</MARGRAVE-COMMAND>"; String bufferStr = inputStringBuffer.toString(); if (bufferStr.trim().endsWith(sMargraveCommandEnding)) break; } // end while(true) for kludge String cmdString = inputStringBuffer.toString(); writeToLog("\n\n*********************************\nDONE! Received command: `" + cmdString + "`\n"); inputXMLDoc = docBuilder.parse(new InputSource(new StringReader(cmdString))); //doc = docBuilder.parse(commandStream); //doc = docBuilder.parse(new InputSource(commandStream)); writeToLog((new Date()).toString()); writeToLog("\nExecuting command: " + transformXMLToString(inputXMLDoc) + "\n"); } // end try catch (SAXException ex) { Logger.getLogger(MCommunicator.class.getName()).log(Level.SEVERE, null, ex); writeToLog( "\nSAXException in handleXMLCommand while parsing command stream: " + ex.getLocalizedMessage()); } catch (IOException ex) { Logger.getLogger(MCommunicator.class.getName()).log(Level.SEVERE, null, ex); writeToLog( "\nIOException in handleXMLCommand while parsing command stream: " + ex.getLocalizedMessage()); } ///////////////////////////////////////////////////// // Done parsing input. Now prepare the response. Document theResponse; try { // protect against getFirstChild() call if (inputXMLDoc != null) theResponse = xmlHelper(inputXMLDoc.getFirstChild(), ""); else theResponse = MEnvironment.errorResponse(MEnvironment.sNotDocument, MEnvironment.sCommand, ""); } catch (Exception e) { // Construct an exception response; theResponse = MEnvironment.exceptionResponse(e); } catch (Throwable e) { // This would ordinarily be a terrible thing to do (catching Throwable) // However, we need to warn the client that we're stuck. try { // First log that we got an exception: writeToLog("\n~~~ Throwable caught: " + e.getClass()); writeToLog("\n " + e.getLocalizedMessage()); writeToLog("\n" + Arrays.toString(e.getStackTrace())); writeToLog("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); theResponse = MEnvironment.exceptionResponse(e); } catch (Throwable f) { // If we can't even warn the client, at least close down the engine. Client will detect EOF. theResponse = null; System.exit(101); } // Last resort System.exit(100); } try { addBuffers(theResponse); writeToLog("Returning: " + transformXMLToString(theResponse) + "\n"); out.write(transformXMLToByteArray(theResponse)); } catch (IOException e) { // don't do this. would go through System.err //e.printStackTrace(); } out.flush(); // ALWAYS FLUSH! }
From source file:edu.virginia.speclab.juxta.author.model.JuxtaXMLParser.java
public void parse() throws ReportedException { firstPassReadFile();/*from w w w.ja va2 s . c o m*/ offsetMap = new OffsetMap(rawXMLText.length()); // Setup special tag handling to cover behavior for // add, del, note and pb tags setupCustomTagHandling(); try { if (file.getName().endsWith("xml")) { SAXParserFactory factory = SAXParserFactory.newInstance(); parser = factory.newSAXParser(); XMLReader xmlReader = parser.getXMLReader(); xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", this); // ignore external DTDs xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); parser.parse(new InputSource(new StringReader(rawXMLText)), this); if (getDocumentType() == DocumentType.UNKNOWN) { // If we made it here and we don't know what the document type is, // it's just an XML document setDocumentType(DocumentType.XML); } // Uncomment these lines for some verbose debugging of the XML parsing // and the resulting processed output. // getRootNode().debugPrint(); // try { // printDebuggingInfo(); // } catch (ReportedException ex) { //Logger.getLogger(JuxtaXMLParser.class.getName()).log(Level.SEVERE, null, ex); // } } else { processAsPlaintext(); } } catch (ParserConfigurationException ex) { throw new ReportedException(ex, "Problem with our parser configuration."); } catch (SAXParseException ex) { throw new ReportedException(ex, "XML Parsing Error at column " + ex.getColumnNumber() + ", line " + ex.getLineNumber() + " :\n" + ex.getLocalizedMessage()); } catch (SAXException ex) { throw new ReportedException(ex, "SAX Exception: " + ex.getLocalizedMessage()); } catch (IOException ex) { throw new ReportedException(ex, ex.getLocalizedMessage()); } }