Java Code Examples for org.xml.sax.SAXException

The following are top voted examples for showing how to use org.xml.sax.SAXException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openjdk-jdk10   File: SAX2DTM.java   View source code 6 votes vote down vote up
/**
 * Receive notification of the end of a Namespace mapping.
 *
 * <p>By default, do nothing.  Application writers may override this
 * method in a subclass to take specific actions at the end of
 * each prefix mapping.</p>
 *
 * @param prefix The Namespace prefix being declared.
 * @throws SAXException Any SAX exception, possibly
 *            wrapping another exception.
 * @see ContentHandler#endPrefixMapping
 */
public void endPrefixMapping(String prefix) throws SAXException
{
  if (DEBUG)
    System.out.println("endPrefixMapping: prefix: " + prefix);

  if(null == prefix)
    prefix = "";

  int index = m_contextIndexes.peek() - 1;

  do
  {
    index = m_prefixMappings.indexOf(prefix, ++index);
  } while ( (index >= 0) && ((index & 0x01) == 0x01) );


  if (index > -1)
  {
    m_prefixMappings.setElementAt("%@$#^@#", index);
    m_prefixMappings.setElementAt("%@$#^@#", index + 1);
  }

  // no op
}
 
Example 2
Project: openjdk-jdk10   File: UnmarshallingContext.java   View source code 6 votes vote down vote up
/**
 * Receives the root element and determines how to start
 * unmarshalling.
 */
@Override
public void childElement(UnmarshallingContext.State state, TagName ea) throws SAXException {
    Loader loader = state.getContext().selectRootLoader(state,ea);
    if(loader!=null) {
        state.loader = loader;
        state.receiver = this;
        return;
    }

    // the registry doesn't know about this element.
    // try its xsi:type
    JaxBeanInfo beanInfo = XsiTypeLoader.parseXsiType(state, ea, null);
    if(beanInfo==null) {
        // we don't even know its xsi:type
        reportUnexpectedChildElement(ea,false);
        return;
    }

    state.loader = beanInfo.getLoader(null,false);
    state.prev.backup = new JAXBElement<Object>(ea.createQName(),Object.class,null);
    state.receiver = this;
}
 
Example 3
Project: EVE   File: Weather.java   View source code 6 votes vote down vote up
private void generateWeather(String c) throws IOException, SAXException, TransformerException, ParserConfigurationException {
    city = c;

    // creating the URL
    String url = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&mode=xml&appid=" + APIKey;

    // printing out XML
    URL urlString = new URL(url);
    URLConnection conn = urlString.openConnection();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(conn.getInputStream());

    TransformerFactory transformer = TransformerFactory.newInstance();
    Transformer xform = transformer.newTransformer();

    xform.transform(new DOMSource(doc), new StreamResult(System.out));
}
 
Example 4
Project: Equella   File: AbstractPluginModel.java   View source code 6 votes vote down vote up
private void parse()
{
	try
	{
		InputStream inputStream = getInputStream();
		if( inputStream != null )
		{
			parsedManifest = parser.parseManifest(inputStream);
		}
		else
		{
			parsedManifest = null;
		}
	}
	catch( ParserConfigurationException | SAXException | IOException | CoreException e )
	{
		parsedManifest = null;
	}
}
 
Example 5
Project: incubator-netbeans   File: LogCommand.java   View source code 6 votes vote down vote up
@Override
public void startElement(String uri, String localName, String qName, Attributes elementAttributes) throws SAXException {            
    tag = qName.trim();                
    if (ENTRY_ELEMENT_NAME.equals(qName)) {                        
        values = new HashMap<String, Object>();
        values.put(REVISION_ATTRIBUTE, elementAttributes.getValue(REVISION_ATTRIBUTE));            
    } else if (PATH_ELEMENT_NAME.equals(qName)) {                                
        List<Path> paths = getPathList();
        Path path = new Path();
        path.action = elementAttributes.getValue(ACTION_ATTRIBUTE).charAt(0);
        path.copyPath = elementAttributes.getValue("copyfrom-path");
        path.copyRev = elementAttributes.getValue("copyfrom-rev");
        paths.add(path);                
    } else if(values != null) {
        values.put(tag, "");
    }            
}
 
