[JAX-RS] Some good auth resources

http://stackoverflow.com/questions/26777083/best-practice-for-rest-token-based-authentication-with-jax-rs-and-jersey

http://www.developerscrappad.com/1814/java/java-ee/rest-jax-rs/java-ee-7-jax-rs-2-0-simple-rest-api-authentication-authorization-with-custom-http-header/

https://jersey.java.net/documentation/latest/security.html

https://www.ibm.com/support/knowledgecenter/SSAW57_8.5.5/com.ibm.websphere.nd.doc/ae/twbs_jaxrs_impl_securejaxrs_webcont.html

 

 

 

Eclipse remote debug (with ant example)

Sometimes you cannot start your program from within eclipse to be able to debug it. Or even worse, you run your application on a remote server where you don’t have the sources or the ability to debug it on that machine. In this case you can use the remote debug capability of the JVM. For this:

1. Start your program with these VM arguments:

-Xdebug
-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=9000

If your application is started as an Ant task then:

<java dir="${running.dir}" jar="${jar.location}" fork="true" failonerror="true" >
         <jvmarg value="-Xdebug" />
 <jvmarg value="-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=9000" />

For address, specify the port you know is open and can be accessed from outside.

2. In eclipse open the project which contains the sources and click Debug -> Debug Configurations. Double click to create new debug configuration.
Set the correct Connection Properties: Host (the target host) and Port the port you specified earlier.

3. Click apply and debug…

[SOLVED] Eclipse create new class slow in Fedora

If you’re having problems with eclipse under Fedora, then it might be due to GTK3. So start eclipse like:

./eclipse --launcher.GTK_version 2

It must also work from eclipse.ini, but you need to make sure to put 2 in the next line:

-startup
plugins/org.eclipse.equinox.launcher_1.3.100.v20150511-1540.jar
--launcher.GTK_version
2
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.300.v20150602-1417
-product
org.eclipse.epp.package.java.product
--launcher.defaultAction
openFile
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.7
-XX:MaxPermSize=256m
-Xms256m
-Xmx1024m

Thanks to this person:
https://hedayatvk.wordpress.com/2015/07/16/eclipse-problems-on-fedora-22/

[WTF] Criteria API

This is the best representation of what I want to say about JPA criteria API:

http://www.odi.ch/weblog/posting.php?posting=667

EntityManager em = ...;
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Root<Pet> pet = cq.from(Pet.class);
cq.select(pet);
TypedQuery<Pet> q = em.createQuery(cq);
List<Pet> allPets = q.getResultList();

The equivalent JPQL query is:

FROM Pet

The equivalent SQL query is:

SELECT * FROM Pet

Clearly SQL is too simple and boring. You really need a bullshit API to produce a simple SQL query. Of course this will ease maintenance, improve performance, reduce code, prevent bugs, speed up development by a factor of 10 and reduce your project cost by 99% at least. A classic case of overengineering.

Java EE 7 WebSocket example

1. Createa a Java EE Web application called MyWebSocket for example.
2. In index.html:

<!DOCTYPE html>
<html>
    <head>
        <title>Start Page</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script language="javascript">
            var ws;
            function connect() {
                ws = new WebSocket("ws://localhost:8080/MyWebSocket/sockOne");
                ws.onmessage = onMessage;
            }
            function onMessage(evt) {
                var dataarr = evt.data;
                document.getElementById("valueElement").innerHTML = dataarr;
            }
            window.addEventListener("load", connect, false);
        </script>
    </head>
    <body>
        <h1>Hello World!</h1>
        <b>Value: </b>
        <b id="valueElement">no data yet</b>
    </body>
</html>

2. Create a class Called WebSocketEndpoint. Here the most important annotations are @ServerEndpoint, @OnOpen, @OnClose and @OnError, in these methods you put whatever you want to get executed when these events happen:

package com.vvirlan.websocket;

import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/**
 *
 * @author vvirlan
 */
@ServerEndpoint("/sockOne")
public class WebSocketEndpoint {

    private static final Logger LOGGER = Logger.getLogger("WebSocketEndpoint");
    private static Queue<Session> sessionQueue = new ConcurrentLinkedQueue<>();

    public static void send(double number) {
        String toSend = String.format("%f", number);
        try {
            for (Session session : sessionQueue) {
                session.getBasicRemote().sendText(toSend);
                LOGGER.log(Level.INFO, "Sent: {0}", toSend);
            }
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, e.toString());
        }
    }

    @OnOpen
    public void openConnection(Session session) {
        sessionQueue.add(session);
        LOGGER.log(Level.INFO, "Connection opened");
    }

    @OnClose
    public void closeConnection(Session session) {
        sessionQueue.remove(session);
        LOGGER.log(Level.INFO, "Connection closed");
    }

    @OnError
    public void error(Session session, Throwable th) {
        sessionQueue.remove(session);
        LOGGER.log(Level.WARNING, "Connection errorred");
        LOGGER.log(Level.WARNING, th.toString());

    }
}

3. The bean which will produce our fake data. It gets injected a TimerService as a @Resource and when @Timeout happens it invokes the send method of our endpoint:

package com.vvirlan.websocket;

import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;

/**
 *
 * @author vvirlan
 * Generates a double every second and calls the endpoint for updating the clients
 */
@Startup
@Singleton
public class GeneratorBean {
    @Resource TimerService timerService;
    private Random random;
    private volatile double number = 777.0;
    private static final Logger logger = Logger.getLogger("GeneratorBean");
    
    @PostConstruct
    public void init() {
        logger.log(Level.INFO, "Initializing EJB");
        random = new Random();
        timerService.createIntervalTimer(1000, 1000, new TimerConfig());
    }
    
    @Timeout
    public void timeout() {
        number = 1.5 * (random.nextInt(100));
        WebSocketEndpoint.send(number);
    }
}

JSF simple ajax example

Here is a simple AJAX example in JSF (run on Glassfish).
Just to note: for sending the value to the bean you use the execute attribute of f:ajax, and for displaying the output from the beans’s getter, you use the render attribute.

1. pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mycompany</groupId>
    <artifactId>ajaxtest</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>ajaxtest</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>7.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

2. The xhtml page:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        Hello from Facelets
        
        <h:form>
            <h:inputText id="msg" value="#{myBean.text}"/>
        <h:commandButton id="submit" value="Submit">
            <f:ajax event="click"  execute="msg" render="outText"/>
        </h:commandButton>
            <h:outputText value="The message: #{myBean.text}" id="outText">
            </h:outputText>
            
            </h:form>
        
    </h:body>
</html>

3. The Bean:

package com.mycompany.ajaxtest;

import java.io.Serializable;
import javax.enterprise.inject.Model;

/**
 *
 * @author vvirlan
 */
@Model
public class MyBean implements Serializable {
    
    private String text = "defaullt";
    
    
    public void message() {
        System.out.println("The message "+text);
        
    }

    public String getText() {
        System.out.println("getText message "+text);
        return text;
    }

    public void setText(String text) {
        System.out.println("setText message "+text);
        this.text = text;
    }
}

[ubuntu] installing Oracle java

unzip the java package into a folder under /opt/

sudo update-alternatives –install “/usr/bin/java” “java” “/opt/java/64/jdk1.8.0_77/bin/java” 1

sudo update-alternatives –set java /opt/java/64/jdk1.8.0_77/bin/java

sudo update-alternatives –install “/usr/bin/javac” “javac” “/opt/java/64/jdk1.8.0_77/bin/javac” 1

sudo update-alternatives –set javac /opt/java/64/jdk1.8.0_77/bin/javac