xml validation using xsd in jaxb - xml-parsing

I have an xml.
I have created one XSD for the xml.
I want to write a prog to validate the xml against xsd.
I wrote a prog and got individual values am setting.
But is there a way, i can give the xml file as input and could see if the xml is valid against the XSD?
Thanks,
Nini

This is an example of xml validation with XSD.
public static boolean validate() {
Source xmlFile = null;
File schemaFile;
SchemaFactory schemaFactory;
Schema schema;
try {
schemaFile = new File(xsdFileName);
xmlFile = new StreamSource(new File(xmlFileName));
schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schema = schemaFactory.newSchema(schemaFile);
Validator validator = schema.newValidator();
validator.validate(xmlFile);
System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException | IOException e) {
System.out.println(xmlFile.getSystemId() + " is NOT valid");
System.out.println("Reason: " + e.getLocalizedMessage());
return false;
}
return true;
}

Related

JDOM XML Parsing: not entering for loop

I want to parse and print XML tags using jdom2 (not w3c/xml.sax)
the root element is getting printed and the debug till before for loop is also there, but after that, there's blank, no syntax error, am I missing something in the for loop?
this is what my main looks like in the message reader class
public class XMLReaderDOM {
public static void main(String[] args) {
System.out.println("Starting out now");
try {
SAXBuilder builder = new SAXBuilder();
File xmlFile = new File("file.xml");
Document doc = (Document) builder.build(xmlFile);
Element root = doc.getRootElement();
System.out.println("Document built");
List < Element > listGrpHdr = root.getChildren("GrpHdr");
List < GrpHdr > grphdrList = new ArrayList <>();
System.out.println("root element:" + doc.getRootElement().getName());
System.out.println("Right before for");
for (Element grphdrElement: listGrpHdr){
GrpHdr grphdr = new GrpHdr();
System.out.println("before getting our elements");
grphdr.setGrp_id(grphdrElement.getChildText("grp_id"));
grphdr.setCreationDateTime(grphdrElement.getChildText("creationDateTime"));
grphdr.setMessageType(grphdrElement.getChildText("messageType"));
grphdr.setGrp_hdr_xml(grphdrElement.getChildText("grp_hdr_xml"));
grphdrList.add(grphdr);
}
grphdrList.forEach(grphdr->{
System.out.println(grphdr.toString());
});
} catch (Exception e) {
e.printStackTrace();
}
}
}

Export data to excel with EPPlus and WebApi

I'm trying to export a list, but when i open the file download it just shows a bunch of characteres that don't make sense (kinda looks like machine language). I've looked at some codes here and all of them are similar to mine, what am I missing?
Here's my code:
The method I call:
[HttpGet]
public HttpResponseMessage Get()
{
HttpResponseMessage response;
response = Request.CreateResponse(HttpStatusCode.OK);
MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue("application/ms-excel");
response.Content = new StreamContent(GetExcelSheet());
response.Content = response.Content;
response.Content.Headers.ContentType = mediaType;
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "PivotGrid_Orders.xls";
return response;
}
The method that format cells:
public MemoryStream GetExcelSheet()
{
using (var package = new ExcelPackage())
{
var worksheet = package.Workbook.Worksheets.Add("Orders");
//worksheet.Cells["A1"].LoadFromCollection()
worksheet.Cells["A1"].LoadFromCollection(Orders(), false);
package.Save();
var stream = new MemoryStream(package.GetAsByteArray()); //capacidade
return stream;
}
}
The list i've created to test:
public List<ExListModel> Orders()
{
List<ExListModel> lst = new List<ExListModel>();
orders.Add(new ExListModel{ Nome = "Developer"});
return lst;
}
As I didn't know EPPlus, I googled it, and its Github page states it produces Open XML excel files (.xlsx). You produce the file with an extension and mimetype of the old binary excel filetype. Change the contenttype to application/vnd.openxmlformats-officedocument.spreadsheetml.sheet and the filename extension to xlsx.

change default format dataExporter in Primefaces

