JUnit Test: Unable to unmarshall element - java

I have encountered the following difficulty for close to a week now after trying countless solutions across the net. The specific problem relates to NullPointerException being thrown after calling the method Configuration.getUnmarshallerFactory().getUnmarshaller(Element) in my JUnit test.
The following is the dependency information for opensaml library imported into my project:
<dependency>
<groupId>org.opensaml</groupId>
<artifactId>opensaml</artifactId>
<version>2.6.4</version>
</dependency>
The following is the implementation. During normal execution of the program/project, it is able to execute and return the Response object successfully.
private Response a(String text) throws ConfigurationException, SAXException {
DefaultBootstrap.bootstrap();
Schema s = SAMLSchemaBuilder.getSAML11Schema();
BasicParserPool bpp = new BasicParserPool();
bpp.setNamespaceAware(true);
bpp.setIgnoreElementContentWhitespace(true);
bpp.setSchema(schema);
InputStream is= new ByteArrayInputStream(Base64.decode(samlContent).getBytes());
Response res= null;
try {
Document doc = bpp.parse(is);
Element elmt= doc.getDocumentElement();
try {
QName qn = new QName(elmt.getNamespaceURI(), elmt.getLocalName(), elmt.getPrefix());
Unmarshaller um = Configuration.getUnmarshallerFactory().getUnmarshaller(qn); <== NullPointerException thrown at this line during JUnit Test**
samlResponse = (Response) unmarshaller.unmarshall(elmt);
} catch (XMLParserException e) {
logger.debug(e.getMessage());
} catch (UnmarshallingException e) {
logger.debug(e.getMessage());
}
return res;
}
The following is JUnit Test:
(I got a sample samlp:Response string from the following website: https://www.samltool.com/generic_sso_res.php)
#Test
public void test() throws Exception {
PowerMockito.mockStatic(DefaultBootstrap.class);
PowerMockito.doNothing().when(DefaultBootstrap.class, "bootstrap");
Response result = classInstance.a(Base64.encode(responseStringFromWebsite));
assertNotNull(result);
}
I would greatly appreciate any help or sharing of knowledge if any of you have encountered similar errors before.

By mocking method DefaultBootstrap # bootstrap, you've skiped initialization of required fields, I guess. Check up the source code of DefaultBootstrap.bootstrap(), it will clarify the reason of NPE.

Related

WordAPI ApiException caught: Not Found

I'm following [this][1] documentation to connect to api, I want to build a JavaFX app that you can enter a word and it's retrieves it from api and I wanted to test the feature before displaying contents on GUI. Howerer I got this exception that the words is not found while I tested endpoint in their website and that word had definitions. I'm pretty new to using API perhaps I missed something that isn't shown in the documentation?
Here is my code:
public void testDetailsWords(String word,String detail) {
//String word = "lovely"; // Word
//String detail = "definitions"; // Detail
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
apiClient = Configuration.getDefaultApiClient();
apiClient.setBasePath("https://www.wordsapi.com/");
// configure authentications
Authentication auth;
auth = apiClient.getAuthentication("Default");
((ApiKeyAuth) auth).setApiKey(Apikey);
try {
WordsApi wordsApi = new WordsApi();
DetailsResponse response = wordsApi.details(word, detail);
System.out.println(response);
} catch (ApiException e) {
System.out.printf("ApiException caught: %s\n", e.getMessage());
}
}
Here is my Controller code :
#FXML
private void handleDefinitions(ActionEvent event) throws IOException {
String word =definitionsfield.getText();
String detail= "definitions";
apiCall.testDetailsWords(word,detail);
}
I would be grateful for the help.
[1]: http://restunited.com/docs/6vc24wq3ojpq
It's seems that tutorial that I tried following is very misleading which is very dissapoing, but I've learned my lesson now .
I decided to use Unirest to get request and it's worked perfectly.
If you stumble upon the link it's better not to follow that tutorial

Unable to invoke DefaultBootstrap.bootstrap(); method in own opensaml unmarshalling method

I have written the following unmarshalling method to process my xml file but am faced with the following error during execution.
The following snippet is my code:
private Response a(String text) throws ConfigurationException, SAXException {
try {
DefaultBootstrap.bootstrap(); <= ERROR HERE
}
catch(ConfigurationException e) {
log.error("Error Encountered", e);
}
Schema s = SAMLSchemaBuilder.getSAML11Schema();
BasicParserPool bpp = new BasicParserPool();
bpp.setNamespaceAware(true);
bpp.setIgnoreElementContentWhitespace(true);
bpp.setSchema(schema);
InputStream is= new ByteArrayInputStream(Base64.decode(samlContent).getBytes());
Response res= null;
try {
Document doc = bpp.parse(is);
Element elmt= doc.getDocumentElement();
try {
QName qn = new QName(elmt.getNamespaceURI(), elmt.getLocalName(), elmt.getPrefix());
Unmarshaller um = Configuration.getUnmarshallerFactory().getUnmarshaller(qn);
samlResponse = (Response) unmarshaller.unmarshall(elmt);
} catch (XMLParserException e) {
logger.debug(e.getMessage());
} catch (UnmarshallingException e) {
logger.debug(e.getMessage());
}
return res;
}
The following is the error messaged return in the IDE:
java.lang.IllegalArgumentException: Error create SSL context
at org.opensaml.ws.soap.client.http.TLSProtocolSocketFactory.init(TLSProtocolSocketFactory.java:151)
at org.opensaml.ws.soap.client.http.TLSProtocolSocketFactory.<init>(TLSProtocolSocketFactory.java:111)
at org.opensaml.DefaultBootstrap.initializeHttpClient(DefaultBootstrap.java:118)
at org.opensaml.DefaultBootstrap.bootstrap(DefaultBootstrap.java:110)
I would greatly appreciate any form of help or sharing of knowledge if you have encountered the following issue previously. Thank you!
If it is just a test code, that runs without any https communtication, you should set system property
org.opensaml.httpclient.https.disableHostnameVerification=true
in jvm, or include the following code snippet before DefaultBootstrap.bootstrap() method:
System.setProperty("org.opensaml.httpclient.https.disableHostnameVerification", "true");

Spring: Test JSP Output in JUnit Test

We have a API, which returns the JSP as the view, for example:
#RequestMapping(value = "/cricket/{matchId}", method = RequestMethod.GET)
public String getCricketWebView(HttpServletRequest request, #PathVariable("matchId") Integer matchId, ModelMap mv){
try{
return "webforms/cricket";
}catch(Exception e){
e.printStackTrace();
}
return "";
}
I wrote a unit test to test this out as follows:
#Test
public void test_cricket()
{
try {
MvcResult result =this.mockMvc.perform(get(BASE + "/cricket/123")
.accept(MediaType.TEXT_HTML))
.andExpect(status().isOk()).andReturn();
String json = result.getResponse().getContentAsString();
System.out.println(json);
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is that, the unit tests only returns the string webforms/cricket and not the actual HTML from the cricket.jsp page. I understand this is happening because I am using the Mock MVC.
But, is there a way I can test the actual HTML? The reason is that we use some complex JSTL tags and we have seen in the past that unit test succeeds but the actual JSP page returns 500 error because of parsing failure.
I tried the following code:
try {
WebConversation conversation = new WebConversation();
GetMethodWebRequest request = new GetMethodWebRequest(
"http://localhost:8080/cricket/123");
WebResponse response = conversation.getResponse(request);
System.out.println(response.getResponseMessage());
}
catch (Exception e)
{
e.printStackTrace();
org.junit.Assert.fail("500 error");
}
But this gives, connection refused exception. Again I understand this is because web server is not setup at the time of test.
This is my configuration:
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(locations = "file:src/main/webapp/WEB-INF/spring-resources/applicationcontext.xml")
public class MobileApiControllerTest {
...
}
I also tried using #WebIntegrationTest, but the same problem. It seems this only works for Spring boot application. Our application is a typical WAR application deployed on Tomcat.
Any idea how can I achieve the actual JSP output in unit test?
Reading and googling I think that this can't happen using the Spring Test framework. Spring test does not run the code(java code, jstl, i18n messages) inside the jsp! This is also a useful answer from so.
If you wish to test the jsp source, you have to use a client side test framework like Selenium or HttpUnit.

What am I doing wrong with my Dom4j Code?

Hey guys I am working on a load class for my project that loads and pulls a info from a xml files. I have been following a few guides online but I am running into the error java.lang.NoClassDefFoundError: org/jaxen/JaxenException. I know the code is finding the save file because I can print out the name. But when I try to pull out the info I get that error. Snippet of code is below if there is no error in there let me know and Ill post more.
public void LoadProjects()
{
try
{
Files.walk(Paths.get("D:/workspace/Project Program/Projects/")).forEach(filePath ->
{
if(Files.isRegularFile(filePath))
{
System.out.println("Testing");
try
{
SAXReader reader = new SAXReader();
Document document = reader.read(filePath.toFile());
System.out.println(document.getName());
Node node = document.selectSingleNode("///Project/Info");
//String name = node.valueOf("#Name");
//String projNum = node.valueOf("#ProjectNumber");
//node = document.selectSingleNode("//Project/Dates");
//String dueBy = node.valueOf("#DueBy");
//CButton temp = new CButton(name, projNum, dueBy);
//Console.console.AddToList(temp);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
}
Did you add the jaxen jar to your servers lib?
Your code seems correct so far but please add as much information as possible from the beginning.
Ff you are using maven:
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.1</version>
</dependency>

xml 1.1 causing NullPointerException when used in xsd

I have an xsd file. I am trying to create javax.xml.validation.Schema using that xsd file. I have written a program that does it. When I use <?xml version="1.0" encoding="UTF-8"?> every thing works fine. But when I use <?xml version="1.1" encoding="UTF-8"?> then the first attempt to create the Schema is throwing NPE but the second and subsequent attempts are successful. Below is the source:
import java.io.File;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
public class Test {
SchemaFactory sf = null;
public static void main(String args[]) {
Test test = new Test();
test.init();
File schemaFile = new File("D:\\test.xsd");
try {
test.doIt(schemaFile);
} catch (Exception e) {
System.out.println("doIt() failed " + e.getMessage());
}
try {
test.doItAgain(schemaFile);
} catch (Exception e) {
System.out.println("doItAgain() failed " + e.getMessage());
}
System.out.println("Execution completed");
}
public void doIt(File schemaFile) throws Exception {
#SuppressWarnings("unused")
Schema schema = null;
synchronized (sf) {
schema = sf.newSchema(schemaFile);
}
System.out.println("doIt() success");
}
public void doItAgain(File schemaFile) throws Exception {
#SuppressWarnings("unused")
Schema schema = null;
synchronized (sf) {
schema = sf.newSchema(schemaFile);
}
System.out.println("doAgainIt() success");
}
public void init() {
sf = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
}
}
The method (doIt() or doItAgain()) executed first is throwing NPE.
Below is the stack trace:
java.lang.NullPointerException
at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.load(XMLEntityScanner.java:1738)
at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.load(XMLEntityScanner.java:1770)
at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.skipSpaces(XMLEntityScanner.java:1543)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$TrailingMiscDriver.next(XMLDocumentScannerImpl.java:1400)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
at com.sun.org.apache.xerces.internal.impl.xs.opti.SchemaParsingConfig.parse(SchemaParsingConfig.java:435)
at com.sun.org.apache.xerces.internal.impl.xs.opti.SchemaParsingConfig.parse(SchemaParsingConfig.java:491)
at com.sun.org.apache.xerces.internal.impl.xs.opti.SchemaDOMParser.parse(SchemaDOMParser.java:510)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.getSchemaDocument(XSDHandler.java:1802)
at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.parseSchema(XSDHandler.java:531)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaLoader.loadSchema(XMLSchemaLoader.java:552)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaLoader.loadGrammar(XMLSchemaLoader.java:519)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaLoader.loadGrammar(XMLSchemaLoader.java:485)
at com.sun.org.apache.xerces.internal.jaxp.validation.XMLSchemaFactory.newSchema(XMLSchemaFactory.java:210)
at javax.xml.validation.SchemaFactory.newSchema(SchemaFactory.java:594)
at javax.xml.validation.SchemaFactory.newSchema(SchemaFactory.java:610)
at Test.doIt(Test.java:39)
at Test.main(Test.java:20)
My question is,
Why XML 1.1 is not working properly?
Why only first attempt is unsuccessful?
I found that if I use the latest versio of Xerces jar I dont face the isue. I also found that the problem is because there is a bug in JDK itself and its also logged at openjdk website and more interesting is that no one cared to fix this. So, use latest version of Xerces jar or use xml version 1.0. I will go with the first option. Who knows how many hidden surprises would be there in the old one :P

Categories