Example 6
Project: openrouteservice   File: TrafficUtility.java   View source code 6 votes vote down vote up
public static Date getMessageDateTime(String tmcMessage) throws ParserConfigurationException, SAXException,
		IOException, ParseException {
	DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
	InputStream stream = new ByteArrayInputStream(tmcMessage.getBytes(StandardCharsets.UTF_8));
	Document doc = docBuilder.parse(stream);

	doc.getDocumentElement().normalize();
	String timeStamp = doc.getDocumentElement().getAttribute("FGT");

	// FGT="2014-05-01T15:06:00"
	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
	formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
	
	return formatter.parse(timeStamp);
}
 
Example 7
Project: fritz-home-skill   File: SwitchService.java   View source code 6 votes vote down vote up
private String getSessionId() throws IOException, ParserConfigurationException, SAXException, NoSuchAlgorithmException {

    HttpURLConnection con = createConnection(SID_REQUEST_URL);

    handleResponseCode(con.getResponseCode());

    Document doc = xmlFactory.newDocumentBuilder().parse(con.getInputStream());
    logger.trace("response:\n{}", XmlUtils.docToString(doc, true));
    if (doc == null) {
      throw new IOException("SessionInfo element not available");
    }
    String sid = XmlUtils.getValue(doc.getDocumentElement(), "SID");

    if (EMPTY_SID.equals(sid)) {
      String challenge = XmlUtils.getValue(doc.getDocumentElement(), "Challenge");
      sid = getSessionId(challenge);
    }

    if (sid == null || EMPTY_SID.equals(sid)) {
      throw new IOException("sid request failed: " + sid);
    }
    return sid;

  }
 
Example 8
Project: openjdk-jdk10   File: XMLSerializer.java   View source code 6 votes vote down vote up
void reconcileID() throws SAXException {
    // find objects that were not a part of the object graph
    idReferencedObjects.removeAll(objectsWithId);

    for( Object idObj : idReferencedObjects ) {
        try {
            String id = getIdFromObject(idObj);
            reportError( new NotIdentifiableEventImpl(
                ValidationEvent.ERROR,
                Messages.DANGLING_IDREF.format(id),
                new ValidationEventLocatorImpl(idObj) ) );
        } catch (JAXBException e) {
            // this error should have been reported already. just ignore here.
        }
    }

    // clear the garbage
    idReferencedObjects.clear();
    objectsWithId.clear();
}
 
Example 9
Project: openjdk-jdk10   File: NGCCInterleaveFilter.java   View source code 6 votes vote down vote up
/**
 * Joins all the child receivers.
 *
 * <p>
 * This method is called by a child receiver when it sees
 * something that it cannot handle, or by this object itself
 * when it sees an event that it can't process.
 *
 * <p>
 * This method forces children to move to its final state,
 * then revert to the parent.
 *
 * @param source
 *      If this method is called by one of the child receivers,
 *      the receiver object. If this method is called by itself,
 *      null.
 */
public void joinByEnterElement( NGCCEventReceiver source,
    String uri, String local, String qname, Attributes atts ) throws SAXException {

    if(isJoining)   return; // we are already in the process of joining. ignore.
    isJoining = true;

    // send special token to the rest of the branches.
    // these branches don't understand this token, so they will
    // try to move to a final state and send the token back to us,
    // which this object will ignore (because isJoining==true)
    // Otherwise branches will find an error.
    for( int i=0; i<_receivers.length; i++ )
        if( _receivers[i]!=source )
            _receivers[i].enterElement(uri,local,qname,atts);

    // revert to the parent
    _parent._source.replace(this,_parent);
    _parent.onChildCompleted(null,_cookie,true);
    // send this event to the parent
    _parent.enterElement(uri,local,qname,atts);
}
 
Example 10
Project: incubator-netbeans   File: JavaActions.java   View source code 6 votes vote down vote up
/**
 * Implementation of Compile File.
 */
