Showing posts from March, 2013

How to validate XML file against XSD in Java

private boolean validateAgainstXSD(InputStream xml, InputStream xsd) { try { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(xsd)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(xml)); return true; } catch(Exception ex) { return false; } }

How to return the root element as a JAXB object from marshaled XML file

public static Object getRootElement(String xmlpath, String package_names){ Object object = null; try { JAXBContext context = JAXBContext.newInstance(package_names); File file = new File(xmlpath); FileInputStream fileInputStream = new FileInputStream(file); Unmarshaller unmarshaller = context.createUnmarshaller(); object = unmarshaller.unmarshal(file); if (object instanceof javax.xml.bind.JAXBElement) { javax.xml.bind.JAXBElement root = (javax.xml.bind.JAXBElement)object; object = root.getValue(); } } catch (JAXBException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } return object; }

How to get the path of the WEB-INF or any folder under it in Struts

You may have a folder for resources under the WEB-INF of your Struts application or even any Java web application. For example if you have a folder called "resources" which is under the WEB-INF and you would like to retrieve the absolute path so you can read or write on it. You can do this by:- First: Get the ServletContext through the ServletActionContext.getServletContext(). ServletContext servletContext = ServletActionContext.getServletContext(); Second: Get the path of the WEB-INF or the "resources" folder. //path of the Web Content String path1 = servletContext.getRealPath(""); //path of the WEB-INF String path2 = servletContext.getRealPath("/WEB-INF"); //path of the folder "resources" under the WEB-INF String path3 = servletContext.getRealPath("/WEB-INF/resources"); The good thing is that the ServletContext is an interface in Java web API which means that there should be an implementation for this interface by

Lambda and Parallelism in Java 8 by Mike Keith

In the first day of JDC2013 , Mike Keith has presented two sessions the first one was " Java EE 7, The new and shiny bits " and the second one was " Creating a configuration standard for Java EE ". The good thing is that he finished the second session earlier by 30 minutes and he asked whether to start talking about another interesting topic or not. The attendees agreed to continue talking about another useful and interesting topic. It was about "Lambda and Parallelism in Java 8". It was really interesting topic and I got to say that there is a nice change will happen on how we code Java in certain cases :D. For more information about Lambda and Parallelism you can check this article on DZone .