List of usage examples for javax.xml.stream XMLStreamReader getAttributeValue
public String getAttributeValue(String namespaceURI, String localName);
From source file:org.activiti.designer.eclipse.bpmn.BpmnParser.java
private SignalEventDefinition parseSignalEventDefinition(XMLStreamReader xtr) { SignalEventDefinition eventDefinition = new SignalEventDefinition(); if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, "signalRef"))) { eventDefinition.setSignalRef(xtr.getAttributeValue(null, "signalRef")); }//from ww w . j a v a 2 s.c o m return eventDefinition; }
From source file:org.activiti.dmn.xml.converter.DmnXMLConverter.java
public DmnDefinition convertToDmnModel(XMLStreamReader xtr) { DmnDefinition model = new DmnDefinition(); DmnElement parentElement = null;//from w w w.j a va 2 s . c o m try { while (xtr.hasNext()) { try { xtr.next(); } catch (Exception e) { LOGGER.debug("Error reading XML document", e); throw new DmnXMLException("Error reading XML", e); } if (xtr.isStartElement() == false) { continue; } if (ELEMENT_DEFINITIONS.equals(xtr.getLocalName())) { model.setId(xtr.getAttributeValue(null, ATTRIBUTE_ID)); model.setName(xtr.getAttributeValue(null, ATTRIBUTE_NAME)); model.setNamespace(MODEL_NAMESPACE); parentElement = model; } else if (ELEMENT_DECISION.equals(xtr.getLocalName())) { Decision decision = new Decision(); model.addDrgElement(decision); decision.setId(xtr.getAttributeValue(null, ATTRIBUTE_ID)); decision.setName(xtr.getAttributeValue(null, ATTRIBUTE_NAME)); parentElement = decision; } else if (ELEMENT_DECISION_TABLE.equals(xtr.getLocalName())) { DecisionTable currentDecisionTable = new DecisionTable(); currentDecisionTable.setId(xtr.getAttributeValue(null, ATTRIBUTE_ID)); if (xtr.getAttributeValue(null, ATTRIBUTE_HIT_POLICY) != null) { currentDecisionTable .setHitPolicy(HitPolicy.valueOf(xtr.getAttributeValue(null, ATTRIBUTE_HIT_POLICY))); } else { currentDecisionTable.setHitPolicy(HitPolicy.FIRST); } model.getDrgElements().get(model.getDrgElements().size() - 1) .setDecisionTable(currentDecisionTable); model.setCurrentDecisionTable(currentDecisionTable); parentElement = currentDecisionTable; } else if (ELEMENT_OUTPUT_CLAUSE.equals(xtr.getLocalName())) { OutputClause outputClause = new OutputClause(); model.getCurrentDecisionTable().addOutput(outputClause); outputClause.setId(xtr.getAttributeValue(null, ATTRIBUTE_ID)); outputClause.setLabel(xtr.getAttributeValue(null, ATTRIBUTE_LABEL)); outputClause.setName(xtr.getAttributeValue(null, ATTRIBUTE_NAME)); outputClause.setTypeRef(xtr.getAttributeValue(null, ATTRIBUTE_TYPE_REF)); parentElement = outputClause; } else if (ELEMENT_DESCRIPTION.equals(xtr.getLocalName())) { parentElement.setDescription(xtr.getElementText()); } else if (ELEMENT_EXTENSIONS.equals(xtr.getLocalName())) { while (xtr.hasNext()) { xtr.next(); if (xtr.isStartElement()) { DmnExtensionElement extensionElement = DmnXMLUtil.parseExtensionElement(xtr); parentElement.addExtensionElement(extensionElement); } else if (xtr.isEndElement()) { if (ELEMENT_EXTENSIONS.equals(xtr.getLocalName())) { break; } } } } else if (convertersToDmnMap.containsKey(xtr.getLocalName())) { BaseDmnXMLConverter converter = convertersToDmnMap.get(xtr.getLocalName()); converter.convertToDmnModel(xtr, model); } } processDmnElements(model.getCurrentDecisionTable()); } catch (DmnXMLException e) { throw e; } catch (Exception e) { LOGGER.error("Error processing DMN document", e); throw new DmnXMLException("Error processing DMN document", e); } return model; }
From source file:org.apache.axis2.databinding.utils.ConverterUtil.java
public static Object getAnyTypeObject(XMLStreamReader xmlStreamReader, Class extensionMapperClass) throws XMLStreamException { Object returnObject = null;//ww w .j av a 2s . c om // make sure reader is at the first element. while (!xmlStreamReader.isStartElement()) { xmlStreamReader.next(); } // first check whether this element is null or not String nillableValue = xmlStreamReader.getAttributeValue(Constants.XSI_NAMESPACE, "nil"); if ("true".equals(nillableValue) || "1".equals(nillableValue)) { returnObject = null; xmlStreamReader.next(); } else { String attributeType = xmlStreamReader.getAttributeValue(Constants.XSI_NAMESPACE, "type"); if (attributeType != null) { String attributeTypePrefix = ""; if (attributeType.indexOf(":") > -1) { attributeTypePrefix = attributeType.substring(0, attributeType.indexOf(":")); attributeType = attributeType.substring(attributeType.indexOf(":") + 1); } NamespaceContext namespaceContext = xmlStreamReader.getNamespaceContext(); String attributeNameSpace = namespaceContext.getNamespaceURI(attributeTypePrefix); if (Constants.XSD_NAMESPACE.equals(attributeNameSpace)) { if ("base64Binary".equals(attributeType)) { returnObject = XMLStreamReaderUtils.getDataHandlerFromElement(xmlStreamReader); } else { String attribValue = xmlStreamReader.getElementText(); if (attribValue != null) { if (attributeType.equals("string")) { returnObject = attribValue; } else if (attributeType.equals("int")) { returnObject = new Integer(attribValue); } else if (attributeType.equals("QName")) { String namespacePrefix = null; String localPart = null; if (attribValue.indexOf(":") > -1) { namespacePrefix = attribValue.substring(0, attribValue.indexOf(":")); localPart = attribValue.substring(attribValue.indexOf(":") + 1); returnObject = new QName(namespaceContext.getNamespaceURI(namespacePrefix), localPart); } } else if ("boolean".equals(attributeType)) { returnObject = new Boolean(attribValue); } else if ("anyURI".equals(attributeType)) { try { returnObject = new URI(attribValue); } catch (URI.MalformedURIException e) { throw new XMLStreamException("Invalid URI"); } } else if ("date".equals(attributeType)) { returnObject = ConverterUtil.convertToDate(attribValue); } else if ("dateTime".equals(attributeType)) { returnObject = ConverterUtil.convertToDateTime(attribValue); } else if ("time".equals(attributeType)) { returnObject = ConverterUtil.convertToTime(attribValue); } else if ("byte".equals(attributeType)) { returnObject = new Byte(attribValue); } else if ("short".equals(attributeType)) { returnObject = new Short(attribValue); } else if ("float".equals(attributeType)) { returnObject = new Float(attribValue); } else if ("long".equals(attributeType)) { returnObject = new Long(attribValue); } else if ("double".equals(attributeType)) { returnObject = new Double(attribValue); } else if ("decimal".equals(attributeType)) { returnObject = new BigDecimal(attribValue); } else if ("unsignedLong".equals(attributeType)) { returnObject = new UnsignedLong(attribValue); } else if ("unsignedInt".equals(attributeType)) { returnObject = new UnsignedInt(attribValue); } else if ("unsignedShort".equals(attributeType)) { returnObject = new UnsignedShort(attribValue); } else if ("unsignedByte".equals(attributeType)) { returnObject = new UnsignedByte(attribValue); } else if ("positiveInteger".equals(attributeType)) { returnObject = new PositiveInteger(attribValue); } else if ("negativeInteger".equals(attributeType)) { returnObject = new NegativeInteger(attribValue); } else if ("nonNegativeInteger".equals(attributeType)) { returnObject = new NonNegativeInteger(attribValue); } else if ("nonPositiveInteger".equals(attributeType)) { returnObject = new NonPositiveInteger(attribValue); } else { throw new ADBException("Unknown type ==> " + attributeType); } } else { throw new ADBException("Attribute value is null"); } } } else { try { Method getObjectMethod = extensionMapperClass.getMethod("getTypeObject", new Class[] { String.class, String.class, XMLStreamReader.class }); returnObject = getObjectMethod.invoke(null, new Object[] { attributeNameSpace, attributeType, xmlStreamReader }); } catch (NoSuchMethodException e) { throw new ADBException( "Can not find the getTypeObject method in the " + "extension mapper class ", e); } catch (IllegalAccessException e) { throw new ADBException( "Can not access the getTypeObject method in the " + "extension mapper class ", e); } catch (InvocationTargetException e) { throw new ADBException( "Can not invoke the getTypeObject method in the " + "extension mapper class ", e); } } } else { throw new ADBException("Any type element type has not been given"); } } return returnObject; }
From source file:org.apache.syncope.client.console.widgets.reconciliation.ReconciliationReportParser.java
public static ReconciliationReport parse(final Date run, final InputStream in) throws XMLStreamException { XMLStreamReader streamReader = INPUT_FACTORY.createXMLStreamReader(in); streamReader.nextTag(); // root streamReader.nextTag(); // report streamReader.nextTag(); // reportlet ReconciliationReport report = new ReconciliationReport(run); List<Missing> missing = new ArrayList<>(); List<Misaligned> misaligned = new ArrayList<>(); Set<String> onSyncope = null; Set<String> onResource = null; Any user = null;/* w w w . ja v a2 s . c o m*/ Any group = null; Any anyObject = null; String lastAnyType = null; while (streamReader.hasNext()) { if (streamReader.isStartElement()) { switch (streamReader.getLocalName()) { case "users": Anys users = new Anys(); users.setTotal(Integer.valueOf(streamReader.getAttributeValue("", "total"))); report.setUsers(users); break; case "user": user = new Any(); user.setType(AnyTypeKind.USER.name()); user.setKey(streamReader.getAttributeValue("", "key")); user.setName(streamReader.getAttributeValue("", "username")); report.getUsers().getAnys().add(user); break; case "groups": Anys groups = new Anys(); groups.setTotal(Integer.valueOf(streamReader.getAttributeValue("", "total"))); report.setGroups(groups); break; case "group": group = new Any(); group.setType(AnyTypeKind.GROUP.name()); group.setKey(streamReader.getAttributeValue("", "key")); group.setName(streamReader.getAttributeValue("", "groupName")); report.getGroups().getAnys().add(group); break; case "anyObjects": lastAnyType = streamReader.getAttributeValue("", "type"); Anys anyObjects = new Anys(); anyObjects.setAnyType(lastAnyType); anyObjects.setTotal(Integer.valueOf(streamReader.getAttributeValue("", "total"))); report.getAnyObjects().add(anyObjects); break; case "anyObject": anyObject = new Any(); anyObject.setType(lastAnyType); anyObject.setKey(streamReader.getAttributeValue("", "key")); final String anyType = lastAnyType; IterableUtils.find(report.getAnyObjects(), new Predicate<Anys>() { @Override public boolean evaluate(final Anys anys) { return anyType.equals(anys.getAnyType()); } }).getAnys().add(anyObject); break; case "missing": missing.add(new Missing(streamReader.getAttributeValue("", "resource"), streamReader.getAttributeValue("", "connObjectKeyValue"))); break; case "misaligned": misaligned.add(new Misaligned(streamReader.getAttributeValue("", "resource"), streamReader.getAttributeValue("", "connObjectKeyValue"), streamReader.getAttributeValue("", "name"))); break; case "onSyncope": onSyncope = new HashSet<>(); break; case "onResource": onResource = new HashSet<>(); break; case "value": Set<String> set = onSyncope == null ? onResource : onSyncope; set.add(streamReader.getElementText()); break; default: } } else if (streamReader.isEndElement()) { switch (streamReader.getLocalName()) { case "user": user.getMissing().addAll(missing); user.getMisaligned().addAll(misaligned); missing.clear(); misaligned.clear(); break; case "group": group.getMissing().addAll(missing); group.getMisaligned().addAll(misaligned); missing.clear(); misaligned.clear(); break; case "anyObject": anyObject.getMissing().addAll(missing); anyObject.getMisaligned().addAll(misaligned); missing.clear(); misaligned.clear(); break; case "onSyncope": misaligned.get(misaligned.size() - 1).getOnSyncope().addAll(onSyncope); onSyncope = null; break; case "onResource": misaligned.get(misaligned.size() - 1).getOnResource().addAll(onResource); onResource = null; break; default: } } streamReader.next(); } return report; }
From source file:org.apache.sysml.runtime.controlprogram.parfor.opt.PerfTestTool.java
private static void readProfile(String fname) throws XMLStreamException, IOException { //init profile map _profile = new HashMap<Integer, HashMap<Integer, CostFunction>>(); //read existing profile FileInputStream fis = new FileInputStream(fname); try {//from ww w . j a v a 2 s . c om //xml parsing XMLInputFactory xif = XMLInputFactory.newInstance(); XMLStreamReader xsr = xif.createXMLStreamReader(fis); int e = xsr.nextTag(); // profile start while (true) //read all instructions { e = xsr.nextTag(); // instruction start if (e == XMLStreamConstants.END_ELEMENT) break; //reached profile end tag //parse instruction int ID = Integer.parseInt(xsr.getAttributeValue(null, XML_ID)); //String name = xsr.getAttributeValue(null, XML_NAME).trim().replaceAll(" ", Lops.OPERAND_DELIMITOR); HashMap<Integer, CostFunction> tmp = new HashMap<Integer, CostFunction>(); _profile.put(ID, tmp); while (true) { e = xsr.nextTag(); // cost function start if (e == XMLStreamConstants.END_ELEMENT) break; //reached instruction end tag //parse cost function TestMeasure m = TestMeasure.valueOf(xsr.getAttributeValue(null, XML_MEASURE)); TestVariable lv = TestVariable.valueOf(xsr.getAttributeValue(null, XML_VARIABLE)); InternalTestVariable[] pv = parseTestVariables( xsr.getAttributeValue(null, XML_INTERNAL_VARIABLES)); DataFormat df = DataFormat.valueOf(xsr.getAttributeValue(null, XML_DATAFORMAT)); int tDefID = getTestDefID(m, lv, df, pv); xsr.next(); //read characters double[] params = parseParams(xsr.getText()); boolean multidim = _regTestDef.get(tDefID).getInternalVariables().length > 1; CostFunction cf = new CostFunction(params, multidim); tmp.put(tDefID, cf); xsr.nextTag(); // cost function end //System.out.println("added cost function"); } } xsr.close(); } finally { IOUtilFunctions.closeSilently(fis); } //mark profile as successfully read _flagReadData = true; }
From source file:org.apache.tomcat.maven.plugin.tomcat7.run.AbstractRunMojo.java
protected StandardContext parseContextFile(File file) throws MojoExecutionException { try {/*from ww w .j av a 2 s .c o m*/ StandardContext standardContext = new StandardContext(); XMLStreamReader reader = XMLInputFactory.newFactory().createXMLStreamReader(new FileInputStream(file)); int tag = reader.next(); while (true) { if (tag == XMLStreamConstants.START_ELEMENT && StringUtils.equals("Context", reader.getLocalName())) { String path = reader.getAttributeValue(null, "path"); if (StringUtils.isNotBlank(path)) { standardContext.setPath(path); } String docBase = reader.getAttributeValue(null, "docBase"); if (StringUtils.isNotBlank(docBase)) { standardContext.setDocBase(docBase); } } if (!reader.hasNext()) { break; } tag = reader.next(); } return standardContext; } catch (XMLStreamException e) { throw new MojoExecutionException(e.getMessage(), e); } catch (FileNotFoundException e) { throw new MojoExecutionException(e.getMessage(), e); } }
From source file:org.deegree.maven.XMLCatalogueMojo.java
@Override public void execute() throws MojoExecutionException, MojoFailureException { File target = new File(project.getBasedir(), "target"); target.mkdirs();/*from www.ja v a2s .co m*/ target = new File(target, "deegree.xmlcatalog"); PrintStream catalogOut = null; try { catalogOut = new PrintStream(new FileOutputStream(target), true, "UTF-8"); final PrintStream catalog = catalogOut; addDependenciesToClasspath(project, artifactResolver, artifactFactory, metadataSource, localRepository); final XMLInputFactory fac = XMLInputFactory.newInstance(); final Reflections r = new Reflections("/META-INF/schemas/"); class CurrentState { String location; } final CurrentState state = new CurrentState(); r.collect("META-INF/schemas", new Predicate<String>() { @Override public boolean apply(String input) { state.location = input; return input != null && input.endsWith(".xsd"); } }, new Serializer() { @Override public Reflections read(InputStream in) { try { XMLStreamReader reader = fac.createXMLStreamReader(in); nextElement(reader); String location = "classpath:META-INF/schemas/" + state.location; String ns = reader.getAttributeValue(null, "targetNamespace"); catalog.println("PUBLIC \"" + ns + "\" \"" + location + "\""); } catch (Throwable e) { getLog().error(e); } return r; } @Override public File save(Reflections reflections, String filename) { return null; } @Override public String toString(Reflections reflections) { return null; } }); } catch (Throwable t) { throw new MojoFailureException("Creating xml catalog failed: " + t.getLocalizedMessage(), t); } finally { closeQuietly(catalogOut); } }
From source file:org.deegree.services.wps.WPService.java
@Override public void doXML(XMLStreamReader xmlStream, HttpServletRequest request, HttpResponseBuffer response, List<FileItem> multiParts) throws ServletException, IOException { LOG.trace("doXML invoked"); try {/*from ww w.jav a 2 s.c om*/ WPSRequestType requestType = getRequestTypeByName(xmlStream.getLocalName()); // check if requested version is supported and offered (except for GetCapabilities) Version requestVersion = getVersion(xmlStream.getAttributeValue(null, "version")); if (requestType != WPSRequestType.GetCapabilities) { checkVersion(requestVersion); } switch (requestType) { case GetCapabilities: GetCapabilitiesXMLAdapter getCapabilitiesAdapter = new GetCapabilitiesXMLAdapter(); getCapabilitiesAdapter.load(xmlStream); GetCapabilities getCapabilitiesRequest = getCapabilitiesAdapter.parse100(); doGetCapabilities(getCapabilitiesRequest, response); break; case DescribeProcess: DescribeProcessRequestXMLAdapter describeProcessAdapter = new DescribeProcessRequestXMLAdapter(); describeProcessAdapter.load(xmlStream); DescribeProcessRequest describeProcessRequest = describeProcessAdapter.parse100(); doDescribeProcess(describeProcessRequest, response); break; case Execute: // TODO switch to StaX-based parsing ExecuteRequestXMLAdapter executeAdapter = new ExecuteRequestXMLAdapter( processManager.getProcesses(), storageManager); executeAdapter.load(xmlStream); ExecuteRequest executeRequest = executeAdapter.parse100(); doExecute(executeRequest, response); break; case GetOutput: case GetResponseDocument: String msg = "Request type '" + requestType.name() + "' is only support as KVP request."; throw new OWSException(msg, OWSException.OPERATION_NOT_SUPPORTED); } } catch (OWSException e) { sendServiceException(e, response); } catch (XMLStreamException e) { LOG.debug(e.getMessage()); } catch (UnknownCRSException e) { LOG.debug(e.getMessage()); } }
From source file:org.deegree.style.se.parser.GraphicSymbologyParser.java
private Triple<InputStream, String, Continuation<StringBuffer>> getOnlineResourceOrInlineContent( XMLStreamReader in) throws XMLStreamException { if (in.getLocalName().equals("OnlineResource")) { String str = in.getAttributeValue(XLNNS, "href"); if (str == null) { Continuation<StringBuffer> contn = context.parser.updateOrContinue(in, "OnlineResource", new StringBuffer(), SBUPDATER, null).second; return new Triple<InputStream, String, Continuation<StringBuffer>>(null, null, contn); }//w ww. ja v a2s . c o m String strUrl = null; try { URL url; if (context.location != null) { url = context.location.resolveToUrl(str); } else { url = resolve(str, in); } strUrl = url.toExternalForm(); LOG.debug("Loading from URL '{}'", url); in.nextTag(); return new Triple<InputStream, String, Continuation<StringBuffer>>(url.openStream(), strUrl, null); } catch (IOException e) { LOG.debug("Stack trace:", e); LOG.warn("Could not retrieve content at URL '{}'.", str); return null; } } else if (in.getLocalName().equals("InlineContent")) { String format = in.getAttributeValue(null, "encoding"); if (format.equalsIgnoreCase("base64")) { ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decodeBase64(in.getElementText())); return new Triple<InputStream, String, Continuation<StringBuffer>>(bis, null, null); } // if ( format.equalsIgnoreCase( "xml" ) ) { // // TODO // } } else if (in.isStartElement()) { Location loc = in.getLocation(); LOG.error("Found unknown element '{}' at line {}, column {}, skipping.", new Object[] { in.getLocalName(), loc.getLineNumber(), loc.getColumnNumber() }); skipElement(in); } return null; }
From source file:org.eclipse.smila.datamodel.record.stax.RecordReader.java
/** * read an attribute from the XML stream and set it on the given {@link MObject}. * // w w w .j a v a 2 s .c o m * @param staxReader * XML stream * @param mobject * metadata object * @throws XMLStreamException * StAX error. */ private void readAttribute(final XMLStreamReader staxReader, final MObject mobject) throws XMLStreamException { final Attribute attribute = _recordFactory.createAttribute(); final String attributeName = staxReader.getAttributeValue(null, RecordParser.ATTRIBUTE_NAME); attribute.setName(attributeName); mobject.setAttribute(attributeName, attribute); staxReader.nextTag(); readAnnotations(staxReader, attribute); while (isStartTag(staxReader, RecordParser.TAG_LITERAL)) { readLiteralElement(staxReader, attribute); staxReader.nextTag(); } while (isStartTag(staxReader, RecordParser.TAG_OBJECT)) { staxReader.nextTag(); attribute.addObject(readMetadata(staxReader)); staxReader.nextTag(); } }