private void handleCompileSingle(Lookup context) throws IOException, SAXException {
    // XXX could also try copy + mod from build.xml? but less likely to have <compile> in an accessible place...
    if (!alert(NbBundle.getMessage(JavaActions.class, "ACTION_compile.single"), FILE_SCRIPT_PATH)) {
        return;
    }
    Document doc = readCustomScript(FILE_SCRIPT_PATH);
    ensurePropertiesCopied(doc.getDocumentElement());
    Comment comm = doc.createComment(" " + NbBundle.getMessage(JavaActions.class, "COMMENT_edit_target") + " ");
    doc.getDocumentElement().appendChild(comm);
    comm = doc.createComment(" " + NbBundle.getMessage(JavaActions.class, "COMMENT_more_info_x.single") + " ");
    doc.getDocumentElement().appendChild(comm);
    String propertyName = "files"; // NOI18N
    AntLocation root = findPackageRoot(context);
    assert root != null : context;
    Element target = createCompileSingleTarget(doc, context, propertyName, root);
    doc.getDocumentElement().appendChild(target);
    writeCustomScript(doc, FILE_SCRIPT_PATH);
    // XXX #53622: support also folders (i.e. just files w/o ext??):
    String targetName = target.getAttribute("name");
    addBinding(ActionProvider.COMMAND_COMPILE_SINGLE, FILE_SCRIPT_PATH, targetName, propertyName, root.virtual, JAVA_FILE_PATTERN, "relative-path", ","); // NOI18N
    jumpToBinding(ActionProvider.COMMAND_COMPILE_SINGLE);
    jumpToBuildScript(FILE_SCRIPT_PATH, targetName);
}
 
Example 11
Project: openjdk-jdk10   File: ersSet.java   View source code 6 votes vote down vote up
public void text(String $value) throws SAXException {
    int $ai;
    switch($_ngcc_current_state) {
    case 0:
        {
            revertToParentFromText(makeResult(), super._cookie, $value);
        }
        break;
    case 1:
        {
            v = $value;
            $_ngcc_current_state = 0;
        }
        break;
    }
}
 
Example 12
Project: openjdk-jdk10   File: DTDParser.java   View source code 6 votes vote down vote up
private String maybeReadAttribute(String name, boolean must)
        throws IOException, SAXException {

    // [24] VersionInfo ::= S 'version' Eq \'|\" versionNum \'|\"
    // [80] EncodingDecl ::= S 'encoding' Eq \'|\" EncName \'|\"
    // [32] SDDecl ::=  S 'standalone' Eq \'|\" ... \'|\"
    if (!maybeWhitespace()) {
        if (!must) {
            return null;
        }
        fatal("P-024", new Object[]{name});
        // NOTREACHED
    }

    if (!peek(name)) {
        if (must) {
            fatal("P-024", new Object[]{name});
        } else {
            // To ensure that the whitespace is there so that when we
            // check for the next attribute we assure that the
            // whitespace still exists.
            ungetc();
            return null;
        }
    }

    // [25] Eq ::= S? '=' S?
    maybeWhitespace();
    nextChar('=', "F-023", null);
    maybeWhitespace();

    return getQuotedString("F-035", name);
}
 
Example 13
Project: DocIT   File: SAXUtilities.java   View source code 6 votes vote down vote up
public static void parse(DefaultHandler handler, String file) throws SAXException, IOException {
	XMLReader xreader = XMLReaderFactory.createXMLReader();
	xreader.setContentHandler(handler);
	xreader.setErrorHandler(handler);
	FileReader reader = new FileReader(file);
    xreader.parse(new InputSource(reader));			
}
 
Example 14
Project: openjdk-jdk10   File: Bug6975265Test.java   View source code 6 votes vote down vote up
@Test
public void test() {
    try {
        File dir = new File(Bug6975265Test.class.getResource("Bug6975265").getPath());
        File files[] = dir.listFiles();
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        for (int i = 0; i < files.length; i++) {
            try {
                System.out.println(files[i].getName());
                Schema schema = schemaFactory.newSchema(new StreamSource(files[i]));
                Assert.fail("should report error");
            } catch (org.xml.sax.SAXParseException spe) {
                System.out.println(spe.getMessage());
                continue;
            }
        }
    } catch (SAXException e) {
        e.printStackTrace();

    }
}
 
