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

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");

Related

JUnit Test: Unable to unmarshall element

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.

FTPS storeFile return always false Java

im trying to send files to FTPS server
connection method: FTPS, ACTIVE, EXPLICIT
setFileType(FTP.BINARY_FILE_TYPE);
setFileTransferMode(FTP.BLOCK_TRANSFER_MODE);
Checking the reply string right after connect i got:
234 AUTH command ok. Expecting TLS Negotiation.
from here
234 Specifies that the server accepts the authentication mechanism specified by the client, and the exchange of security data is complete. A higher level nonstandard code created by Microsoft.
while trying to send file with storeFile or storeUniqeFile i get false
checking the reply string right after store file i got: 501 Server cannot accept argument.
what is weird i was able creating a directory to this client without any issues
with makeDirectory("test1");
i was trying both this links : link1 , link2
FOR EXAMPLE when i was trying to use ftp.enterLocalPassiveMode(); before ftp.storeFile(destinationfile, in);
i got time out error .
Does anyone have any idea how to solve it ?
public static void main(String[] args) throws Exception {
FTPSProvider ftps = new FTPSProvider();
String json = "connection details";
DeliveryDetailsFTPS details = gson.fromJson(json, DeliveryDetailsFTPS .class);
File file = File.createTempFile("test", ".txt");
FileUtils.write(file, " some test", true);
try (FileInputStream stream = new FileInputStream(file)) {
ftps.sendInternal(ftps.getClient(details), details, stream, file.getName());
}
}
protected void sendInternal(FTPClient client, DeliveryDetailsFTPS details, InputStream stream, String filename) throws Exception {
try {
// release the enc
DeliveryDetailsFTPS ftpDetails = (DeliveryDetailsFTPS) details;
setClient(client, ftpDetails);
boolean isSaved = false;
try (BufferedInputStream bis = new BufferedInputStream(stream)) {
isSaved = client.storeFile(filename, bis);
}
client.makeDirectory("test1");
client.logout();
if (!isSaved) {
throw new IOException("Unable to upload file to FTP");
}
} catch (Exception ex) {
LOG.debug("Unable to send to FTP", ex);
throw ex;
} finally {
client.disconnect();
}
}
#Override
protected FTPClient getClient(DeliveryDetails details) {
return new FTPSClient(isImplicitSSL((DeliveryDetailsFTPS ) details));
}
protected void setClient(FTPClient client, DeliveryDetailsFTPS details) throws Exception {
DeliveryDetailsFTPS ftpDetails = (DeliveryDetailsFTPS ) details;
client.setConnectTimeout(100000);
client.setDefaultTimeout(10000 * 60 * 2);
client.setControlKeepAliveReplyTimeout(300);
client.setControlKeepAliveTimeout(300);
client.setDataTimeout(15000);
client.connect(ftpDetails.host, ftpDetails.port);
client.setBufferSize(1024 * 1024);
client.login(ftpDetails.username, ftpDetails.getSensitiveData());
client.setControlEncoding("UTF-8");
int code = client.getReplyCode();
if (code == 530) {
throw new IOException(client.getReplyString());
}
// Set binary file transfer
client.setFileType(FTP.BINARY_FILE_TYPE);
client.setFileTransferMode(FTP.BLOCK_TRANSFER_MODE);
if (ftpDetails.ftpMode == FtpMode.PASSIVE) {
client.enterLocalPassiveMode();
}
client.changeWorkingDirectory(ftpDetails.path);
}
I have tried this solution as well didn't solve the problem:
they only way i was able send file is with FileZilla and it is using FTPES .
But i need my Java code to do it . can anyone give me a clue
I have tried almost any possible solution offered on different websites could not make it work with Apache FTPS CLIENT ,
had to use a different class which worked like a charm here is a snippet:
com.jscape.inet.ftps Link
private Ftps sendWithFtpsJSCAPE(ConnDetails details, InputStream stream, String filename) throws FtpException, IOException {
Ftps ftp;
FtpConnectionDetails ftpDetails = FtpConnectionDetails details;
ftp = new Ftps(ftpDetails.getHost(), ftpDetails.getUsername(), ftpDetails.getPassword());
if (ftpDetails.getSecurityMode().equals(FtpConnectionDetails.SecurityMode.EXPLICIT)) {
ftp.setConnectionType(Ftps.AUTH_TLS);
} else {
ftp.setConnectionType(Ftps.IMPLICIT_SSL);
}
ftp.setPort(ftpDetails.getPort());
if (!ftpDetails.getFtpMode().equals(FtpMode.ACTIVE)) {
ftp.setPassive(true);
}
ftp.setTimeout(FTPS_JSCAPE_TIME_OUT);
ftp.connect();
ftp.setBinary();
ftp.setDir(ftpDetails.getPath());
ftp.upload(stream, filename);
return ftp;
}

Trying to parse xml file but get java.security.AccessControlException in deployed GAE

