List of usage examples for org.xml.sax InputSource getSystemId
public String getSystemId()
From source file:bpelg.packaging.ode.util.BgSchemaCollection.java
public void read(InputSource inputSource) throws Exception { DocumentBuilderFactory docFac = DocumentBuilderFactory.newInstance(); docFac.setNamespaceAware(true);/* www .j ava 2s.c om*/ DocumentBuilder builder = docFac.newDocumentBuilder(); Document doc = builder.parse(inputSource); read(doc.getDocumentElement(), inputSource.getSystemId() != null ? new URI(inputSource.getSystemId()) : null); }
From source file:de.smartics.maven.alias.MavenAliasMojo.java
private AliasesProcessor createProcessor(final InputSource source) throws MojoExecutionException { try {/*from w ww .ja va 2 s. c o m*/ return new AliasesProcessor(source); } catch (final Exception e) { throw new MojoExecutionException("Cannot read alias XML from '" + source.getSystemId() + "'.", e); } }
From source file:com.netspective.commons.xml.ParseContext.java
public void init(InputSource inputSource) throws ParserConfigurationException, SAXException { this.inputSource = inputSource; this.errors = new ArrayList(); this.warnings = new ArrayList(); if (inputSource.getSystemId() == null) throw new ParserConfigurationException("Please set the system id."); SAXParser saxParser = getParserFactory().newSAXParser(); parser = saxParser.getXMLReader();/*from ww w. j a v a 2s . c o m*/ }
From source file:com.netspective.commons.xml.ParseContext.java
public void doExternalTransformations() throws TransformerConfigurationException, TransformerException, ParserConfigurationException, SAXException, IOException { // re-create the input source because the original stream is already closed InputSource inputSource = recreateInputSource(); Source activeSource = inputSource.getByteStream() != null ? new StreamSource(inputSource.getByteStream()) : new StreamSource(inputSource.getCharacterStream()); activeSource.setSystemId(inputSource.getSystemId()); Writer activeResultBuffer = new StringWriter(); Result activeResult = new StreamResult(activeResultBuffer); activeResult.setSystemId(activeResultBuffer.getClass().getName()); TransformerFactory factory = TransformerFactory.newInstance(); int lastTransformer = transformSources.length - 1; for (int i = 0; i <= lastTransformer; i++) { Transformer transformer = factory.newTransformer(transformSources[i]); transformer.transform(activeSource, activeResult); if (i < lastTransformer) { activeSource = new StreamSource(new StringReader(activeResultBuffer.toString())); activeResultBuffer = new StringWriter(); activeResult = new StreamResult(activeResultBuffer); }/*from w ww .j ava 2s . c o m*/ } // now that all the transformations have been performed, we want to reset our input source to the final // transformation init(createInputSource(activeResultBuffer.toString())); }
From source file:CSVXMLReader.java
/** * Parse a CSV file. SAX events are delivered to the ContentHandler * that was registered via <code>setContentHandler</code>. * * @param input the comma separated values file to parse. *//*from w ww . j ava 2 s .c o m*/ public void parse(InputSource input) throws IOException, SAXException { // if no handler is registered to receive events, don't bother // to parse the CSV file ContentHandler ch = getContentHandler(); if (ch == null) { return; } // convert the InputSource into a BufferedReader BufferedReader br = null; if (input.getCharacterStream() != null) { br = new BufferedReader(input.getCharacterStream()); } else if (input.getByteStream() != null) { br = new BufferedReader(new InputStreamReader(input.getByteStream())); } else if (input.getSystemId() != null) { java.net.URL url = new URL(input.getSystemId()); br = new BufferedReader(new InputStreamReader(url.openStream())); } else { throw new SAXException("Invalid InputSource object"); } ch.startDocument(); // emit <csvFile> ch.startElement("", "", "csvFile", EMPTY_ATTR); // read each line of the file until EOF is reached String curLine = null; while ((curLine = br.readLine()) != null) { curLine = curLine.trim(); if (curLine.length() > 0) { // create the <line> element ch.startElement("", "", "line", EMPTY_ATTR); // output data from this line parseLine(curLine, ch); // close the </line> element ch.endElement("", "", "line"); } } // emit </csvFile> ch.endElement("", "", "csvFile"); ch.endDocument(); }
From source file:net.lightbody.bmp.proxy.jetty.xml.XmlParser.java
public synchronized Node parse(InputSource source) throws IOException, SAXException { Handler handler = new Handler(); XMLReader reader = _parser.getXMLReader(); reader.setContentHandler(handler);/*from www . j a va 2s .c o m*/ reader.setErrorHandler(handler); reader.setEntityResolver(handler); if (log.isDebugEnabled()) log.debug("parsing: sid=" + source.getSystemId() + ",pid=" + source.getPublicId()); _parser.parse(source, handler); if (handler._error != null) throw handler._error; Node doc = (Node) handler._top.get(0); handler.clear(); return doc; }
From source file:org.mycore.common.xml.MCRURIResolver.java
/** * URI Resolver that resolves XSL document() or xsl:include calls. * * @see javax.xml.transform.URIResolver//from w w w. jav a2 s. c om */ public Source resolve(String href, String base) throws TransformerException { if (LOGGER.isDebugEnabled()) { if (base != null) { LOGGER.debug("Including " + href + " from " + base); addDebugInfo(href, base); } else { LOGGER.debug("Including " + href); addDebugInfo(href, null); } } if (!href.contains(":")) { return tryResolveXSL(href, base); } String scheme = getScheme(href, base); URIResolver uriResolver = SUPPORTED_SCHEMES.get(scheme); if (uriResolver != null) { return uriResolver.resolve(href, base); } else { // try to handle as URL, use default resolver for file:// and try { InputSource entity = MCREntityResolver.instance().resolveEntity(null, href); if (entity != null) { LOGGER.debug("Resolved via EntityResolver: " + entity.getSystemId()); return new MCRLazyStreamSource(entity::getByteStream, entity.getSystemId()); } } catch (SAXException | IOException e) { LOGGER.debug("Error while resolving uri: " + href); } // http:// if (href.endsWith("/") && scheme.equals("file")) { //cannot stream directories return null; } StreamSource streamSource = new StreamSource(); streamSource.setSystemId(href); return streamSource; } }
From source file:org.anodyneos.jse.cron.CronDaemon.java
public CronDaemon(InputSource source) throws JseException { Schedule schedule;/*ww w . j a va 2s . c o m*/ // parse source try { JAXBContext jc = JAXBContext.newInstance("org.anodyneos.jse.cron.config"); Unmarshaller u = jc.createUnmarshaller(); //Schedule Source schemaSource = new StreamSource(Thread.currentThread().getContextClassLoader() .getResourceAsStream("org/anodyneos/jse/cron/cron.xsd")); SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = sf.newSchema(schemaSource); u.setSchema(schema); ValidationEventCollector vec = new ValidationEventCollector(); u.setEventHandler(vec); JAXBElement<?> rootElement; try { rootElement = ((JAXBElement<?>) u.unmarshal(source)); } catch (UnmarshalException ex) { if (!vec.hasEvents()) { throw ex; } else { for (ValidationEvent ve : vec.getEvents()) { ValidationEventLocator vel = ve.getLocator(); log.error("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:" + ve.getMessage()); } throw new JseException("Validation failed for source publicId='" + source.getPublicId() + "'; systemId='" + source.getSystemId() + "';"); } } schedule = (Schedule) rootElement.getValue(); if (vec.hasEvents()) { for (ValidationEvent ve : vec.getEvents()) { ValidationEventLocator vel = ve.getLocator(); log.warn("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:" + ve.getMessage()); } } } catch (JseException e) { throw e; } catch (Exception e) { throw new JseException("Cannot parse " + source + ".", e); } SpringHelper springHelper = new SpringHelper(); //////////////// // // Configure Spring and Create Beans // //////////////// TimeZone defaultTimeZone; if (schedule.isSetTimeZone()) { defaultTimeZone = getTimeZone(schedule.getTimeZone()); } else { defaultTimeZone = TimeZone.getDefault(); } if (schedule.isSetSpringContext() && schedule.getSpringContext().isSetConfig()) { for (Config config : schedule.getSpringContext().getConfig()) { springHelper.addXmlClassPathConfigLocation(config.getClassPathResource()); } } for (org.anodyneos.jse.cron.config.JobGroup jobGroup : schedule.getJobGroup()) { for (Job job : jobGroup.getJob()) { if (job.isSetBeanRef()) { if (job.isSetBean() || job.isSetClassName()) { throw new JseException("Cannot set bean or class attribute for job when beanRef is set."); } // else config ok } else { if (!job.isSetClassName()) { throw new JseException("must set either class or beanRef for job."); } GenericBeanDefinition beanDef = new GenericBeanDefinition(); MutablePropertyValues propertyValues = new MutablePropertyValues(); if (!job.isSetBean()) { job.setBean(UUID.randomUUID().toString()); } if (springHelper.containsBean(job.getBean())) { throw new JseException( "Bean name already used; overriding not allowed here: " + job.getBean()); } beanDef.setBeanClassName(job.getClassName()); for (Property prop : job.getProperty()) { String value = null; if (prop.isSetSystemProperty()) { value = System.getProperty(prop.getSystemProperty()); } if (null == value) { value = prop.getValue(); } propertyValues.addPropertyValue(prop.getName(), value); } beanDef.setPropertyValues(propertyValues); springHelper.registerBean(job.getBean(), beanDef); job.setBeanRef(job.getBean()); } } } springHelper.init(); //////////////// // // Configure Timer Services // //////////////// for (org.anodyneos.jse.cron.config.JobGroup jobGroup : schedule.getJobGroup()) { String jobGroupName; JseTimerService service = new JseTimerService(); timerServices.add(service); if (jobGroup.isSetName()) { jobGroupName = jobGroup.getName(); } else { jobGroupName = UUID.randomUUID().toString(); } if (jobGroup.isSetMaxConcurrent()) { service.setMaxConcurrent(jobGroup.getMaxConcurrent()); } for (Job job : jobGroup.getJob()) { TimeZone jobTimeZone = defaultTimeZone; if (job.isSetTimeZone()) { jobTimeZone = getTimeZone(job.getTimeZone()); } else { jobTimeZone = defaultTimeZone; } Object obj; Date notBefore = null; Date notAfter = null; if (job.isSetNotBefore()) { notBefore = job.getNotBefore().toGregorianCalendar(jobTimeZone, null, null).getTime(); } if (job.isSetNotAfter()) { notAfter = job.getNotAfter().toGregorianCalendar(jobTimeZone, null, null).getTime(); } CronSchedule cs = new CronSchedule(job.getSchedule(), jobTimeZone, job.getMaxIterations(), job.getMaxQueue(), notBefore, notAfter); obj = springHelper.getBean(job.getBeanRef()); log.info("Adding job " + jobGroup.getName() + "/" + job.getName() + " using bean " + job.getBeanRef()); if (obj instanceof CronJob) { ((CronJob) obj).setCronContext(new CronContext(jobGroupName, job.getName(), cs)); } if (obj instanceof JseDateAwareJob) { service.createTimer((JseDateAwareJob) obj, cs); } else if (obj instanceof Runnable) { service.createTimer((Runnable) obj, cs); } else { throw new JseException("Job must implement Runnable or JseDateAwareJob"); } } } }
From source file:org.apache.axis2.jaxbri.CodeGenerationUtility.java
/** * @param additionalSchemas/*from ww w.j a v a2 s . co m*/ * @throws RuntimeException */ public static TypeMapper processSchemas(final List schemas, Element[] additionalSchemas, CodeGenConfiguration cgconfig) throws RuntimeException { try { //check for the imported types. Any imported types are supposed to be here also if (schemas == null || schemas.isEmpty()) { //there are no types to be code generated //However if the type mapper is left empty it will be a problem for the other //processes. Hence the default type mapper is set to the configuration return new DefaultTypeMapper(); } final Map schemaToInputSourceMap = new HashMap(); final Map<String, StringBuffer> publicIDToStringMap = new HashMap<String, StringBuffer>(); //create the type mapper JavaTypeMapper mapper = new JavaTypeMapper(); String baseURI = cgconfig.getBaseURI(); if (!baseURI.endsWith("/")) { baseURI = baseURI + "/"; } for (int i = 0; i < schemas.size(); i++) { XmlSchema schema = (XmlSchema) schemas.get(i); InputSource inputSource = new InputSource(new StringReader(getSchemaAsString(schema))); //here we have to set a proper system ID. otherwise when processing the // included schaemas for this schema we have a problem // it creates the system ID using this target namespace value inputSource.setSystemId(baseURI + "xsd" + i + ".xsd"); inputSource.setPublicId(schema.getTargetNamespace()); schemaToInputSourceMap.put(schema, inputSource); } File outputDir = new File(cgconfig.getOutputLocation(), "src"); outputDir.mkdir(); Map nsMap = cgconfig.getUri2PackageNameMap(); EntityResolver resolver = new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { InputSource returnInputSource = null; XmlSchema key = null; for (Iterator iter = schemaToInputSourceMap.keySet().iterator(); iter.hasNext();) { key = (XmlSchema) iter.next(); String nsp = key.getTargetNamespace(); if (nsp != null && nsp.equals(publicId)) { // when returning the input stream we have to always return a new // input stream. // sinc jaxbri internally consumes the input stream it gives an // exception. returnInputSource = new InputSource(new StringReader(getSchemaAsString(key))); InputSource existingInputSource = (InputSource) schemaToInputSourceMap.get(key); returnInputSource.setSystemId(existingInputSource.getSystemId()); returnInputSource.setPublicId(existingInputSource.getPublicId()); break; } } if (returnInputSource == null) { // then we have to find this using the file system if (systemId != null) { returnInputSource = new InputSource(systemId); returnInputSource.setSystemId(systemId); } } if (returnInputSource == null) { if (publicId != null) { if (!publicIDToStringMap.containsKey(publicId)) { URL url = new URL(publicId); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(url.openStream())); StringBuffer stringBuffer = new StringBuffer(); String str = null; while ((str = bufferedReader.readLine()) != null) { stringBuffer.append(str); } publicIDToStringMap.put(publicId, stringBuffer); } String schemaString = publicIDToStringMap.get(publicId).toString(); returnInputSource = new InputSource(new StringReader(schemaString)); returnInputSource.setPublicId(publicId); returnInputSource.setSystemId(publicId); } } return returnInputSource; } }; Map properties = cgconfig.getProperties(); String bindingFileName = (String) properties.get(BINDING_FILE_NAME); XmlSchema key = null; for (Iterator schemaIter = schemaToInputSourceMap.keySet().iterator(); schemaIter.hasNext();) { SchemaCompiler sc = XJC.createSchemaCompiler(); if (bindingFileName != null) { if (bindingFileName.endsWith(".jar")) { scanEpisodeFile(new File(bindingFileName), sc); } else { InputSource inputSoruce = new InputSource(new FileInputStream(bindingFileName)); inputSoruce.setSystemId(new File(bindingFileName).toURI().toString()); sc.getOptions().addBindFile(inputSoruce); } } key = (XmlSchema) schemaIter.next(); if (nsMap != null) { Iterator iterator = nsMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); String namespace = (String) entry.getKey(); String pkg = (String) nsMap.get(namespace); registerNamespace(sc, namespace, pkg); } } sc.setEntityResolver(resolver); sc.setErrorListener(new ErrorListener() { public void error(SAXParseException saxParseException) { log.error(saxParseException.getMessage()); log.debug(saxParseException.getMessage(), saxParseException); } public void fatalError(SAXParseException saxParseException) { log.error(saxParseException.getMessage()); log.debug(saxParseException.getMessage(), saxParseException); } public void warning(SAXParseException saxParseException) { log.warn(saxParseException.getMessage()); log.debug(saxParseException.getMessage(), saxParseException); } public void info(SAXParseException saxParseException) { log.info(saxParseException.getMessage()); log.debug(saxParseException.getMessage(), saxParseException); } }); sc.parseSchema((InputSource) schemaToInputSourceMap.get(key)); sc.getOptions().addGrammar((InputSource) schemaToInputSourceMap.get(key)); for (Object property : properties.keySet()) { String propertyName = (String) property; if (propertyName.startsWith("X")) { String[] args = null; String propertyValue = (String) properties.get(property); if (propertyValue != null) { args = new String[] { "-" + propertyName, propertyValue }; } else { args = new String[] { "-" + propertyName }; } sc.getOptions().parseArguments(args); } } // Bind the XML S2JJAXBModel jaxbModel = sc.bind(); if (jaxbModel == null) { throw new RuntimeException("Unable to generate code using jaxbri"); } // Emit the code artifacts JCodeModel codeModel = jaxbModel.generateCode(null, null); FileCodeWriter writer = new FileCodeWriter(outputDir); codeModel.build(writer); Collection mappings = jaxbModel.getMappings(); Iterator iter = mappings.iterator(); while (iter.hasNext()) { Mapping mapping = (Mapping) iter.next(); QName qn = mapping.getElement(); String typeName = mapping.getType().getTypeClass().fullName(); mapper.addTypeMappingName(qn, typeName); } //process the unwrapped parameters if (!cgconfig.isParametersWrapped()) { //figure out the unwrapped operations List axisServices = cgconfig.getAxisServices(); for (Iterator servicesIter = axisServices.iterator(); servicesIter.hasNext();) { AxisService axisService = (AxisService) servicesIter.next(); for (Iterator operations = axisService.getOperations(); operations.hasNext();) { AxisOperation op = (AxisOperation) operations.next(); if (WSDLUtil.isInputPresentForMEP(op.getMessageExchangePattern())) { AxisMessage message = op.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE); if (message != null && message.getParameter(Constants.UNWRAPPED_KEY) != null) { Mapping mapping = jaxbModel.get(message.getElementQName()); List elementProperties = mapping.getWrapperStyleDrilldown(); for (int j = 0; j < elementProperties.size(); j++) { Property elementProperty = (Property) elementProperties.get(j); QName partQName = WSDLUtil.getPartQName(op.getName().getLocalPart(), WSDLConstants.INPUT_PART_QNAME_SUFFIX, elementProperty.elementName().getLocalPart()); //this type is based on a primitive type- use the //primitive type name in this case String fullJaveName = elementProperty.type().fullName(); if (elementProperty.type().isArray()) { fullJaveName = fullJaveName.concat("[]"); } mapper.addTypeMappingName(partQName, fullJaveName); if (elementProperty.type().isPrimitive()) { mapper.addTypeMappingStatus(partQName, Boolean.TRUE); } if (elementProperty.type().isArray()) { mapper.addTypeMappingStatus(partQName, Constants.ARRAY_TYPE); } } } } if (WSDLUtil.isOutputPresentForMEP(op.getMessageExchangePattern())) { AxisMessage message = op.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE); if (message != null && message.getParameter(Constants.UNWRAPPED_KEY) != null) { Mapping mapping = jaxbModel.get(message.getElementQName()); List elementProperties = mapping.getWrapperStyleDrilldown(); for (int j = 0; j < elementProperties.size(); j++) { Property elementProperty = (Property) elementProperties.get(j); QName partQName = WSDLUtil.getPartQName(op.getName().getLocalPart(), WSDLConstants.OUTPUT_PART_QNAME_SUFFIX, elementProperty.elementName().getLocalPart()); //this type is based on a primitive type- use the //primitive type name in this case String fullJaveName = elementProperty.type().fullName(); if (elementProperty.type().isArray()) { fullJaveName = fullJaveName.concat("[]"); } mapper.addTypeMappingName(partQName, fullJaveName); if (elementProperty.type().isPrimitive()) { mapper.addTypeMappingStatus(partQName, Boolean.TRUE); } if (elementProperty.type().isArray()) { mapper.addTypeMappingStatus(partQName, Constants.ARRAY_TYPE); } } } } } } } } // Return the type mapper return mapper; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.apache.axis2.jaxws.description.impl.URIResolverImpl.java
public InputSource resolveEntity(String namespace, String schemaLocation, String baseUri) { if (log.isDebugEnabled()) { log.debug("resolveEntity: [" + namespace + "][" + schemaLocation + "][ " + baseUri + "]"); }/* w ww . j a v a 2 s .c o m*/ InputStream is = null; URI pathURI = null; String pathURIStr = null; if (log.isDebugEnabled()) { log.debug("Import location: " + schemaLocation + " parent document: " + baseUri); } if (baseUri != null) { try { // if the location is an absolute path, build a URL directly // from it if (log.isDebugEnabled()) { log.debug("Base URI not null"); } if (isAbsolute(schemaLocation)) { if (log.isDebugEnabled()) { log.debug("Retrieving input stream for absolute schema location: " + schemaLocation); } is = getInputStreamForURI(schemaLocation); } else { if (log.isDebugEnabled()) { log.debug("schemaLocation not in absolute path"); } try { pathURI = new URI(baseUri); } catch (URISyntaxException e) { // Got URISyntaxException, Creation of URI requires // that we use special escape characters in path. // The URI constructor below does this for us, so lets use that. if (log.isDebugEnabled()) { log.debug("Got URISyntaxException. Exception Message = " + e.getMessage()); log.debug("Implementing alternate way to create URI"); } pathURI = new URI(null, null, baseUri, null); } pathURIStr = schemaLocation; // If this is absolute we need to resolve the path without the // scheme information if (pathURI.isAbsolute()) { if (log.isDebugEnabled()) { log.debug("Parent document is at absolute location: " + pathURI.toString()); } URL url = new URL(baseUri); if (url != null) { URI tempURI; try { tempURI = new URI(url.getPath()); } catch (URISyntaxException e) { //Got URISyntaxException, Creation of URI requires // that we use special escape characters in path. // The URI constructor below does this for us, so lets use that. if (log.isDebugEnabled()) { log.debug("Got URISyntaxException. Exception Message = " + e.getMessage()); log.debug("Implementing alternate way to create URI"); } tempURI = new URI(null, null, url.getPath(), null); } URI resolvedURI = tempURI.resolve(schemaLocation); // Add back the scheme to the resolved path pathURIStr = constructPath(url, resolvedURI); if (log.isDebugEnabled()) { log.debug("Resolved this path to imported document: " + pathURIStr); } } } else { if (log.isDebugEnabled()) { log.debug("Parent document is at relative location: " + pathURI.toString()); } pathURI = pathURI.resolve(schemaLocation); pathURIStr = pathURI.toString(); if (log.isDebugEnabled()) { log.debug("Resolved this path to imported document: " + pathURIStr); } } // If path is absolute, build URL directly from it if (isAbsolute(pathURIStr)) { is = getInputStreamForURI(pathURIStr); } // if the location is relative, we need to resolve the // location using // the baseURI, then use the loadStrategy to gain an input // stream // because the URI will still be relative to the module if (is == null) { is = classLoader.getResourceAsStream(pathURI.toString()); } } } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Exception occured in resolveEntity, ignoring exception continuing processing " + e.getMessage()); log.debug(e); } } } if (is == null) { if (log.isDebugEnabled()) { log.debug("XSD input stream is null after resolving import for: " + schemaLocation + " from parent document: " + baseUri); } } else { if (log.isDebugEnabled()) { log.debug("XSD input stream is not null after resolving import for: " + schemaLocation + " from parent document: " + baseUri); } } InputSource returnInputSource = new InputSource(is); // We need to set the systemId. XmlSchema will use this value to maintain a collection of // imported XSDs that have been read. If this value is null, then circular XSDs will // cause infinite recursive reads. returnInputSource.setSystemId(pathURIStr != null ? pathURIStr : schemaLocation); if (log.isDebugEnabled()) { log.debug("returnInputSource :" + returnInputSource.getSystemId()); } return returnInputSource; }