Reporting Gradle Builds using WebSockets

Posted By Hoyt Summers Pittman

If you have a build server you might want to receive reporting from your build. Many build bots offer this kind of reporting, but I decided to implement it myself in a standard Gradle build script. I override the default logger and replace it with one that writes all of the logging to a web socket. I have also created a very simple Java EE service which can consume logging messages and rebroadcast them to a different web socket using JMS¹.

Gradle Configuration

buildscript {
    dependencies {
        /* I'm using the tyrus libraries for my web socket client.
         Because logging is part of the build and not the project, 
         they must be declared classpath and in the buildscript.dependencies
         stanza.    
        */
        classpath 'org.glassfish.tyrus:tyrus-client:1.+'
        classpath 'org.glassfish.tyrus:tyrus-server:1.+'
        classpath 'org.glassfish.tyrus:tyrus-container-grizzly:1.+'
    }
}
//Now we begin the setup for the WebSocket Logger
import org.glassfish.tyrus.client.*;

gradle.useLogger(new WebSocketLogger());

class WebSocketLogger implements org.gradle.api.logging.StandardOutputListener {

    def manager = ClientManager.createClient();
    def session = manager.connectToServer(WebSocketLoggerClientEndpoint.class, java.net.URI.create("ws://localhost:8080/log_viewer/logging"));

    // useLogger replaces the default logging.  I am writing to a tmp file for debugging purposes.
    def tmp = new File('/tmp/log.txt');

    @Override
    void onOutput(CharSequence charSequence) {
        tmp.append(charSequence +"\n");
        session.basicRemote.sendText(charSequence.toString());
    }

    @javax.websocket.ClientEndpoint
    class WebSocketLoggerClientEndpoint {

        @javax.websocket.OnMessage
        public void processMessageFromServer(String message, javax.websocket.Session session) {
            tmp.append(message +"\n");
        }

        @javax.websocket.OnError
        public void handleError(javax.websocket.Session session, Throwable thr) {
            tmp.append('Err' + thr.message +"\n");
        }
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

Java EE Server

The server side was more complex because of how CDI and WebSockets interact in Java EE 7. The code is really simple and benefits much more from browsing in GitHub than in snippets here. You may view the server source here : https://github.com/secondsun/log_viewer².

All this code does is take messages sent to the socket found at “ws://localhost:8080/log_viewer/logging” and rebroadcasts them to “ws://localhost:8080/log_viewer/read”

Conclusion

Being able to rebroadcast log messages is neat and useful. Additionally having a working example for connecting websockets to JMS was a lot of fun to put together.

Foot notes

1: I would have used CDI events, but CDI and the ServerEndpoint annotation do not get along. There are several JIRAs tracking this issue.
* WEBSOCKET_SPEC-196
* JMS_SPEC-121
* CDI-370
2: Thanks to https://blogs.oracle.com/brunoborges/entry/integrating_websockets_and_jms_with for help with getting this working.

May 25th, 2016

AeroGear Android 3.0

Posted By Hoyt Summers Pittman

So it has been a while, but AeroGear Android 3.0 is out. As fitting a major number release we have a few breaking changes, lots of bug fixes, and a few new features. The full changelist can be viewed on our JIRA page

Changes

Breaking Changes

New Features

  • aerogear-android-push now uses GCM 3 including GcmListener, InstanceID, and GCM Topics.
  • Android 23 support
  • Material design in cookbooks

Minor Changes

  • JUnit 4 based automated tests
  • Updates to all required libraries (Android SDK, Android Maven Plugin)

How to get it

In Android Studio just declare our dependencies in your build.gradle file. Feel free to mix and match as necessary.

    compile 'org.jboss.aerogear:aerogear-android-core:3.0.0'
    compile 'org.jboss.aerogear:aerogear-android-security:3.0.0'
    compile 'org.jboss.aerogear:aerogear-android-store:3.0.0'
    compile 'org.jboss.aerogear:aerogear-android-pipe:3.0.0'
    compile 'org.jboss.aerogear:aerogear-android-auth:3.0.0'
    compile 'org.jboss.aerogear:aerogear-android-authz:3.0.0'
    compile 'org.jboss.aerogear:aerogear-android-push:3.0.1'

Also, feel free to take our cookbook samples for a spin!

How to get involved

Feel free to join us at #aerogear on IRC, follow us @aerogears on Twitter, or also join our aerogear-dev and aerogear-users mailing lists. For more details please check out our Community Page.

May 17th, 2016

Android N – Security with Self Signed Certificates

Posted By Hoyt Summers Pittman

If you are a good developer you are securing your services with SSL encryption. Unless you have put in a lot of effort, local testing still uses the good old fashioned self signed certificate and just click through the warning window of shame.

Screenshot from 2016-05-04 13-04-42

This is great until you are writing a RESTful service to be consumed by something which isn’t a browser. If you are an Android developer you have probably come across blog posts (or the official Android docs) encouraging you to make your own Trust Manager to accept your certificate or, worse, disable certificate checking altogether! However, Android N has come to the rescue with new security configuration features.

Using Self Signed Certificates with Android N

To use a self signed certificate you need to

  1. Add a meta-data tag to your AndroidManifest.xml which points to a security configuration xml file
  2. Add to your xml resources directory the security configuration file
  3. Download your self signed certificate to your project

Edit AndroidManifest.xml

I’ve added in my projects the following code to Android Manifest’s application element

<meta-data android:name="android.security.net.config"
               android:resource="@xml/network_security_config" />

This code just informs Android that the configuration file is found in res/xml/network_security_config.xml.

Creating the Network Security Config

The full documentation for the network security files covers a lot more than our use case for a self signed certificate. It is well worth a read to understand what is being done.

Here is my XML file to load my certificate from the raw directory. I have it named server_aerogear_dev, but the file name is irrelevant. What matters is that the common name in the certificate file matches the domain name of the server. I am pretty sure that this also works with IP addresses, but I haven’t tested it.

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config>
        <trust-anchors>
            <certificates src="@raw/server_aergear_dev"/>
        </trust-anchors>
    </base-config>
</network-security-config>

Downloading the certificate

You can download the certificate to the raw directory in your source using your web browser or using the command line.

cd app/src/main/res/raw;
echo -n | openssl s_client -connect server.aerogear.dev:8443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > server_aerogear_dev
// Credit to SO : http://serverfault.com/questions/139728/how-to-download-the-ssl-certificate-from-a-website

Replace the name of the server and the port with configuration appropriate to you.

Final Notes

This is a very simple example of a new feature from Android N. This may change or go out of date. However, this gives us a simple was to manage security and it ALSO works within Android’s build flavor system. Take a look, and stay safe.

May 4th, 2016

RHMAP and Google Accounts in Android

Posted By Hoyt Summers Pittman

The Red Hat Mobile Application Platform (RHMAP) has strong authentication and authorization mechanisms baked into its Auth Policy system. Android has deep integration with Google’s ecosystem which provides many easy mechanisms for authorizing services to act on a user’s behalf. Out of the box RHMAP allows for connecting to a Google account using OAuth and a web view, but a better user experience is using Google’s Android account picker. To enable this integration in RHMAP we have to use a MBaaS Auth Policy.

Prerequisites

This post should be informative to anybody who wishes to learn more about RHMAP; however, you will have the most benefit if you have access to a RHMAP instance and have read through the Getting Started documentation. If you do not have access to a instance of RHMAP, you may sign up for a free one at openshift.feedhenry.com.

Additionally you will need a Google account and Android emulator or device with Google’s APIs set up.

Demo

You can view an example of this integration in my FehBot video. The Android portion of this post will refer to the code in the application.

Creating an MBaaS Auth Policy

Create a blank MBaaS Service

Select “Services & APIs” from the top navigation. Click “Provision MBaaS Services/API”

CReate_MBaaS_1

Select “Choose” next to the item “New mBaaS Service”.

CReate_MBaaS_2

Name the service, click “Next”, ensure you are using the “Development” environment, and finally click “Deploy”. The service should deploy and you should have a green bar.

CReate_MBaaS_3

You are now ready to set up the Auth Policy.

Setup the Auth Policy

Select “Admin” from the top navigation and then “Auth Policies” from the 6 boxes which appear. Create_auth_policy_1

Click “Create” on the next screen to begin setting up an Auth Policy.
CReate_Auth_Policy_2

Name the Policy and select “MBaaS Service” as the “Type” under “Authentication. From the “Service” drop down select the service you created in the previous step. For “Endpoint” our MBaaS service will use “/auth/init”. Finally select for your “Default Environment” the value “Development.
CReate_Auth_Policy_3

Scroll down to the bottom of the page and click “Create Auth Policy”.

Implementing the MBaaS

I have created a MBaaS Service for us to use. It implements the server side token validation that Google recommends in its documentation. You should be able to copy this project into your MBaaS’s source and redeploy it.

You may wish to limit which Cloud applications can access your MBaaS services in the “Service Settings” section of the MBaaS “Details” page.

Create_MBaas_4

/auth/init

The /auth/init route will consume tokens from the Android device and set up user accounts in RHMAP. The code should be easy ish to follow along. The most important part is that we return a userId value in the json which we can use to look up the user’s session informaiton.

/list/:session

The route /list/:session can be used by Cloud applications to fetch a user’s account information which is created and saved after a call to “/auth/init”.

Android Integration

In order to integrate with Android, please follow Google’s Guide for instructions on how to setup an Android account and get an IdToken from a sign in. The FehBot Android client contains a working example.

Once you have a IdToken you can use FH.buildAuthRequest to perform the sign-in with RHMAP. For the three parameters us the Auth Policy name you assigned during “Setup the Auth Policy”, the IdToken you retrived from Google, and an empty string for the final parameter. Here is an example from the FeHBot app.

Caveats

As per the RHMAP Authentication API if you use this you will have to manually verify your sessions in your application yourself. The built in verification methods will not work.

Conclusion

As you can see, it is easy to add a third party authentication mechanism to RHMAP. The principles in this post can be applied to many other authentication providers and client platforms.

Mar 23rd, 2016
Next Page »