I want to use to generate a pdf dataexporter, use the method preprocessor to insert some content. By giving the type letter size page assimilates well as formats of texts. Then make a page break to put the chart on a new page, right there is the problem that generates the second page with other size and also find a way to change the font size of the text of the exported table.
<h:commandLink>
<p:graphicImage value="/images/pdf.png"/>
<p:dataExporter type="pdf" target="dataTableAddDetalles" fileName="pdf" preProcessor="#{serviciosMB.preProcessPDF}"/>
</h:commandLink>
backing bean
public void preProcessPDF(Object document) throws Exception {
try {
Document pdf = (Document) document;
pdf.open();
pdf.setPageSize(PageSize.LETTER);
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String logo = servletContext.getRealPath("") + File.separator + "images" + File.separator + "header.gif";
// pdf.add(Image.getInstance(logo));
pdf.add(new Paragraph("EMNI", FontFactory.getFont(FontFactory.HELVETICA, 22, Font.BOLD, new Color(0, 0, 0))));
SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
pdf.add(new Phrase("Fecha: " + formato.format(new Date())));
pdf.newPage();
} catch (Exception e) {
//JsfUtil.addErrorMessage(e, e.getMessage());
}
}
You can't do what you want using dataexporter, you need to change your code to:
<h:commandLink actionListener="#{serviciosMB.createPDF}">
<p:graphicImage value="/images/pdf.png" />
</h:commandLink>
And your managed bean:
public void createPDF() {
try { //catch better your exceptions, this is just an example
FacesContext context = FacesContext.getCurrentInstance();
Document document = new Document();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
if (!document.isOpen()) {
document.open();
}
PdfPTable pdfTable = exportPDFTable();
document.add(pdfTable);
//Keep modifying your pdf file (add pages and more)
document.close();
String fileName = "PDFFile";
writePDFToResponse(context.getExternalContext(), baos, fileName);
context.responseComplete();
} catch (Exception e) {
//e.printStackTrace();
}
}
exportPDFTable method:
private PdfPTable exportPDFTable() {
int numberOfColumns = 1;
itemOfList item = null;
PdfPTable pdfTable = new PdfPTable(numberOfColumns);
pdfTable.setWidthPercentage(100);
BaseFont helvetica = null;
try {
helvetica = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
} catch (Exception e) {
//font exception
}
Font font = new Font(helvetica, 8, Font.NORMAL);
pdfTable.addCell(new Paragraph("columnName", font));
for (int i = 0; i < lstPdfTable.size(); i++) { //lstPdfTable is the list from your datatable. A List of "itemOfList" type
item = new itemOfList();
item = lstPdfTable.get(i);
//pdfTable.addCell(new Paragraph('any_string_field', font));
pdfTable.addCell(new Paragraph(item.getStringField(), font));
}
return pdfTable;
}
and writePDFToResponse method is:
private void writePDFToResponse(ExternalContext externalContext, ByteArrayOutputStream baos, String fileName) {
try {
externalContext.responseReset();
externalContext.setResponseContentType("application/pdf");
externalContext.setResponseHeader("Expires", "0");
externalContext.setResponseHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
externalContext.setResponseHeader("Pragma", "public");
externalContext.setResponseHeader("Content-disposition", "attachment;filename=" + fileName + ".pdf");
externalContext.setResponseContentLength(baos.size());
OutputStream out = externalContext.getResponseOutputStream();
baos.writeTo(out);
externalContext.responseFlushBuffer();
} catch (Exception e) {
//e.printStackTrace();
}
}
The primefaces documentation (as of 4.0) does not mention any ability to write a custom data exporter, only pre & post processors, which in the case of PDF prevents you from doing extensive modifications to data, etc.
But what you can do is create a package in your project called
org.primefaces.component.export
and copy ExporterFactory.java from primefaces source.
You can then replace the original PDFExporter call with your own implementation.
The exporter implementation is fairly simple. It uses iText library (although an outdated version) and you can easily extend it to your needs.
An obvious problem with this approach is that you may have to be extra careful when (and if) you are updating your primefaces library in the future.

How to tell if a segment actually exists in a HL7 message via NHAPI?