Example 15
Project: defense-solutions-proofs-of-concept   File: CoTUtilities.java   View source code 6 votes vote down vote up
public static ArrayList<CoTTypeDef> getCoTTypeMap(InputStream mapInputStream) throws ParserConfigurationException, SAXException, IOException
{

	ArrayList<CoTTypeDef> types = null;

	String content = getStringFromFile(mapInputStream);


	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	DocumentBuilder db = dbf.newDocumentBuilder();
	InputSource source = new InputSource();
	source.setCharacterStream(new StringReader(content));
	Document doc = db.parse(source);
	NodeList nodeList = doc.getElementsByTagName("types");
	types = typeBreakdown(nodeList.item(0));
	return types;
}
 
Example 16
Project: winter   File: SortedNeighbourhoodBlockerTest.java   View source code 6 votes vote down vote up
public void testGeneratePairs() throws XPathExpressionException,
		ParserConfigurationException, SAXException, IOException {
	DataSet<Movie, Attribute> ds = generateDS1();

	DataSet<Movie, Attribute> ds2 = generateDS2();

	SortedNeighbourhoodBlocker<Movie, Attribute, Attribute> blocker = new SortedNeighbourhoodBlocker<>(
			new MovieBlockingKeyByYearGenerator(), 3);

	MatchingGoldStandard gs = new MatchingGoldStandard();
	gs.loadFromCSVFile(new File(
			"usecase/movie/goldstandard/gs_academy_awards_2_actors.csv"));
	
	Processable<Correspondence<Movie, Attribute>> pairs = blocker.runBlocking(ds, ds2, null);

	System.out.println("Pairs: " + pairs.size());
	System.out.println("Reduction Rate: " + blocker.getReductionRatio());

	for (Correspondence<Movie, Attribute> p : pairs.get()) {
		System.out.println(p.getFirstRecord().getIdentifier() + " | "
				+ p.getSecondRecord().getIdentifier());
	}
	assertEquals(4, pairs.size());
}
 
Example 17
Project: gate-core   File: CreoleXmlUpperCaseFilter.java   View source code 6 votes vote down vote up
/**
 * Process the start of an element. If the element is a standard
 * creole.xml element then it and all its attributes have their names
 * converted to upper case. Other elements are passed through
 * untouched.
 */
@Override
public void startElement(String uri, String localName, String name,
        Attributes atts) throws SAXException {
  String upperCaseName = localName.toUpperCase();
  if(knownElements.contains(upperCaseName)) {
    AttributesImpl newAtts = new AttributesImpl();
    for(int i = 0; i < atts.getLength(); i++) {
      String upperCaseAttrName = atts.getLocalName(i).toUpperCase();
      String attrQName = atts.getQName(i);
      newAtts.addAttribute(atts.getURI(i), upperCaseAttrName, attrQName
              .substring(0, attrQName.indexOf(':') + 1)
              + upperCaseAttrName, atts.getType(i), atts.getValue(i));
    }
    super.startElement(uri, upperCaseName, name.substring(0, name
            .indexOf(':') + 1)
            + upperCaseName, newAtts);
  }
  else {
    super.startElement(uri, localName, name, atts);
  }
}
 
Example 18
Project: Tarski   File: mxGraphViewReader.java   View source code 6 votes vote down vote up
public void startElement(String uri, String localName, String qName, Attributes atts)
    throws SAXException {
  String tagName = qName.toUpperCase();
  Map<String, Object> attrs = new Hashtable<String, Object>();

  for (int i = 0; i < atts.getLength(); i++) {
    String name = atts.getQName(i);

    // Workaround for possible null name
    if (name == null || name.length() == 0) {
      name = atts.getLocalName(i);
    }

    attrs.put(name, atts.getValue(i));
  }

  parseElement(tagName, attrs);
}
 
Example 19
Project: openjdk-jdk10   File: ersSet.java   View source code 6 votes vote down vote up
public void leaveAttribute(String $__uri, String $__local, String $__qname) throws SAXException {
    int $ai;
    $uri = $__uri;
    $localName = $__local;
    $qname = $__qname;
    switch($_ngcc_current_state) {
    case 0:
        {
            revertToParentFromLeaveAttribute(makeResult(), super._cookie, $__uri, $__local, $__qname);
        }
        break;
    default:
        {
            unexpectedLeaveAttribute($__qname);
        }
        break;
    }
}
 
