/** * Returns an XML Document, parsed strictly if possible, or sloppily. * Exceptions during strict parsing will be ignored. * * This method does NOT strip the XML declaration and add a wrapper * tag with namespaces. That must be done beforehand. * * @see net.vhati.modmanager.core.EmptyAwareSAXHandlerFactory * @see net.vhati.modmanager.core.SloppyXMLParser */ public static Document parseStrictOrSloppyXML(CharSequence srcSeq, String srcDescription) throws IOException, JDOMException { Document doc; try { SAXBuilder strictParser = new SAXBuilder(); strictParser.setSAXHandlerFactory(new EmptyAwareSAXHandlerFactory()); doc = strictParser.build(new StringReader(srcSeq.toString())); } catch (JDOMParseException e) { // Ignore the error, and do a sloppy parse instead. try { SloppyXMLParser sloppyParser = new SloppyXMLParser(); doc = sloppyParser.build(srcSeq); } catch (JDOMParseException f) { throw new JDOMException(String.format("While processing \"%s\", strict parsing failed, then sloppy parsing failed: %s", srcDescription, f.getMessage()), f); } } return doc; }
public void reportGeneralProblem(Exception e) { String message; if (e instanceof IOException || e instanceof JDOMParseException) { message = "There was a problem parsing your input data. \n" + "Perhaps check that the XML is well formed."; } else if (e instanceof YQueryException) { message = e.getMessage(); } else { message = e.getMessage(); } e.printStackTrace(); JOptionPane.showMessageDialog( this, message, "Problem with data input", JOptionPane.ERROR_MESSAGE); }
public static ArrayList<Element> findTagsNamed( String contents, String tagName ) throws JDOMParseException { Document doc = null; doc = IOUtils.parseXML( contents ); ArrayList<Element> tagList = new ArrayList<Element>(); Element root = doc.getRootElement(); if ( root.getName().equals( tagName ) ) { tagList.add( root ); } else { for ( Element e : root.getChildren( tagName ) ) tagList.add( e ); } return tagList; }
public PartialConfig parseFile(File file) { FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); return loader.fromXmlPartial(inputStream, PartialConfig.class); } catch (JDOMParseException jdomex) { throw new RuntimeException("Syntax error in xml file: " + file.getName(), jdomex); } catch (IOException ioex) { throw new RuntimeException("IO error when trying to parse xml file: " + file.getName(), ioex); } catch (Exception ex) { throw new RuntimeException("Failed to parse xml file: " + file.getName(), ex); } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException e) { LOGGER.error("Failed to close file: {}", file, e); } } }
/** * Returns an XML Document, parsed strictly if possible, or sloppily. * Exceptions during strict parsing will be ignored. * * This method does NOT strip the XML declaration and add a wrapper * tag with namespaces. That must be done beforehand. * * @see net.vhati.modmanager.core.EmptyAwareSAXHandlerFactory * @see net.vhati.modmanager.core.SloppyXMLParser */ public static Document parseStrictOrSloppyXML( CharSequence srcSeq, String srcDescription ) throws IOException, JDOMException { Document doc = null; try { SAXBuilder strictParser = new SAXBuilder(); strictParser.setSAXHandlerFactory( new EmptyAwareSAXHandlerFactory() ); doc = strictParser.build( new StringReader( srcSeq.toString() ) ); } catch ( JDOMParseException e ) { // Ignore the error, and do a sloppy parse instead. try { SloppyXMLParser sloppyParser = new SloppyXMLParser(); doc = sloppyParser.build( srcSeq ); } catch ( JDOMParseException f ) { throw new JDOMException( String.format( "While processing \"%s\", strict parsing failed, then sloppy parsing failed: %s", srcDescription, f.getMessage() ), f ); } } return doc; }
@Override public boolean suppressStackTrace() { // Don't dump the stack if the root cause is just a parse error Throwable thrown = getThrown(); while(thrown instanceof InvalidXMLException) thrown = thrown.getCause(); return thrown == null || (thrown instanceof JDOMParseException) || super.suppressStackTrace(); }
private String validateXML(String xml, SAXBuilder builder) throws JDOMException, IOException { Reader in; int i = 0; xml = xml.replaceAll("\\&", "&"); while (i < 5) { in = new StringReader(xml); try { builder.build(in); break; } catch (JDOMParseException e) { String message = e.getMessage(); if (message.matches("^.*.The element type.*.must be terminated by the matching end-tag.*")) { String tag = message.substring(message.lastIndexOf("type") + 6, message.lastIndexOf("must") - 2); xml = xml.replaceAll("(?i)</" + tag + ">" , "</" + tag + ">"); } else { break; } i++; } } return xml; }
/** * Saves the ship within the context of the specified database entry, as the specified file. * * @param destination * the output file. * @param entry * the DatabaseEntry (runtime representation of an .ftl mod) within which the ship is to be saved. * @param container * the ShipContainer to be saved. */ public static void saveShipModFTL( File destination, DatabaseEntry entry, ShipContainer container ) throws IllegalArgumentException, IOException, JDOMParseException { if ( destination == null ) throw new IllegalArgumentException( "Destination file must not be null." ); if ( destination.isDirectory() ) throw new IllegalArgumentException( "Not a file: " + destination.getName() ); HashMap<String, byte[]> entryMap = IOUtils.readEntry( entry ); IOUtils.merge( entryMap, container ); IOUtils.writeZip( entryMap, destination ); }
public static void saveShipModXML( File destination, DatabaseEntry entry, ShipContainer container ) throws IllegalArgumentException, IOException, JDOMParseException { if ( destination == null ) throw new IllegalArgumentException( "Destination file must not be null." ); if ( !destination.isDirectory() ) throw new IllegalArgumentException( "Not a directory: " + destination.getName() ); HashMap<String, byte[]> entryMap = IOUtils.readEntry( entry ); IOUtils.merge( entryMap, container ); IOUtils.writeDir( entryMap, destination ); }
@Test public void shouldNotAllowEmptyAuthInApproval() throws Exception { CruiseConfig cruiseConfig = ConfigMigrator.load(ConfigFileFixture.ONE_PIPELINE); StageConfig stageConfig = com.thoughtworks.go.helper.StageConfigMother.custom("newStage", new AuthConfig()); cruiseConfig.pipelineConfigByName(new CaseInsensitiveString("pipeline1")).add(stageConfig); try { xmlWriter.write(cruiseConfig, output, false); assertThat("Should not allow approval with empty auth", output.toString().contains("<auth"), is(false)); } catch (JDOMParseException expected) { assertThat(expected.getMessage(), containsString("The content of element 'auth' is not complete")); } }
@Test public void shouldThrowExceptionWhenXmlIsMalformed() throws Exception { expectedException.expect(JDOMParseException.class); expectedException.expectMessage(containsString("Error on line 1: XML document structures must start and end within the same entity")); String xmlContent = "<foo name='invalid'"; buildXmlDocument(xmlContent, GoConfigSchema.getCurrentSchema()); }
public static InvalidXMLException fromJDOM(JDOMParseException e, String documentPath) { return new InvalidXMLException(e.getMessage(), null, e.getPartialDocument(), documentPath, e.getLineNumber(), e.getLineNumber(), e.getColumnNumber(), e); }
/** * * @param text text to convert to HTML * @return */ public static List<Element> convertHtmlTextToXhtml(String text) { List<Element> result = null; // if (logger.isTraceEnabled()) // logger.trace("Comment to convert: " + Database.stringToHex(text)); if (Helper.isNotNullOrEmpty(text)) { if (!text.startsWith("<")) { // plain text if (logger.isTraceEnabled())logger.trace("convertHtmlTextToXhtml: plain text"); StringBuffer sb = new StringBuffer(); if (Helper.isNotNullOrEmpty(text)) { List<String> strings = Helper.tokenize(text, "\n", true); for (String string : strings) { if (Helper.isNullOrEmpty(string)) { sb.append("<p />"); } else { sb.append("<p>"); sb.append(string); sb.append("</p>\n"); } } } text = sb.toString(); } // tidy the text if (logger.isTraceEnabled()) logger.trace("convertHtmlTextToXhtml: tidy the text"); try { String noNL = text.replaceAll("\\n",""); result = tidyInputStream(new ByteArrayInputStream(noNL.getBytes("utf-8"))); // result = tidyInputStream(new ByteArrayInputStream(text.getBytes("utf-8"))); String afterTIDY = result.toString(); int dummy = 1; } catch (JDOMParseException j) { if (logger.isDebugEnabled()) logger.trace("convertHtmlTextToXhtml: caught JDOMParseException in the tidy process"); if (logger.isTraceEnabled()) logger.trace( "" + j); tidyForTidyInputStream = null; // Force a new clean object to be gebnerated for next time around } catch (Exception ee) { if (logger.isDebugEnabled()) logger.debug("convertHtmlTextToXhtml: caught exception in the tidy process", ee); tidyForTidyInputStream = null; // Force a new clean object to be gebnerated for next time around } catch (Throwable t) { logger.error("convertHtmlTextToXhtml: caught throwable in the tidy process", t); tidyForTidyInputStream = null; // Force a new clean object to be gebnerated for next time around } if (result != null) { if (logger.isTraceEnabled()) logger.trace("convertHtmlTextToXhtml: returning XHTML"); } else { if (Helper.isNotNullOrEmpty(text)) logger.debug("convertHtmlTextToXhtml: Cannot convert comment text\n" + text); } } return result; }
public static ArrayList<Element> findShipsWithName( File f, String blueprintName ) throws IllegalArgumentException, JDOMParseException, IOException { return findShipsWithName( blueprintName, new FileInputStream( f ), f.getName() ); }
public static ArrayList<Element> findTagsNamed( InputStream is, String fileName, String tagName ) throws IllegalArgumentException, JDOMParseException, IOException { IOUtils.DecodeResult dr = IOUtils.decodeText( is, fileName ); return findTagsNamed( dr.text, tagName ); }
public static ArrayList<Element> findTagsNamed( File f, String tagName ) throws IllegalArgumentException, JDOMParseException, IOException { return findTagsNamed( new FileInputStream( f ), f.getName(), tagName ); }
/** * Merges the file-byte map with the specified ShipContainer, effectively saving * the ship in the file-byte map. */ public static void merge( Map<String, byte[]> base, ShipContainer container ) throws JDOMParseException, IOException { ShipObject ship = container.getShipController().getGameObject(); Map<String, byte[]> fileMap = ShipSaveUtils.saveShip( container ); for ( String file : fileMap.keySet() ) { if ( base.containsKey( file ) ) { // Mod already contains that file; need to consider further if ( file.endsWith( ".png" ) || file.equals( ship.getLayoutTXT() ) || file.equals( ship.getLayoutXML() ) ) { // Overwrite graphics and layout files base.put( file, fileMap.get( file ) ); } else if ( file.endsWith( ".xml" ) || file.endsWith( ".append" ) || file.endsWith( ".rawappend" ) || file.endsWith( ".rawclobber" ) ) { // Merge XML files, while removing obscured elements Document docBase = IOUtils.parseXML( new String( base.get( file ) ) ); Document docAdd = IOUtils.parseXML( new String( fileMap.get( file ) ) ); Element root = docBase.getRootElement(); List<Content> addList = docAdd.getContent(); for ( int i = 0; i < addList.size(); ++i ) { Content c = addList.get( i ); if ( c instanceof Element == false ) continue; Element e = (Element)c; String name = e.getAttributeValue( "name" ); if ( name == null ) { // Can't identify; just add it. e.detach(); root.addContent( e ); } else { // Remove elements that are obscured, in order to prevent bloating List<Element> baseList = root.getChildren( e.getName(), e.getNamespace() ); for ( int j = 0; j < baseList.size(); ++j ) { Element el = baseList.get( j ); String name2 = el.getAttributeValue( "name" ); if ( name2 != null && name2.equals( name ) ) { el.detach(); } } e.detach(); root.addContent( e ); } } base.put( file, readDocument( docBase ).getBytes() ); } } else { // Doesn't exist; add it base.put( file, fileMap.get( file ) ); } } }
private GoConfigService goConfigServiceWithInvalidStatus() throws Exception { goConfigDao = mock(GoConfigDao.class, "badCruiseConfigManager"); when(goConfigDao.checkConfigFileValid()).thenReturn(GoConfigValidity.invalid(new JDOMParseException("JDom exception", new RuntimeException()))); return new GoConfigService(goConfigDao, pipelineRepository, new SystemTimeClock(), mock(GoConfigMigration.class), goCache, null, ConfigElementImplementationRegistryMother.withNoPlugins(), instanceFactory, null, null); }
private void expectDOCTYPEDisallowedException() { expectedException.expect(JDOMParseException.class); expectedException.expectMessage(containsString("DOCTYPE is disallowed when the feature \"http://apache.org/xml/features/disallow-doctype-decl\" set to true")); }
/** * * @param ship * ship object in which the loaded data will be saved * @param f * file from which the data is read * @throws IllegalArgumentException * when the file is wrongly formatted - a tag or an attribute is missing * @throws JDOMParseException * when a parsing error occurs * @throws IOException * when a general IO error occurs */ public static void loadLayoutXML( ShipObject ship, File f ) throws IllegalArgumentException, JDOMParseException, IOException { if ( ship == null ) throw new IllegalArgumentException( "Ship object must not be null." ); if ( f == null ) throw new IllegalArgumentException( "File must not be null." ); loadLayoutXML( ship, new FileInputStream( f ) ); }
/** * Interprets the string as XML. * * @param contents * the string to be interpreted * @return the XML document representing the string * * @throws JDOMParseException * when an exception occurs while parsing XML */ public static Document parseXML( String contents ) throws JDOMParseException { if ( contents == null ) throw new IllegalArgumentException( "Parsed string must not be null." ); SloppyXMLParser parser = new SloppyXMLParser(); return parser.build( contents ); }
/** * Returns the line number of the end of the text where the parse error occurred. * <p> * The first line in the document is line 1. * </p> * * @return an integer representing the line number, or -1 if the information is not available. */ public int getLineNumber() { if (getCause() instanceof JDOMParseException) { return ((JDOMParseException) getCause()).getLineNumber(); } else { return -1; } }
/** * Returns the column number of the end of the text where the parse error occurred. * <p> * The first column in a line is position 1. * </p> * * @return an integer representing the column number, or -1 if the information is not available. */ public int getColumnNumber() { if (getCause() instanceof JDOMParseException) { return ((JDOMParseException) getCause()).getColumnNumber(); } else { return -1; } }
/** * Decodes the contents of the specified file as text, and then interprets the text as XML. * * @param f * the file to be read * @return the XML document representing the contents of the file * * @throws FileNotFoundException * when the file is not found * @throws IOException * when an IO exception occurs while reading the file * @throws JDOMParseException * when an exception occurs while parsing XML */ public static Document readFileXML( File f ) throws FileNotFoundException, IOException, JDOMParseException { String contents = readFileText( f ); return parseXML( contents ); }
/** * Reads the stream supplied in argument, decodes it as text, and interprets it as XML.<br> * This method fully reads the stream, and as such after this method has been invoked, * the stream will have reached EOF.<br> * <b>This method does not close the stream.</b> * * @param is * The stream to be read. * @param label * How error messages should refer to the stream, or null. */ public static Document readStreamXML( InputStream is, String label ) throws IOException, JDOMParseException { String contents = readStreamText( is, label ); return parseXML( contents ); }
/** * Returns the line number of the end of the text where the * parse error occurred. * <p> * The first line in the document is line 1.</p> * * @return an integer representing the line number, or -1 * if the information is not available. */ public int getLineNumber() { return (getCause() instanceof JDOMParseException)? ((JDOMParseException)getCause()).getLineNumber(): -1; }
/** * Returns the column number of the end of the text where the * parse error occurred. * <p> * The first column in a line is position 1.</p> * * @return an integer representing the column number, or -1 * if the information is not available. */ public int getColumnNumber() { return (getCause() instanceof JDOMParseException)? ((JDOMParseException)getCause()).getColumnNumber(): -1; }