Loading file from /src/main/resources - java

I have an XML schema file in /src/main/resources/vast_2.0.1.xsd.
I need to load it and use it to validate my XML file.
This is what's happening:
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
File schemaFile = new File("/src/main/resources/vast_2.0.1.xsd");
try {
Schema schema = scehmaFactory.newSchema(schemaFile);
Validator validator = schema.newValidator();
Source sourceXMLFile = new StreamSource(validationRequest.xmlInputStream);
validator.validate(sourceXMLFile);
} catch (SAXException e) {
responseEngine.addFailedCheck("NON_VAST_COMPLIANT", "Does not meet VAST 2.0 XML schema specifications");
} catch (IOException e) {
// should not reach here
}
For some reason, after the File schemaFile = new File... line, it ceases to run (using print statements). Am I loading the file incorrectly?

I assume from your directory structure that you are using maven. In maven project, src/main/resources is always in the classpath so you need to specify just the file name without the path. Try this:
File schemaFile = new File("vast_2.0.1.xsd");

Related

Apache Configuration cannot load file Properties - returns null

I gave Apache Configuration2 a try.
I try to load a path from properties file:
String configFileName = getConfigFileName();
Configurations configs = new Configurations();
try {
File configFile = new File(configFileName);
String configFileStr = FileUtils.readFileToString(configFile, StandardCharsets.UTF_8); // content is loaded correctly
config = configs.properties(configFile);
config = configs.properties("src/main/resources/config.properties");
baseStoreDir = config.getString("baseStoreDir", baseStoreDir);
} catch (ConfigurationException cex) {
log.fatal(...);
} catch (IOException ex) {
log.fatal(...);
}
With this code I cannot get property value. Just as file or property is not found.
config.getString("baseStoreDir");
This returns null.
Why I cannot get the property?
The issue was in properties file. Directory path there was in format:
baseStoreDir = .\src\main\resources\
When I converted it to:
baseStoreDir = ./src/main/resources/
it worked.
Apache Configuration2 has very strange "logic" of reading resource files as Java files :P

Strange JAXB Exception after GIT merge - SAXParseException - well-formed character data?

After doing a GIT rebase, out of nowhere, I started receiving this exception:
by: org.xml.sax.SAXParseException: "The content of elements must consist of well-formed character data or markup"
The Java code simply tries to unmarshall an xml file to a jaxb object. Something like this:
...
FGIXmlValidationEventCollector collector = new FGIXmlValidationEventCollector();
Unmarshaller unmarshaller = null;
try {
unmarshaller = context.createUnmarshaller();
unmarshaller.setSchema(getSchema());
unmarshaller.setEventHandler(collector);
} catch (JAXBException e) {
throw new FGIXmlException(e);
} catch (SAXException e) {
throw new FGIXmlException(e);
}
public Schema getSchema() throws SAXException {
SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
URL schemaLocation = getClass().getResource("/config/xsd/fgi.xsd");
**return schemaFactory.newSchema(schemaLocation); // exception is thrown here!!!**
}
I'm clueless. There was no code change that justifies this. This code has worked for many years. I don't know why after some trivial git pull/rebase I ended up with this behavior. By the way, there's no apparent problem whatsoever with the XML file that I want to unmarshall. It's an UFT-8 xml file. I've even tried changing the encoding but to no avail.
Any ideas?
Thank you

How to get a File reference from within a JAR

First of all I would like to add that I probably have tried every proposed solution on SO about this issue but still cant get it working.
So this is my problem...
I have an application for parsing XML files. I select an xml file (source) and I validate it against an xsd (this is the file inside my JAR that I cant access). Running the code from within my IDE works fine:
xsd = new File(getClass().getResourceAsStream("xsds/2014/schema.xsd").getFile());
System.out.println(xsd.getAbsolutePath());
//returns: C:\Users\xxx\Desktop\Documents\NetBeansProjects\JavaXMLValidator\build\classes\app\xsds\2014\schema.xsd
But when I build by application to JAR file and I run it I cant get the reference to that file.
When I run the application from within my JAR i get this:
//returns: C:\Users\xxx\Desktop\Documents\NetBeansProjects\JavaXMLValidator\dist\file:C:\Users\xxx\Desktop\Documents\NetBeansProjects\JavaXMLValidator\dist\JavaXMLValidator.jar!\app\xsds\2014\schema.xsd
The path looks ok (i think) but I cant get a correct reference to my file in the code:
Source schemaFile = new StreamSource(xsd);
Schema schema = null;
try {
schema = factory.newSchema(schemaFile);
} catch (SAXException ex) {
JOptionPane.showMessageDialog(null, "Invalid XML Schema Selected!!!\n Exception: "+this.getStackTraceString(ex," "));
return;
}
I get the exception:
SAXParseException: schema_reference.4: Failed to read schema document
'C:\Users\xxx\Desktop\Documents\NetBeansProjects\JavaXMLValidator\dist\file:C:\Users\xxx\Desktop\Documents\NetBeansProjects\JavaXMLValidator\dist\JavaXMLValidator.jar!\app\xsds\2014\schema.xsd',
because 1)could not find the document;
2)the document could not be read;
3)the root element of the document is not <xsd:schema>
........
Can anyone suggest a way that I could have a correct reference to the xsd file withing the JAR?
Thanks a lot for any help
As MadProgrammer says, use the URL:
URL xsd = getClass().getResource("xsds/2014/schema.xsd");
Schema schema = null;
try {
schema = factory.newSchema(xsd);
} catch (SAXException ex) {
JOptionPane.showMessageDialog(null, "Invalid XML Schema Selected!!!\n Exception: "+this.getStackTraceString(ex," "));
return;
}
For example there is a project with such structure:
testproject
xsdfolder
schema.xsd
javaclassfolder
SomeClass.java
public static class SomeClass {
public static URL getLocalXsd() throws MalformedURLException {
URL baseUrl = SomeClass.class.getResource(SomeClass.class.getSimpleName() + ".class");
return new URL(baseUrl, "../xsdfolder/schema.xsd");
}
}

