List of usage examples for javax.xml.stream XMLInputFactory newInstance
public static XMLInputFactory newInstance() throws FactoryConfigurationError
From source file:org.openhab.binding.dwdunwetter.internal.data.DwdWarningsData.java
/** * Refreshes the Warnings Data/*from ww w . ja v a 2s . co m*/ */ public boolean refresh() { String rawData = dataAccessCached.getValue(); if (StringUtils.isEmpty(rawData)) { logger.debug("No Data from Endpoint"); return false; } cityData.clear(); try { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLStreamReader reader = inputFactory.createXMLStreamReader(new StringReader(rawData)); XMLEventReader eventReader = inputFactory.createXMLEventReader(reader); DwdWarningData gemeindeData = new DwdWarningData(); boolean insideGemeinde = false; while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); if (!insideGemeinde && event.isStartElement()) { DwdXmlTag xmlTag = DwdXmlTag.getDwdXmlTag(event.asStartElement().getName().getLocalPart()); switch (xmlTag) { case WARNUNGEN_GEMEINDEN: gemeindeData = new DwdWarningData(); insideGemeinde = true; break; default: break; } } else if (insideGemeinde && event.isStartElement()) { DwdXmlTag xmlTag = DwdXmlTag.getDwdXmlTag(event.asStartElement().getName().getLocalPart()); switch (xmlTag) { case SEVERITY: gemeindeData.setSeverity(Severity.getSeverity(getValue(eventReader))); break; case DESCRIPTION: gemeindeData.setDescription(getValue(eventReader)); break; case EFFECTIVE: gemeindeData.setEffective(getTimestampValue(eventReader)); break; case EXPIRES: gemeindeData.setExpires(getTimestampValue(eventReader)); break; case EVENT: gemeindeData.setEvent(getValue(eventReader)); break; case STATUS: gemeindeData.setStatus(getValue(eventReader)); break; case MSGTYPE: gemeindeData.setMsgType(getValue(eventReader)); break; case HEADLINE: gemeindeData.setHeadline(getValue(eventReader)); break; case ONSET: gemeindeData.setOnset(getTimestampValue(eventReader)); break; case ALTITUDE: gemeindeData.setAltitude(getBigDecimalValue(eventReader)); break; case CEILING: gemeindeData.setCeiling(getBigDecimalValue(eventReader)); break; case IDENTIFIER: gemeindeData.setId(getValue(eventReader)); break; case INSTRUCTION: gemeindeData.setInstruction(getValue(eventReader)); break; case URGENCY: gemeindeData.setUrgency(Urgency.getUrgency(getValue(eventReader))); break; default: break; } } else if (insideGemeinde && event.isEndElement()) { DwdXmlTag xmlTag = DwdXmlTag.getDwdXmlTag(event.asEndElement().getName().getLocalPart()); switch (xmlTag) { case WARNUNGEN_GEMEINDEN: if (!gemeindeData.isTest() && !gemeindeData.isCancel()) { cityData.add(gemeindeData); } insideGemeinde = false; break; default: break; } } } } catch (XMLStreamException e) { logger.debug("Exception while parsing the XML Response", e); return false; } Collections.sort(cityData, new SeverityComparator()); return true; }
From source file:org.openhealthtools.openatna.archive.Loader.java
public void extract() throws Exception { File f = new File(archive); if (!f.exists() || f.length() == 0) { throw new Exception("archive does not exist"); }//from www.j a va2s . co m if (loadEntities) { InputStream min = ArchiveHandler.readEntities(f); if (min != null) { XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(min); loadEntities(reader); reader.close(); } else { log.info(" Input stream to " + f.getAbsolutePath() + " message file is null"); } } if (loadMessages) { InputStream min = ArchiveHandler.readMessages(f); if (min != null) { XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(min); loadMessages(reader); reader.close(); } else { log.info(" Input stream to " + f.getAbsolutePath() + " message file is null"); } } if (loadErrors) { InputStream min = ArchiveHandler.readErrors(f); if (min != null) { XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(min); loadErrors(reader); reader.close(); } else { log.info(" Input stream to " + f.getAbsolutePath() + " message file is null"); } } }
From source file:org.openhim.mediator.denormalization.EnrichRegistryStoredQueryActor.java
private String enrichStoredQueryXML(Identifier id, InputStream xml) throws XMLStreamException { XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(xml); StringWriter output = new StringWriter(); XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output); XMLEventFactory eventFactory = XMLEventFactory.newFactory(); String curSlot = null;//from ww w.j a va 2 s .com boolean patientIdSlot = false; while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); if (event.getEventType() == XMLEvent.START_ELEMENT) { StartElement elem = event.asStartElement(); if ("Slot".equals(elem.getName().getLocalPart())) { curSlot = elem.getAttributeByName(new QName("name")).getValue(); } else if ("Value".equals(elem.getName().getLocalPart()) && ParseRegistryStoredQueryActor.PATIENT_ID_SLOT_TYPE.equals(curSlot)) { patientIdSlot = true; writer.add(event); } } else if (event.getEventType() == XMLEvent.END_ELEMENT) { EndElement elem = event.asEndElement(); if (patientIdSlot && "Value".equals(elem.getName().getLocalPart())) { XMLEvent ecidEvent = eventFactory.createCharacters("'" + id.toString() + "'"); writer.add(ecidEvent); patientIdSlot = false; } } if (!patientIdSlot) { writer.add(event); } } writer.close(); return output.toString(); }
From source file:org.openhim.mediator.enrichers.IdentityEnricher.java
public String enrich(String xml) throws XMLStreamException { InputStream in = IOUtils.toInputStream(xml); XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(in); StringWriter output = new StringWriter(); XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output); while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); processXMLEvent(writer, event);// ww w . j a v a 2s.c o m } writer.close(); return output.toString(); }
From source file:org.openo.nfvo.emsdriver.collector.TaskThread.java
private boolean processCMXml(File tempfile, String nename, String type) { String csvpath = localPath + nename + "/" + type + "/"; File csvpathfile = new File(csvpath); if (!csvpathfile.exists()) { csvpathfile.mkdirs();/*from ww w. j av a 2s .c o m*/ } String csvFileName = nename + dateFormat.format(new Date()) + System.nanoTime(); String csvpathAndFileName = csvpath + csvFileName + ".csv"; BufferedOutputStream bos = null; FileOutputStream fos = null; try { fos = new FileOutputStream(csvpathAndFileName, false); bos = new BufferedOutputStream(fos, 10240); } catch (FileNotFoundException e1) { log.error("FileNotFoundException " + StringUtil.getStackTrace(e1)); } boolean FieldNameFlag = false; boolean FieldValueFlag = false; //line num int countNum = 0; String xmlPathAndFileName = null; String localName = null; String endLocalName = null; String rmUID = null; int index = -1; ArrayList<String> names = new ArrayList<String>();// colname LinkedHashMap<String, String> nameAndValue = new LinkedHashMap<String, String>(); FileInputStream fis = null; InputStreamReader isr = null; XMLStreamReader reader = null; try { fis = new FileInputStream(tempfile); isr = new InputStreamReader(fis, Constant.ENCODING_UTF8); XMLInputFactory fac = XMLInputFactory.newInstance(); reader = fac.createXMLStreamReader(isr); int event = -1; boolean setcolum = true; while (reader.hasNext()) { try { event = reader.next(); switch (event) { case XMLStreamConstants.START_ELEMENT: localName = reader.getLocalName(); if ("FieldName".equalsIgnoreCase(localName)) { FieldNameFlag = true; } if (FieldNameFlag) { if ("N".equalsIgnoreCase(localName)) { String colName = reader.getElementText().trim(); names.add(colName); } } if ("FieldValue".equalsIgnoreCase(localName)) { FieldValueFlag = true; } if (FieldValueFlag) { if (setcolum) { xmlPathAndFileName = this.setColumnNames(nename, names, type); setcolum = false; } if ("Object".equalsIgnoreCase(localName)) { int ac = reader.getAttributeCount(); for (int i = 0; i < ac; i++) { if ("rmUID".equalsIgnoreCase(reader.getAttributeLocalName(i))) { rmUID = reader.getAttributeValue(i).trim(); } } nameAndValue.put("rmUID", rmUID); } if ("V".equalsIgnoreCase(localName)) { index = Integer.parseInt(reader.getAttributeValue(0)) - 1; String currentName = names.get(index); String v = reader.getElementText().trim(); nameAndValue.put(currentName, v); } } break; case XMLStreamConstants.CHARACTERS: break; case XMLStreamConstants.END_ELEMENT: endLocalName = reader.getLocalName(); if ("FieldName".equalsIgnoreCase(endLocalName)) { FieldNameFlag = false; } if ("FieldValue".equalsIgnoreCase(endLocalName)) { FieldValueFlag = false; } if ("Object".equalsIgnoreCase(endLocalName)) { countNum++; this.appendLine(nameAndValue, bos); nameAndValue.clear(); } break; } } catch (Exception e) { log.error("" + StringUtil.getStackTrace(e)); event = reader.next(); } } if (bos != null) { bos.close(); bos = null; } if (fos != null) { fos.close(); fos = null; } String[] fileKeys = this.createZipFile(csvpathAndFileName, xmlPathAndFileName, nename); //ftp store Properties ftpPro = configurationInterface.getProperties(); String ip = ftpPro.getProperty("ftp_ip"); String port = ftpPro.getProperty("ftp_port"); String ftp_user = ftpPro.getProperty("ftp_user"); String ftp_password = ftpPro.getProperty("ftp_password"); String ftp_passive = ftpPro.getProperty("ftp_passive"); String ftp_type = ftpPro.getProperty("ftp_type"); String remoteFile = ftpPro.getProperty("ftp_remote_path"); this.ftpStore(fileKeys, ip, port, ftp_user, ftp_password, ftp_passive, ftp_type, remoteFile); //create Message String message = this.createMessage(fileKeys[1], ftp_user, ftp_password, ip, port, countNum, nename); //set message this.setMessage(message); } catch (Exception e) { log.error("" + StringUtil.getStackTrace(e)); return false; } finally { try { if (reader != null) { reader.close(); } if (isr != null) { isr.close(); } if (fis != null) { fis.close(); } if (bos != null) { bos.close(); } if (fos != null) { fos.close(); } } catch (Exception e) { log.error(e); } } return true; }
From source file:org.opentestsystem.delivery.AccValidator.handlers.ValidationHandler.java
public void validateXmlAccs(String filePath, String xsdPath) throws ValidationException { try {/*from w ww.j ava 2 s .com*/ InputStream xmlInput = new FileInputStream(new File(filePath)); InputStream xsdInput = new FileInputStream(new File(xsdPath)); String text = null; XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); XMLStreamReader reader = factory.createXMLStreamReader(xmlInput); boolean firstSelect = true; MasterResourceAccommodation masterResource = null; List<MasterResourceAccommodation> resourceFamiltyMasterResourceAccommodations = null; AccommodationText accommodationText = null; List<AccommodationText> accommodationTexts = null; AccommodationOption accommodationOption = null; List<AccommodationOption> accommodationOptions = null; AccFamilySubject familySubject = null; List<AccFamilySubject> familySubjects = null; ResourceFamily resourceFamily = null; List<String> grades = null; while (reader.hasNext()) { int Event = reader.next(); switch (Event) { case XMLStreamConstants.START_ELEMENT: { switch (reader.getLocalName()) { case "MasterResourceFamily": _masterResourceAccommodations = new ArrayList<MasterResourceAccommodation>(); break; case "SingleSelectResource": masterResource = new MasterResourceAccommodation(); accommodationTexts = new ArrayList<AccommodationText>(); accommodationOptions = new ArrayList<AccommodationOption>(); break; case "MultiSelectResource": masterResource = new MasterResourceAccommodation(); accommodationTexts = new ArrayList<AccommodationText>(); accommodationOptions = new ArrayList<AccommodationOption>(); break; case "EditResource": masterResource = new MasterResourceAccommodation(); accommodationTexts = new ArrayList<AccommodationText>(); accommodationOptions = new ArrayList<AccommodationOption>(); break; case "ResourceFamily": masterResource = new MasterResourceAccommodation(); familySubjects = new ArrayList<AccFamilySubject>(); resourceFamily = new ResourceFamily(); accommodationTexts = new ArrayList<AccommodationText>(); accommodationText = new AccommodationText(); resourceFamiltyMasterResourceAccommodations = new ArrayList<MasterResourceAccommodation>(); grades = new ArrayList<String>(); break; case "Subject": familySubject = new AccFamilySubject(); break; case "Selection": if (firstSelect) { masterResource.setHeader(accommodationTexts); accommodationOption = new AccommodationOption(); accommodationTexts = new ArrayList<AccommodationText>(); } else { accommodationOption = new AccommodationOption(); } firstSelect = false; break; case "Text": accommodationText = new AccommodationText(); break; default: break; } break; } case XMLStreamConstants.CHARACTERS: { String nodeValue = getContents(reader.getText()); if (nodeValue.length() > 0) { text = nodeValue; } break; } case XMLStreamConstants.END_ELEMENT: { switch (reader.getLocalName()) { case "Code": if (accommodationOption == null) { if (familySubject == null) { masterResource.setCode(text); } else { familySubject.setCode(text); } } else { accommodationOption.setCode(text); } text = null; break; case "Order": if (accommodationOption == null) { masterResource.setOrder(Integer.valueOf(text)); } else { accommodationOption.setOrder(Integer.valueOf(text)); } text = null; break; case "MutuallyExclusive": accommodationOption.setMutuallyExclusive(true); text = null; break; case "DefaultSelection": masterResource.setDefaultSelection(text); text = null; break; case "Disabled": masterResource.setDisabled(true); text = null; break; case "Language": accommodationText.setLanguage(text); text = null; break; case "Label": accommodationText.setLabel(text); text = null; break; case "Description": accommodationText.setDescription(text); text = null; break; case "Message": accommodationText.setMessage(text); text = null; break; case "Text": accommodationTexts.add(accommodationText); text = null; break; case "Selection": accommodationOption.setText(accommodationTexts); accommodationOptions.add(accommodationOption); accommodationOption = new AccommodationOption(); accommodationTexts = new ArrayList<AccommodationText>(); text = null; break; case "SingleSelectResource": masterResource.setResourceType("SingleSelectResource"); if (accommodationTexts.size() > 0) { masterResource.setHeader(accommodationTexts); } masterResource.setOptions(accommodationOptions); if (resourceFamily == null) { _masterResourceAccommodations.add(masterResource); } else { resourceFamiltyMasterResourceAccommodations.add(masterResource); } masterResource = null; accommodationOption = null; accommodationOption = null; firstSelect = true; text = null; break; case "MultiSelectResource": masterResource.setResourceType("MultiSelectResource"); if (accommodationTexts.size() > 0) { masterResource.setHeader(accommodationTexts); } masterResource.setOptions(accommodationOptions); if (resourceFamily == null) { _masterResourceAccommodations.add(masterResource); } else { resourceFamiltyMasterResourceAccommodations.add(masterResource); } masterResource = null; accommodationOption = null; accommodationOption = null; firstSelect = true; text = null; break; case "EditResource": masterResource.setResourceType("EditResource"); if (accommodationTexts.size() > 0) { masterResource.setHeader(accommodationTexts); } masterResource.setOptions(accommodationOptions); if (resourceFamily == null) { _masterResourceAccommodations.add(masterResource); } else { resourceFamiltyMasterResourceAccommodations.add(masterResource); } masterResource = null; accommodationOption = null; accommodationOption = null; firstSelect = true; text = null; break; case "ResourceFamily": resourceFamily.setSubject(familySubjects); resourceFamily.setGrade(grades); resourceFamily.setMasterResourceAccommodation(resourceFamiltyMasterResourceAccommodations); _resourceFamilies.add(resourceFamily); familySubjects = null; grades = null; resourceFamily = null; resourceFamiltyMasterResourceAccommodations = null; text = null; break; case "Name": familySubject.setName(text); text = null; break; case "Subject": familySubjects.add(familySubject); familySubject = null; text = null; break; case "Grade": grades.add(text); text = null; break; } break; } } } validateRules(_masterResourceAccommodations, _resourceFamilies); // validation against xsd xmlInput = new FileInputStream(new File(filePath)); xsdInput = new FileInputStream(new File(xsdPath)); validateAgainstXSD(xmlInput, xsdInput); } catch (IOException e) { throw new ValidationException("failed", "The xml could not be parsed into objects. The error message is:" + e.getMessage()); } catch (XMLStreamException e) { throw new ValidationException("failed", "The xml could not be parsed into objects. The error message is:" + e.getMessage()); } }
From source file:org.orbisgis.core.layerModel.mapcatalog.RemoteMapCatalog.java
/** * Request the workspaces synchronously. * This call may take a long time to execute. * @return A list of workspaces/*from w ww. ja va2 s . c o m*/ * @throws IOException The request fail */ public List<Workspace> getWorkspaces() throws IOException { List<Workspace> workspaces = new ArrayList<Workspace>(); // Construct request URL requestWorkspacesURL = new URL(RemoteCommons.getUrlWorkspaceList(cParams)); // Establish connection HttpURLConnection connection = (HttpURLConnection) requestWorkspacesURL.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(cParams.getConnectionTimeOut()); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException(I18N.tr("HTTP Error {0} message : {1}", connection.getResponseCode(), connection.getResponseMessage())); } // Read the response content BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream(), RemoteCommons.getConnectionCharset(connection))); //"Content-Type" "text/xml; charset=utf-8" XMLInputFactory factory = XMLInputFactory.newInstance(); // Parse Data XMLStreamReader parser; try { parser = factory.createXMLStreamReader(in); // Fill workspaces parseXML(workspaces, parser); parser.close(); } catch (XMLStreamException ex) { throw new IOException(I18N.tr("Invalid XML content"), ex); } return workspaces; }
From source file:org.orbisgis.core.layerModel.mapcatalog.Workspace.java
/** * Add a mapcontext to the workspace//from w w w . j av a 2s. com * @param mapContext * @return The ID of the published map context * @throws IOException */ public int publishMapContext(MapContext mapContext, Integer mapContextId) throws IOException { // Construct request URL requestWorkspacesURL; if (mapContextId == null) { // Post a new map context requestWorkspacesURL = new URL(RemoteCommons.getUrlPostContext(cParams, workspaceName)); } else { // Update an existing map context requestWorkspacesURL = new URL(RemoteCommons.getUrlUpdateContext(cParams, workspaceName, mapContextId)); } // Establish connection HttpURLConnection connection = (HttpURLConnection) requestWorkspacesURL.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setConnectTimeout(cParams.getConnectionTimeOut()); connection.addRequestProperty("Content-Type", "text/xml"); OutputStream out = connection.getOutputStream(); mapContext.write(out); // Send map context out.close(); // Get response int responseCode = connection.getResponseCode(); if (!((responseCode == HttpURLConnection.HTTP_CREATED && mapContextId == null) || (responseCode == HttpURLConnection.HTTP_OK && mapContextId != null))) { throw new IOException(I18N.tr("HTTP Error {0} message : {1} with the URL {2}", connection.getResponseCode(), connection.getResponseMessage(), requestWorkspacesURL)); } if (mapContextId == null) { // Get response content BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), RemoteCommons.getConnectionCharset(connection))); XMLInputFactory factory = XMLInputFactory.newInstance(); // Parse Data XMLStreamReader parser; try { parser = factory.createXMLStreamReader(in); // Fill workspaces int resId = parsePublishResponse(parser); parser.close(); return resId; } catch (XMLStreamException ex) { throw new IOException(I18N.tr("Invalid XML content"), ex); } } else { return mapContextId; } }
From source file:org.orbisgis.core.layerModel.mapcatalog.Workspace.java
/** * Retrieve the list of MapContext linked with this workspace * This call may take a long time to execute. * @return//from w w w. j av a 2 s . c om * @throws IOException Connection failure */ public List<RemoteMapContext> getMapContextList() throws IOException { List<RemoteMapContext> contextList = new ArrayList<RemoteMapContext>(); // Construct request URL requestWorkspacesURL = new URL(RemoteCommons.getUrlContextList(cParams, workspaceName)); // Establish connection HttpURLConnection connection = (HttpURLConnection) requestWorkspacesURL.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(cParams.getConnectionTimeOut()); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException(I18N.tr("HTTP Error {0} message : {1}", connection.getResponseCode(), connection.getResponseMessage())); } XMLInputFactory factory = XMLInputFactory.newInstance(); // Read the response content BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream(), RemoteCommons.getConnectionCharset(connection))); // Parse Data XMLStreamReader parser; try { parser = factory.createXMLStreamReader(in); // Fill workspaces parseXML(contextList, parser); parser.close(); } catch (XMLStreamException ex) { throw new IOException(I18N.tr("Invalid XML content"), ex); } return contextList; }
From source file:org.overlord.commons.auth.filters.SamlBearerTokenAuthFilter.java
/** * Handles SAML Bearer token authentication. Assumes the password is an * encoded SAML assertion./*from w w w . java 2s. c om*/ * @param assertionData * @param request * @throws IOException */ protected SimplePrincipal doSamlLogin(String assertionData, HttpServletRequest request) throws IOException { try { Document samlAssertion = DocumentUtil.getDocument(assertionData); SAMLAssertionParser parser = new SAMLAssertionParser(); XMLEventReader xmlEventReader = XMLInputFactory.newInstance() .createXMLEventReader(new StringReader(assertionData)); Object parsed = parser.parse(xmlEventReader); AssertionType assertion = (AssertionType) parsed; SAMLBearerTokenUtil.validateAssertion(assertion, request, allowedIssuers); if (signatureRequired) { KeyPair keyPair = getKeyPair(assertion); if (!SAMLBearerTokenUtil.isSAMLAssertionSignatureValid(samlAssertion, keyPair)) { throw new IOException(Messages.getString("SamlBearerTokenAuthFilter.InvalidSig")); //$NON-NLS-1$ } } return consumeAssertion(assertion); } catch (IOException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } }