SAML marshalling opensaml and java - java

I have recently upgraded opensaml dependency from 2.5.3 to 2.6.1 and xmlutil from
1.3.0 to 1.4.1.
It compiles without any errors but while running the application i get the following exception:
java.lang.NullPointerException
org.opensaml.xml.io.AbstractXMLObjectMarshaller.marshall(AbstractXMLObjectMarshaller.java:84)
Calling Code:
final MarshallerFactory marshallerFac = SAMLUtil.getMarshallerFactory();
final org.opensaml.xml.io.Marshaller authnStatementMarshaller = marshallerFac.getMarshaller(assertion);
Element assertionElement = null;
try {
assertionElement = authnStatementMarshaller.marshall(assertion);
try {
// Sign assertion and query signature
Signer.signObject(signature);
}
catch (final SignatureException e) {
LOGGER.error("Fout opgetreden bij ondertekenen Assertion", e);
}
}

I've noticed that if you don't initialize ("bootstrap") the SAML configuration, you get a NullPointerException (rather unhelpfully, I might add) when you try to construct the SAML.
import org.opensaml.DefaultBootstrap;
import org.opensaml.xml.ConfigurationException;
try {
DefaultBootstrap.bootstrap();
}
catch (ConfigurationException ce) {
}
The above is just a snippet of code to illustrate what I'm talking about. Did you maybe forget to bootstrap the configuration? That has to be done before you do anything.

Related

Can not create a new client instance for ConfigCat (configcat-java-client-6.0.1)

I want to implement config cat in my java 8 project.
The way I am creating a config cat client is this:
import com.configcat.ConfigCatClient;
public class ConfigCatClientUtil {
public ConfigCatClientUtil() {
}
public ConfigCatClient createClient(String configCatKey) {
ConfigCatClient configCatClient = null;
try {
configCatClient = new ConfigCatClient(configCatKey);
} catch (Exception e) {
}
return configCatClient;
}
}
The problem is that when try to execute this new ConfigCatClient(configCatKey) throws an error:
messages Feb 11 13:11:38 server: Caused by: java.lang.NoClassDefFoundError: okhttp3/Callback
I am using configcat-java-client-6.0.1.jar.
Does anyone know why I am getting this error?
This library has a direct dependency on OkHttp
https://mvnrepository.com/artifact/com.configcat/configcat-java-client/6.0.1
If you are following their documentation you wouldn't see this, so I suggest starting with their instructions for setting up your maven or Gradle build.
https://configcat.com/docs/sdk-reference/java/

Getting Error java.lang.NoClassDefFoundError: sun/net/www/protocol/https/HttpsURLConnectionImpl when deployed in Jboss EAP 6.4.x

I am writing a rest client using java.net which should do a PATCH request. But as PATCH is not a supported method in java.net, I used reflection to make it supported by changing the code like
private void updateConnectionToSupportPatchRequest(final HttpURLConnection conn)
throws ReflectiveOperationException {
try {
final Object targetConn;
if (conn instanceof HttpsURLConnectionImpl) {
final Field delegateField = HttpsURLConnectionImpl.class.getDeclaredField("delegate");
delegateField.setAccessible(true);
targetConn = delegateField.get(conn);
} else {
targetConn = conn;
}
final Field methodField = HttpURLConnection.class.getDeclaredField("method");
methodField.setAccessible(true);
methodField.set(targetConn, "PATCH");
} catch (final NoSuchFieldException ex) {
LOGGER.error("NoSuchFieldException: {} ", ex.getMessage());
}
}
but when I deploy my application which uses my rest client in JBoss, I get this error -
java.lang.NoClassDefFoundError: sun/net/www/protocol/https/HttpsURLConnectionImpl
I looked up on this error and came across this post http://planet.jboss.org/post/dealing_with_sun_jdk_related_noclassdeffounderror_under_jboss
I tried the suggested solution in the post still getting the same error. Any ideas on how to get passed this issue?
P.S. I cannot use the Apache HttpClient or RestEasy(Jboss) as there is another 3PP being used in the project which does not support Apache HttpClient
Have you tried using the workaround X-HTTP-Method-Override before trying to fiddle with internal classes of the JDK? If that's the case, you can use the instance's getClass-method to access fields and use isAssignableFrom as alternative to instanceof.
Another approach to get rid off specifying concrete classes is just trying to get the field in HttpsURLConnection and assuming a non-Https-URLConnection if the field can't be found. This might look like the following code:
private void updateConnectionToSupportPatchRequest(final HttpURLConnection conn)
throws ReflectiveOperationException {
try {
final Object targetConn = conn;
try {
final Field delegateField = findField(conn.getClass(), "delegate");
delegateField.setAccessible(true);
targetConn = delegateField.get(conn);
}
catch(NoSuchFieldException nsfe) {
// no HttpsURLConnection
}
final Field methodField = findField(conn.getClass(), "method");
methodField.setAccessible(true);
methodField.set(targetConn, "PATCH");
} catch (final NoSuchFieldException ex) {
LOGGER.error("NoSuchFieldException: {} ", ex.getMessage());
}
}
private Field findField(Class clazz, String name) throws NoSuchFieldException {
while (clazz != null) {
try {
return clazz.getDeclaredField(name);
}
catch(NoSuchFieldException nsfe) {
// ignore
}
clazz = clazz.getSuperclass();
}
throw new NoSuchFieldException(name);
}
But this might fail at another level because - obviously - the class that is used within JBoss is not the one you implemented the workaround, so fields and methods might be named differently.

Google Maps API (Directions) throws 403 error in Payara, not in WebLogic

I've been given the task to move our application from WebLogic 12.1.3 to Payara 4.1 and have run into an issue that I feel I'm more or less at the end of the line of troubleshooting.
We have an EJB (a Stateless bean) that has two methods, one that makes a call to the Google Maps Directions API and one that makes a call to the Google Maps Geocoding API, both using the same credentials and Googles client libraries for Java. Both methods work perfectly running on WebLogic, but after switching to Payara the one using the Directions API gives me an error. Here's the relevant part of the stacktrace:
java.io.IOException: Server Error: 403 Forbidden
at com.google.maps.internal.OkHttpPendingResult.parseResponse(OkHttpPendingResult.java:258)
at com.google.maps.internal.OkHttpPendingResult.await(OkHttpPendingResult.java:167)
at com.google.maps.PendingResultBase.await(PendingResultBase.java:56)
at com.somecompany.integration.GoogleDirectionsIntegration.getDirections(GoogleDirectionsIntegration.java:XXX)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
So the geocoding-method still works on both platforms, but when attempting the call to the Directions API I get a 403 back from Google indicating that my credentials are messed up, but the very same credentials work for the geocoding call. The code hasn't been changed in any way switching from one platform to the other.
What's even more confusing is that if I grab the actual URL of the call to Google from the logs and try it in my browser, i.e. paste "https://maps.googleapis.com/maps/api/directions/json?client=gme-company&mode=driving&arrival_time=1435825037&o
rigin=Somewhere&destination=Somewhere+else&alternat
ives=false&signature=nfre3XYZ2kmuDX8Qibce87ZFKQQ=" into Chrome, it works. I get a proper answer from Google. (btw, those aren't the actual credentials or origin and destination I'm using, they've been "anonymized" :-)). I've also checked that this URL (which is built by the client library) is the same running on both platforms as well as used the URL Signing Debugger on Google's developer pages, but to no avail. There should be nothing wrong with my credentials.
I'm really at the end of the line here, having spent days troubleshooting and searching online without finding a solution.
Not that it matters that much but I didn't write this code myself, and the person who did of course doesn't work here anymore :-P
Anyway, here's the code (somewhat anonymized):
#Stateless
public class GoogleDirectionsIntegration {
private static final Logger LOGGER = Logger.getLogger(GoogleDirectionsIntegration.class.getName());
private GeoApiContext context = null;
/**
* Initializer
*/
#PostConstruct
public void init() {
LOGGER.log(Level.INFO, "initiating {0}", this.getClass().getSimpleName());
this.context = new GeoApiContext().setEnterpriseCredentials("gme-company", "companyGoogleCryptographicSecret");
this.context.setReadTimeout(1, TimeUnit.SECONDS)
.setRetryTimeout(1, TimeUnit.SECONDS)
.setConnectTimeout(1, TimeUnit.SECONDS)
.setWriteTimeout(1, TimeUnit.SECONDS);
OkHttpRequestHandler okHttpRequestHandler = null;
OkHttpClient okHttpClient = null;
try {
Field requestField = this.context.getClass().getDeclaredField("requestHandler");
requestField.setAccessible(true);
okHttpRequestHandler = (OkHttpRequestHandler) requestField.get(this.context);
Field f = okHttpRequestHandler.getClass().getDeclaredField("client");
f.setAccessible(true);
okHttpClient = (OkHttpClient) f.get(okHttpRequestHandler);
} catch (NoSuchFieldException | SecurityException | IllegalAccessException | IllegalArgumentException e) {
throw new IllegalStateException("Failed to create SSL context", e);
}
SSLContext sslCtx = this.getSslContext();
if (sslCtx != null && okHttpClient != null) {
SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
okHttpClient.setSslSocketFactory(sslSocketFactory);
}
}
private SSLContext getSslContext() {
TrustManager[] tm = new TrustManager[] {
new CustomTrustManager()
};
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, tm, new SecureRandom());
} catch (NoSuchAlgorithmException | KeyManagementException ex) {
throw new IllegalStateException("Failed to create SSL context", ex);
}
return sslContext;
}
public DirectionsRoute getDirections(final String origin, final String destination, final DistanceUnit distanceUnit,
#Nullable TransportMode mode, #NotNull Instant arrivalTime) throws NotFoundException {
TransportMode actualMode = mode == null ? TransportMode.CAR : mode;
DirectionsRoute[] directionsRoutes;
DirectionsApiRequest directionsApiRequest = DirectionsApi.getDirections(this.context, origin, destination);
directionsApiRequest.arrivalTime(new Instant(arrivalTime));
directionsApiRequest.alternatives(false);
directionsApiRequest.mode(this.toTravelMode(actualMode));
try {
DirectionsResult res = directionsApiRequest.await(); // THIS IS WHERE IT BREAKS!
directionsRoutes = res.routes;
} catch (Exception e) {
LOGGER.log(Level.WARNING, e.getMessage(), e);
throw new NotFoundException(e.getMessage());
}
if (directionsRoutes.length != 1) {
throw new NotFoundException("Failed to fetch valid directions");
}
return directionsRoutes[0];
}
public void getAddress(LatLng startLocation, Location location, boolean cacheOverride) throws Exception {
com.google.maps.model.LatLng gLatLng = new com.google.maps.model.LatLng(startLocation.getLat(), startLocation.getLng());
GeocodingApiRequest geocodingApiRequest = GeocodingApi.reverseGeocode(this.context, gLatLng);
GeocodingResult[] geocodingResults;
geocodingResults = geocodingApiRequest.await();
if (0 < geocodingResults.length) {
//.. Code that does stuff with the result..
} else {
LOGGER.log(Level.WARNING, "Received empty results from Google reverse geocode for [{0}].", startLocation);
}
}
}
So I solved it. The problem wasn't in the code but in the dependencies, or rather in a dependency to one of the dependencies - OkHttp. I simply changed the version and it works now.

Exception in thread "main" java.lang.NoSuchFieldError: ifpossible

I am trying to establish a XMPP connection using the Smack library. Using the version 4.2.0-beta2(smack-core) and 4.1.8(smack-tcp)
public void gcmConnect()
{
try{
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder().setHost(GCM_SERVER)
.setPort(GCM_PORT).setUsernameAndPassword("27614215340#gcm.googleapis.com", API_KEY).build();
XMPPTCPConnection connection = new XMPPTCPConnection(config);
connection.connect();
System.out.println("Connected");
}
catch(XMPPException ex)
{
ex.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
XMPPConnectionTest obj = new XMPPConnectionTest();
obj.gcmConnect();
}
It gives the following error
Exception in thread "main" java.lang.NoSuchFieldError: ifpossible
at org.jivesoftware.smack.ConnectionConfiguration$Builder.<init>(ConnectionConfiguration.java:438)
at org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration$Builder.<init>(XMPPTCPConnectionConfiguration.java:91)
at org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration$Builder.<init>(XMPPTCPConnectionConfiguration.java:87)
at org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration.builder(XMPPTCPConnectionConfiguration.java:80)
at com.inn.foresight.gcm.XMPPConnectionTest.gcmConnect(XMPPConnectionTest.java:32)
at com.inn.foresight.gcm.XMPPConnectionTest.main(XMPPConnectionTest.java:53)
These are the possible reasons of getting this Exception
1. You probably compile using one version of a library, but use another version at run-time . You must verify that your classpath contains the proper version of the specified library.
2. You might have got two versions of jar being used.
3. Incomplete jar file

Java elasticsearch client always null

I've recently made the switch from elasticsearch 1.7 to 2.0 and I noticed the way you setup the client has changed. I went through the documentation and for some reason the client is always null. I was wondering if I have set it up correctly.
Here is my code:
Client client = null;
try {
client = TransportClient.builder().build().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
} catch (Exception e) {
Logger.log(e);
} finally {
client.close();
try {
conn.close();
} catch (SQLException e) {
Logger.log(e);
}
}
As noted in the comments, but a little bit more in detail: Elasticsearch 2.0 uses Guava 18.0 (see https://github.com/elastic/elasticsearch/pull/7593). So to fix errors like java.lang.NoSuchMethodError: com.google.common.util.concurrent.MoreExecutors.directExecutor()Ljava/util/concu‌rrent/Executor;, make sure to use Guava 18.0 as dependency and not other versions.

Categories