Reading Properties file inside conf folder

I have a properties file which is located under conf folder. conf folder is under the project root directory. I am using the following code.
public class PropertiesTest {
public static void main(String[] args) {
InputStream inputStream = PropertiesTest.class
.getResourceAsStream("/conf/sampleprop.conf");
Properties prop = new Properties();
try {
prop.load(inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(prop.getProperty("TEST"));
}
}
But I get nullpointer exception.
I have tried using
InputStream inputStream = PropertiesTest.class
.getResourceAsStream("./conf/sampleprop.conf");
and
InputStream inputStream = PropertiesTest.class
.getResourceAsStream("conf/sampleprop.conf");
But all result in nullpointer exception.
Can anyone please help.
Thanks in advance
Try to recover your working directory first:
String workingDir = System.getProperty("user.dir");
System.out.println("Current working dir: " + workingDir);
and then is simple:
Properties propertiesFile = new Properties();
propertiesFile.load(new FileInputStream(workingDir+ "/yourFilePath"));
String first= propertiesFile.getProperty("myprop.first");
Regards, fabio
The getResourceAsStream() method tries to locate and load the resource using the ClassLoader of the class it is called on. Ideally it can locate the files only the class folders .. Rather you could use FileInputStream with relative path.
EDIT
if the conf folder is under src, then you still be able to access with getResourceAsStream()
InputStream inputStream = Test.class
.getResourceAsStream("../conf/sampleprop.conf");
the path would be relative to the class from you invoke getRes.. method.
If not
try {
FileInputStream fis = new FileInputStream("conf/sampleprop.conf");
Properties prop = new Properties();
prop.load(fis);
System.out.println(prop.getProperty("TEST"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
NOTE: this will only work if it is Stand alone application/in eclipse. This will not work if its web based (as the root will be Tomcat/bin, for eg)
I would suggest to copy the configuration file at designated place, then you can acess at ease. At certain extent 'System.getProperty("user.dir")' can be used if you are always copying the file 'tomcat` root or application root. But if the files to be used by external party, ideal to copy in a configurable folder (C:\appconf)
Your code works like a charm! But you might have to add the project root dir to your classpath.
If you work with Maven, place your configuration in src/main/resources/conf/sampleprop.conf
When invoking java directly add the project root dir with the java -classpath parameter. Something like:
java -classpath /my/classes/dir:/my/project/root/dir my.Main

How do I validate an XML file against an XSD through https URL?

I would like to validate an XML file using a schema located at a secure https site. How do I tell the validator to except a self-signed certificate or use an https URL? I have a file called test.xml and a schema located at https://localhost:1234/module/testschema.xsd. I'm using the same code found here. If I use a regular URL (http://localhost/module/testschema.xsd), it works great. If I substitute with an https URL, then I get this error:
schema_reference.4: Failed to read schema document 'https://localhost:1234/module/testschema.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
Copied Code:
public boolean validateFile(String xml, String strSchemaLocation)
{
Source xmlFile = null;
try {
URL schemaFile = new URL(strSchemaLocation);
xmlFile = new StreamSource(new File(xml));
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(schemaFile);
Validator validator = schema.newValidator();
validator.validate(xmlFile);
System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
System.out.println(xmlFile.getSystemId() + " is NOT valid");
System.out.println("Reason: " + e.getLocalizedMessage());
return false;
} catch (IOException ioe) {
System.out.println("IOException");
return false;
}
return true;
}
This has very little to to do with schema validation. Your problem is that you need to establish an HTTPS connection and trust a self-signed certificate. See How can I use different certificates on specific connections? or google around for that.
I don't think you'll be able to use the SchemaFactory.newSchema factory method that takes a File, so just use the one that takes a StreamSource:
URL schemaFile = new URL(strSchemaLocation);
HttpsURLConnection schemaConn = (HttpsURLConnection)schemaFile.openConnection();
// Magic from the other answer to accept self-signed cert
InputStream is = schemaConn.getInputStream();
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new StreamSource(is));
(I'm leaving out the try..catch to close the input stream and the connection)
It's not a validation problem, java.net.URL supports https, there should be bo difference. Just make sure that you can open https://localhost:1234/module/testschema.xsd with a browser.

Categories