Example 20
Project: OpenJSharp   File: SAX2StAXWriter.java   View source code 5 votes vote down vote up
public void processingInstruction(String target, String data)
    throws SAXException
{
    try {
        _writer.writeProcessingInstruction(target, data);
    }
    catch (XMLStreamException e) {
        throw new SAXException(e);
    }
}
 
Example 21
Project: openjdk-jdk10   File: SAXDocumentSerializer.java   View source code 5 votes vote down vote up
public final void startDTD(String name, String publicId, String systemId) throws SAXException {
    if (getIgnoreDTD()) return;

    try {
        encodeTermination();

        encodeDocumentTypeDeclaration(publicId, systemId);
        encodeElementTermination();
    } catch (IOException e) {
        throw new SAXException("startDTD", e);
    }
}
 
Example 22
Project: satisfy   File: RestXMLOnlySteps.java   View source code 5 votes vote down vote up
@Then("get value from REST-XML response by '$xpath' and save to '$variable'")
public void getXPathFromLastRESTResponse(String xPath, String variable) throws IOException, SOAPException, ParserConfigurationException, SAXException, XPathExpressionException {
    Response response = getVariableValue(KEY);
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource source = new InputSource();
    source.setCharacterStream(new StringReader(response.getBody().asString()));
    Document doc = db.parse(source);
    XPath xpath = XPathFactory.newInstance().newXPath();
    Node node = (Node) xpath.evaluate(xPath, doc.getDocumentElement(), XPathConstants.NODE);
    assertNotNull("No element by Xpath: " + xPath + " was found", node);
    save(variable, node.getTextContent());
}
 
Example 23
Project: OpenJSharp   File: AbstractExtensionBindingChecker.java   View source code 5 votes vote down vote up
/**
 * Verify that the given URI is indeed a valid extension namespace URI,
 * and if so enable it.
 * <p>
 * This method does all the error handling.
 */
protected final void checkAndEnable(String uri) throws SAXException {
    if( !isRecognizableExtension(uri) ) {
        String nearest = EditDistance.findNearest(uri, recognizableExtensions);
        // not the namespace URI we know of
        error( Messages.ERR_UNSUPPORTED_EXTENSION.format(uri,nearest) );
    } else
    if( !isSupportedExtension(uri) ) {
        // recognizable but not not supported, meaning
        // the plug-in isn't enabled

        // look for plug-in that handles this URI
        Plugin owner = null;
        for( Plugin p : options.getAllPlugins() ) {
            if(p.getCustomizationURIs().contains(uri)) {
                owner = p;
                break;
            }
        }
        if(owner!=null)
            // we know the plug-in that supports this namespace, but it's not enabled
            error( Messages.ERR_PLUGIN_NOT_ENABLED.format(owner.getOptionName(),uri));
        else {
            // this shouldn't happen, but be defensive...
            error( Messages.ERR_UNSUPPORTED_EXTENSION.format(uri) );
        }
    }

    // as an error recovery enable this namespace URI anyway.
    enabledExtensions.add(uri);
}
 
Example 24
Project: OpenJSharp   File: SAXCatalogReader.java   View source code 5 votes vote down vote up
/** The SAX <code>processingInstruction</code> method. Does nothing. */
public void processingInstruction (String target, String data)
  throws SAXException {
  if (saxParser != null) {
    saxParser.processingInstruction(target, data);
  }
}
 
Example 25
Project: openjdk-jdk10   File: XMLStreamWriterOutput.java   View source code 5 votes vote down vote up
@Override
public void endDocument(boolean fragment) throws IOException, SAXException, XMLStreamException {
    if(!fragment) {
        out.writeEndDocument();
        out.flush();
    }
    super.endDocument(fragment);
}
 
Example 26
Project: OpenJSharp   File: LeafBeanInfoImpl.java   View source code 5 votes vote down vote up
public final void serializeBody(BeanT bean, XMLSerializer w) throws SAXException, IOException, XMLStreamException {
    // most of the times leaves are printed as leaf element/attribute property,
    // so this code is only used for example when you have multiple XmlElement on a property
    // and some of them are leaves. Hence this doesn't need to be super-fast.
    try {
        xducer.writeText(w,bean,null);
    } catch (AccessorException e) {
        w.reportError(null,e);
    }
}
 