I'm trying to run a SAXParser on a GAE application on a local XML file I stored in the WEB-INF file. It works fine when I use it on development mode but when I deploy it and try to parse that file I get the following exception, and I'm not writing am XML file, just trying to parse a local one:
java.security.AccessControlException: access denied ("java.io.FilePermission" "WEB-INF/MapInfo.xml" "write")
The code I'm trying to run looks like this:
#Override
public Double countPOIs() {
Double total = 0.0;
List<String> Coordinates;
Coordinates = new ArrayList<String>();
try {
XMLParser parser = new XMLParser(Coordinates, 8);
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(parser);
reader.parse("WEB-INF/MapInfo.xml");
total = parser.getACC();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return total;
}
The constructor seems a little strange but its irrelevant for this operation. Does anyone see any problems here?
Try replacing the reader.parse line with the following (sorry, unable to test it):
final javax.servlet.ServletContext servletContext = this.getServletContext();
java.io.InputStream stream = servletContext.getResourceAsStream("/WEB-INF/MapInfo.xml");
reader.parse(stream);

Sending XML from Java to MSMQ - bodyType from VT_EMPTY to VT_BSTR

We work on a Java (Java EE) application, and we generate XML files in order to send them to a remote .NET application with MSMQ reading on their side.
The XML file is generated by JDom, like so :
// add elements...
Document doc = new Document(root);
String XmlData = new XMLOutputter(Format.getPrettyFormat().setOmitEncoding(true)).outputString(doc);
try {
SendFile( XmlData, "title" , "path");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MessageQueueException e) {
e.printStackTrace();
}
Then we use this function, using the MsmqJava library to send the file :
private void SendFile(String data, String title, String outputPath) throws UnsupportedEncodingException, MessageQueueException{
String qname="name_of_the_queue";
String fullname= "server_path" + qname;
String body = data;
String label = title;
String correlationId= "L:none";
try {
Queue queue= new Queue(fullname);
Message msg= new Message(body, label, correlationId);
queue.send(msg);
} catch (MessageQueueException ex1) {
System.out.println("Put failure: " + ex1.toString());
}
}
They correctly receive the file, but they told us that the bodyType was set to "VT_EMPTY" while they wanted "VT_BSTR", and we haven't find a clue about how to fix this. If you know another lib who does the job, or a workaround to this one, we can change with no problem.
Thanks !
Looking at the documentation for the library you use, it is not possible using that library.
Jmsmqqueue also doesn't provide the functionality you need.
It seems sun also had an adapter: https://wikis.oracle.com/display/JavaCAPS/Sun+Adapter+for+MSMQ

Secure WS client with UsernameToken(SOAP security header)

I'm trying to secure my WS client to be able to call the WS.
My code looks like this:
SendSmsService smsService = new SendSmsService();
SendSms sendSMS = smsService.getSendSms();
BindingProvider stub = (BindingProvider)sendSMS;
//Override endpoint with local copy of wsdl.
String URL ="";//here is the wsdl url
Map<String,Object> requestContext = stub.getRequestContext();
requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, URL);
//Set usernametoken
URL fileURL = loader.getResource("client-config.xml");
File file = new File(fileURL.getFile());
FileInputStream clientConfig = null;
try {
clientConfig = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
XWSSecurityConfiguration config = null;
try {
config = SecurityConfigurationFactory.newXWSSecurityConfiguration(clientConfig);
} catch (Exception e) {
e.printStackTrace();
log.warn("Exception: "+e.getMessage());
}
requestContext.put(XWSSecurityConfiguration.MESSAGE_SECURITY_CONFIGURATION, config);
//Invoke the web service
String requestId = null;
try {
requestId = sendSMS.sendSms(addresses, senderName, charging, message, receiptRequest);
} catch (PolicyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and the config file looks like this:
<xwss:JAXRPCSecurity xmlns:xwss="http://java.sun.com/xml/ns/xwss/config" optimize="true">
<xwss:Service>
<xwss:SecurityConfiguration dumpMessages="true"
xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
<xwss:UsernameToken name="username" password="password>
</xwss:SecurityConfiguration>
</xwss:Service>
<xwss:SecurityEnvironmentHandler>
util.SecurityEnvironmentHandler
</xwss:SecurityEnvironmentHandler>
</xwss:JAXRPCSecurity>
The SecurityEnviromentHandler is a dummy class that implements javax.security.auth.callback.CallbackHandler.
Authentication must be in compliance with Oasis Web Services Security Username Token Profile 1.0.
But I'm constantly getting "Security header not valid" error.
Where am I going wrong, can anyone tell me.
I used wsimport(JAX_WS 2.1 to generate classes for my client)
Note:Only thing I know about this WS is WSDL URL and user&pass for authentication
SOLUTION
I solved the problem. The thing that was going wrong is that client-config.xml file cause I didn't know how to set it properly. I ran into this example and used it:
http://www.javadb.com/using-a-message-handler-to-alter-the-soap-header-in-a-web-service-client
Just copied those 2 classes on the link into my projects structure and called them, something like this:
SendSmsService smsService = new SendSmsService();
HeaderHandlerResolver handlerResolver = new HeaderHandlerResolver();
smsService.setHandlerResolver(handlerResolver);
SendSms sendSMS = smsService.getSendSms();
Now it works perfectly!

Categories