I have an SIU S12 message that does not contain a PV2 segment. However, when I get the parsed message from NHAPI, the parent group for PV2, the SIU_S12_PATIENT group, return 1 for currentReps ("PV2"), which means the PV2 is present.
var parser = new NHapi.Base.Parser.PipeParser();
var parsedMessage = parser.Parse(message) as NHapi.Model.V231.Message.SIU_S12;
var patientGroup=parsedMessage.GetPATIENT(0);
// This call should not create the segment if it does not exist
int pv2Count=patientGroup.currentReps("PV2");
//pv2Count is 1 here despite no PV2 segment exists in the message
//also Both GetAll("PV2") and SegmentFinder say the PV2 segment is present
//DG1RepetitionsUsed is also 1 despite no DG1 segment is present in the message
I am trying to avoid writing code to evaluate every field in the segment. PV2 is just an example - there are a lot more segments that could be missing from the message source.
I am using NHAPI v 2.4, the latest version.
Update: following Tyson's suggestion I come up with this method;
var parser = new NHapi.Base.Parser.PipeParser();
var parsedMessage = parser.Parse(message) as NHapi.Model.V231.Message.SIU_S12;
var encodingChars = new NHapi.Base.Parser.EncodingCharacters('|', null);
var patientGroup = parsedMessage.GetPATIENT(0);
var dg1 = (NHapi.Model.V231.Segment.DG1) (patientGroup.GetStructure("DG1"));
string encodedDg1 = NHapi.Base.Parser.PipeParser.Encode(dg1, encodingChars);
bool dg1Exists = string.Compare(encodedDg1,
"DG1", StringComparison.InvariantCultureIgnoreCase)==0;
easiest thing that I have found to do is to determine if a segment is in a message is to search the actual string of the message for the segment name plus a pipe. So, for example
if(message.Contains("PV2|"))
{
//do something neat
}
From my experience, it is either that, or examining every sub-field under the segment to see if there is a value.
EDIT
I found another way to check that might work a little better. The PipeParser class has a couple of static methods on it that takes in ISegment, IGroup, and IType objects that will return a string representation of the object NHapi reference.
Sample code:
string validTestMessages =
"MSH|^~\\&|ADT1|MCM|LABADT|MCM|198808181126|SECURITY|ADT^A01|MSG00001|P|2.6\r" +
"EVN|A01-|198808181123\r" +
"PID|||PID1234^5^M11^HBOC^CPI^HV||JONES^WILLIAM^A^III||19610615000000|M||2106-3|1200 N ELM STREET^^GREENSBORO^NC^27401-1020|GL||||S||S|123456789|9-87654^NC\r" +
"PV1|1|I|||||TEST^TEST^TEST||||||||||||||||||||||||||||||||||||||||||||\r";
var encodingChars = new EncodingCharacters('|', null);
PipeParser parser = new PipeParser();
var message = parser.Parse(validTestMessages);
PV1 pv1 = (PV1)message.GetStructure("PV1");
var doctor = pv1.GetAttendingDoctor(0);
string encodedMessage = PipeParser.Encode(pv1, encodingChars);
Console.WriteLine(encodedMessage);
encodedMessage = PipeParser.Encode(doctor, encodingChars);
Console.WriteLine(encodedMessage);
Output:
PV1|1|I|||||TEST^TEST^TEST
TEST^TEST^TEST
if there is no segment or the item is empty, then the PiperParser will return an empty string.
You can read segment line by line to a file and add in hl7 Record object and check segment exist or not.
package com.sachan.ranvijay#gmail.com.hl7.msg;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import org.nule.lighthl7lib.hl7.Hl7Record;
import org.nule.lighthl7lib.hl7.Hl7Segment;
import com.stpl.hl7.dto.HL7PatientInfoDTO;
/**
* This class will parse the hl7 message. it can accept message file in the format of java.io.file
* as well as String. Its Uses org.nule.lighthl7lib.hl7.Hl7Record
* as a main component.
* #author Ranvijay.Singh
*
*/
public class PrepareHL7Message {
StringBuilder hl7Msg = new StringBuilder();
Hl7Record record = null;
public PrepareHL7Message(File file) throws Exception {
BufferedReader reader = new BufferedReader(
new FileReader(file));
String str = reader.readLine();
while (str != null) {
hl7Msg.append(str).append("\r");
str = reader.readLine();
}
reader.close();
try{
record = new Hl7Record(hl7Msg.toString());
}catch (Exception e) {
throw e;
}
}
public PrepareHL7Message(String msg) throws Exception {
try{
record = new Hl7Record(msg);
}catch (Exception e) {
throw e;
}
}
private HL7PatientInfoDTO getPatientOrderingPhysician(HL7PatientInfoDTO padto) {
Hl7Segment seg = record.getSegment("PV1");
if(seg!=null)
padto.setOrderingPhysician(seg.field(7).toString());
return padto;
}
}
//DTO.............
package com.sachan.ranvijay#gmail.com.hl7.dto;
public class HL7PatientInfoDTO {
/**
* maped with PV1-7
*/
private String orderingPhysician;
/**
* #return the orderingPhysician
*/
public String getOrderingPhysician() {
return orderingPhysician;
}
/**
* #param orderingPhysician the orderingPhysician to set
*/
public void setOrderingPhysician(String orderingPhysician) {
this.orderingPhysician = orderingPhysician;
}
}

Parsing arabic text using Sax produce?

I'm developing LWUIT project using netbeans to run on Blackberry environment. this project will read data from .net web service, I used ksoap2 and Sax Parser. Parser looks like that
public static Vector ParseSAX(String input ,final String[] elements) {
final Vector values = new Vector();
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
for(int u = 0;u < elements.length;u++){
if (qName.equalsIgnoreCase(elements[u].toString())) {
flag = true;
}
}
}
public void endElement(String uri, String localName,
String qName) throws SAXException {
}
public void characters(char ch[], int start, int length) throws SAXException {
if (flag) {
values.addElement(new String(ch, start, length));
flag = false;
}
}
};
InputStreamReader inputStream = new InputStreamReader(new ByteArrayInputStream(input.getBytes()), "UTF-8");
InputSource is = new InputSource();
is.setEncoding("UTF-8");
is.setCharacterStream(inputStream);
saxParser.parse(is, handler);
} catch (Exception e) {
e.printStackTrace();
}
return values;
}
I cared to parse arabic characters.
By the way, I converted the project encoding to UTF-8 and changed javac.encoding=UTF-8 in project.properties and in private.properties I added runtime.encoding=UTF-8
if I put this code in isolated project, it runs fine.
If I added in BB project or web project, will produce?
I do not know what can I do?

Resources