Example 27
Project: parabuild-ci   File: FormatCallout.java   View source code 5 votes vote down vote up
public void endSpan(DOMBuilder rtf) 
  throws SAXException {
  // no point in doing this for FO, right?
  if (!stylesheetFO) {
    rtf.endElement("", "span", "span");
  }
}
 
Example 28
Project: OpenJSharp   File: SchemaBuilderImpl.java   View source code 5 votes vote down vote up
private void error(SAXParseException message) throws BuildException {
    noteError();
    try {
        if (eh != null) {
            eh.error(message);
        }
    } catch (SAXException e) {
        throw new BuildException(e);
    }
}
 
Example 29
Project: rapidminer   File: Plugin.java   View source code 5 votes vote down vote up
/**
 * Checks, if a XML file with information about the settings of a plugin is provided. If such a
 * XML file is found, it is parsed and the settings items are added to the {@link SettingsItems}
 * container. The settings can be displayed and changed via the 'RapidMiner Studio Preferences'
 * dialog.
 */
private void loadSettingsStructure() {
	// XML file has to be provided by extension
	if (getPluginSettingsStructure() != null) {

		// Locate XML resource
		URL settingsXML = getClassLoader().getResource(getPluginSettingsStructure());

		// XML file has to be found
		if (settingsXML != null) {
			try {
				// Parse XML
				Map<String, SettingsItem> map = new SettingsXmlHandler().parse(settingsXML.toURI());

				// Add to settings items
				SettingsItems settingsItems = SettingsItems.INSTANCE;
				Iterator<Entry<String, SettingsItem>> iterator = map.entrySet().iterator();
				while (iterator.hasNext()) {
					Entry<String, SettingsItem> entry = iterator.next();
					if (!settingsItems.containsKey(entry.getKey())) {
						settingsItems.put(entry.getKey(), entry.getValue());
					}
				}
			} catch (ParserConfigurationException | SAXException | IOException | URISyntaxException e) {
				LogService.getRoot().log(Level.WARNING, "Could not parse XML settings file: "
						+ SettingsXmlHandler.SETTINGS_XML_FILE + " of extension " + getName() + " " + getVersion());
				// Must not throw an exception, as the settings work without the structure
				// inside XML.
			}
		}

	}

}
 
Example 30
Project: openjdk-jdk10   File: ArrayBeanInfoImpl.java   View source code 5 votes vote down vote up
@Override
public void childElement(UnmarshallingContext.State state, TagName ea) throws SAXException {
    if(ea.matches("","item")) {
        state.setLoader(itemLoader);
        state.setReceiver(this);
    } else {
        super.childElement(state,ea);
    }
}
 
Example 31
Project: LibScout   File: LibraryProfiler.java   View source code 5 votes vote down vote up
public LibraryProfiler(File libraryFile, File libDescriptionFile) throws ParserConfigurationException, SAXException, IOException, ParseException {
	this.libraryFile = libraryFile;
	
	// read library description
	libDesc = XMLParser.readLibraryXML(libDescriptionFile);
	
	// set identifier for logging
	String logIdentifier = CliOptions.logDir.getAbsolutePath() + File.separator;
	logIdentifier += libDesc.name.replaceAll(" ", "-") + "_" + libDesc.version;
	
	MDC.put("appPath", logIdentifier);
}
 
Example 32
Project: apache-tomcat-7.0.73-with-comment   File: Digester.java   View source code 5 votes vote down vote up
/**
 * Forward notification of a fatal parsing error to the application
 * supplied error handler (if any).
 *
 * @param exception The fatal error information
 *
 * @exception SAXException if a parsing exception occurs
 */
@Override
public void fatalError(SAXParseException exception) throws SAXException {

    log.error("Parse Fatal Error at line " + exception.getLineNumber() +
            " column " + exception.getColumnNumber() + ": " +
            exception.getMessage(), exception);
    if (errorHandler != null) {
        errorHandler.fatalError(exception);
    }

}
 
Example 33
Project: hadoop   File: Configuration.java   View source code 5 votes vote down vote up
private Document parse(DocumentBuilder builder, InputStream is,
    String systemId) throws IOException, SAXException {
  if (!quietmode) {
    LOG.debug("parsing input stream " + is);
  }
  if (is == null) {
    return null;
  }
  try {
    return (systemId == null) ? builder.parse(is) : builder.parse(is,
        systemId);
  } finally {
    is.close();
  }
}
 
Example 34
Project: OpenJSharp   File: RuntimeBuiltinLeafInfoImpl.java   View source code 5 votes vote down vote up
public URI parse(CharSequence text) throws SAXException {
    try {
        return new URI(text.toString());
    } catch (URISyntaxException e) {
        UnmarshallingContext.getInstance().handleError(e);
        return null;
    }
}
 
Example 35
Project: Java-APIs   File: XMLReader.java   View source code 5 votes vote down vote up
protected Element getRootElement(byte[] data) throws ParserConfigurationException, SAXException, IOException {
	DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
	documentBuilderFactory.setValidating(false);
	
	DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
	documentBuilder = documentBuilderFactory.newDocumentBuilder();
	InputStream inputStream = new ByteArrayInputStream(data);
	InputSource inputSource = new InputSource(inputStream);
	Document document = documentBuilder.parse(inputSource);

	Element element = document.getDocumentElement();
	return element;
}
 
Example 36
Project: openjdk-jdk10   File: TextSerializer.java   View source code 5 votes vote down vote up
public void startElement( String tagName, AttributeList attrs )
    throws SAXException
{
    boolean      preserveSpace;
    ElementState state;

    try {
        state = getElementState();
        if ( isDocumentState() ) {
            // If this is the root element handle it differently.
            // If the first root element in the document, serialize
            // the document's DOCTYPE. Space preserving defaults
            // to that of the output format.
            if ( ! _started )
                startDocument( tagName );
        }
        // For any other element, if first in parent, then
        // use the parnet's space preserving.
        preserveSpace = state.preserveSpace;

        // Do not change the current element state yet.
        // This only happens in endElement().

        // Ignore all other attributes of the element, only printing
        // its contents.

        // Now it's time to enter a new element state
        // with the tag name and space preserving.
        // We still do not change the curent element state.
        state = enterElementState( null, null, tagName, preserveSpace );
    } catch ( IOException except ) {
        throw new SAXException( except );
    }
}
 
Example 37
Project: verify-hub   File: MatchingServiceHealthChecker.java   View source code 5 votes vote down vote up
private Optional<String> extractVersionFromResponseId(String response) throws IOException, SAXException, ParserConfigurationException {
    final Response attributeQueryResponse = elementToResponseTransformer.apply(XmlUtils.convertToElement(response));
    final String responseId = attributeQueryResponse.getID();
    final String key = "version-";
    if(responseId.contains(key)) {
        return Optional.fromNullable(responseId.trim().substring(responseId.indexOf(key) + key.length()));
    }
    return Optional.absent();
}
 
Example 38
Project: jaffa-framework   File: SoaEventManager.java   View source code 5 votes vote down vote up
/**
    * {@inheritDoc}
    */
@Override
public void registerResource(Resource resource, String context, String variation) throws JAXBException, SAXException, IOException {
	SoaEvents soaEvents = JAXBHelper.unmarshalConfigFile(SoaEvents.class, resource, CONFIGURATION_SCHEMA_FILE);

	if (soaEvents != null) {
		for (SoaEventInfo soaEventInfo : soaEvents.getSoaEvent()) {
		    ContextKey contextKey = new ContextKey(soaEventInfo.getName(), resource.getURI().toString(), variation, context);
			registerSoaEventInfo(contextKey, soaEventInfo);
		}
	}
}
 
Example 39
Project: gradle-dependency-metadata-plugin   File: XMLNamespaceFilter.java   View source code 5 votes vote down vote up
@Override
public void startElement(String uri, String localName,
                         String qName, Attributes attributes)
        throws SAXException {
    super.startElement("", localName, qName,
            attributes);
}
 
Example 40
Project: openjdk-jdk10   File: CatalogTest.java   View source code 5 votes vote down vote up
SAXParser getParser() {
    SAXParser saxParser = null;
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        saxParser = factory.newSAXParser();
    } catch (ParserConfigurationException | SAXException e) {
    }

    return saxParser;
}