Installing jdk 9 manually

THis link http://blog.skypayjm.com/2014/02/installing-jdk-manually.html was helpful for me to install jdk 9 but I noticed some change to be done :

–>      change directory to directory C:\JDK\.rsrc\JAVA_CAB10
to        C:\JDK\.rsrc\1033\JAVA_CAB10\

-->  extrac32 111
by   extrac32 4

then every thing is done

Advertisements
Posted in Java_corner

Lambda Expression in JAVA 8

Do you remember Anonymous Class, easy game isn’t it ? but is it enough clear and easy to read? I don’t think so.
Anonymous class are in general used to pass a functionality as an argument to an other method (likes Event, Listener) by implementing often only one method that makes code more verbose and unclear.
But Java 8 introduces a new gate to functional programming (FP) by introducing Lambda Expression which makes clean and readable code easy to maintain and more coherent.

So What is Lambda?

In the Java Specification (Click here), Lambda is defined as a block of parameters and code  that can be used to pass function as a parameter.

To illustrate this let implement Runnable using the old and new fashion of Java coding .
In Java 7 and previous, the only way to do it is by doing this:

Runnable runnableOldFachion = new Runnable() {
			
			@Override
			public void run() {
				/* your code here*/
			}
		};

With java 8 we can  do it also  this way

Runnable runnableNewFachion = ()-> {/*your code here*/};

WaW so clean. imagine so the combination of the two programming approach, functional (FP) and object oriented (OOP). imagine the strength while doing reactive programming, map reducing, data aggregation, data filtering and  searching or even  high multi threading concurrent programming.
I advice you to look inside this and start any new project using java 8. this will help you to understand this concept.
Note: People who  never develop in Schem or Lisp, will encounter some trouble to understand the FP concepts, but don’t stop keep learning and exercising, then everything will be easy and clear.

Here it is an simple use case  of FP in java 8

/**
 * 
 */
package java_8__spec_test;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import java_8__spec_test.Vehicle.VehicleType;

/**
 * FP Example inside JAVA 8
 * 
 * @author Younss Azzayani
 *
 */
class Vehicle {
	/**
	 * Vehicle Type.
	 * */
	enum VehicleType {
		BICYCLE(0), MOTORCYCLE(1), CAR(2), TRUCK(3), OTHER(4);
		int type;

		VehicleType(int type) {
			this.type = type;
		}

	}

	/**
	 * Vehicle Reference
	 */
	String referenceCode;
	/**
	 * Vehicle Type
	 */
	VehicleType type;

	/**
	 * Constructor
	 * 
	 * @param referenceCode
	 * @param type
	 */
	public Vehicle(String referenceCode, VehicleType type) {
		if (referenceCode == null || type == null) {
			throw new RuntimeException("reference and type must not be null ");

		}
		this.referenceCode = referenceCode;
		this.type = type;
	}

	@Override
	public String toString() {
		return type + " [" + referenceCode + "]";
	}

	/**
	 * Compare current object with given object as param.
	 * 
	 * @param b
	 * @return
	 */
	public int compareByType(Vehicle b) {
		return this.type.type >= b.type.type ? 1 : -1;
	}
}

/**
 * Lambda Sample
 * 
 * @author Younss AZZAYANI
 *
 */
public class LambdaSample {

	/**
	 * 
	 * @param args
	 */
	public static void main(String... args) {
		/* Lets have a Collection of Vehicle */
		List<Vehicle> vehicles = Arrays.asList(new Vehicle("c0",
				VehicleType.CAR), new Vehicle("c2", VehicleType.CAR),
				new Vehicle("b0", VehicleType.BICYCLE), new Vehicle("t0",
						VehicleType.TRUCK), new Vehicle("m0",
						VehicleType.MOTORCYCLE));

		System.out.println("*** 1- Show Vehicles first aproch");
		vehicles.forEach((p) -> {
			System.out.println(p.toString());
		});
		/* Sort Example 1st approch */
		Collections.sort(vehicles, Vehicle::compareByType);
		/* Sort Example 2d approch */
		Collections.sort(vehicles, (v1, v2) -> v1.type.type >= v2.type.type ? 1
				: -1);

		System.out.println("*** 2- Show Vehicles second aproch");
		vehicles.forEach(System.out::println);
		/* filter all cars from original vehicle collection */
		List<Vehicle> cars = vehicles.stream()
				.filter((v) -> v.type.equals(VehicleType.CAR))
				.collect(Collectors.toList());

		System.out.println("*** 3- Show Cars:");
		cars.forEach(System.out::println);

	}

}

Posted in Java_corner

Simple JMS 2.0 Example within JEE7

Introduction:

Source Wikipedia (http://en.wikipedia.org/wiki/Java_Message_Service)

The Java Message Service (JMS) API is a Java Message Oriented Middleware (MOM) API for sending messages between two or more clients. JMS is a part of the Java Platform, Enterprise Edition, and is defined by a specification developed under the Java Community Process as JSR 914. It is a messaging standard that allows application components based on the Java Enterprise Edition (Java EE) to create, send, receive, and read messages. It allows the communication between different components of a distributed application to be loosely coupled, reliable, and asynchronous.

We list these JMS elements below:

JMS provider

An implementation of the JMS interface for a Message Oriented Middleware (MOM). Providers are implemented as either a Java JMS implementation or an adapter to a non-Java MOM.

JMS client

An application or process that produces and/or receives messages.

JMS producer/publisher

A JMS client that creates and sends messages.

JMS consumer/subscriber

A JMS client that receives messages.

JMS message

An object that contains the data being transferred between JMS clients.

JMS queue

A staging area that contains messages that have been sent and are waiting to be read (by only one consumer). Note that, contrary to what the name queue suggests, messages don’t have to be received in the order in which they were sent. A JMS queue only guarantees that each message is processed only once.

JMS topic

A distribution mechanism for publishing messages that are delivered to multiple subscribers.

 

JMS 2.0

Part of JEE 7, Java Message Service 2.0 was released in May 2013, it brings to the developer the advantage to write a few number of code lines to use this technology by introducing a new elements and by supporting resource injection.
It can be used within Java EE Web or EJB applications, or in standalone java application.
Three new interfaces were introduced :

To learn more about JMS 2.0 I recommend highly to read the folowing:
Wiki Page
JSR 343
JEE DOC

 Example:

In our example we will create two stateless EJB whose first acts as producer and the second as consumer. Handled message will be simply a string pushed to a Queue. The broker will be the Glassfish Embedded broker, so no extra install is needed. all what you need is JEE 7 certified server with an IDE and a JDK (for your information I use JDK8 and Eclipse Luna 4.4.1 )

both of these EJBs will be used inside a Servlet.

For both Producer and Consumer, we need to declare a JMSContext annotated by @Inject and @JMSConnectionFactory. And declare a Queue annotated with @Resource.

The @Inject annotation tells the container to inject the JMSContext when it is needed. The @JMSConnectionFactory annotation tells the container the JNDI of the ConnectionFactory that it should use.

@Resource annotation on the Queue marks it as needed by the application. The container will inject an instance of the requested resource into the application component when the component is initialized by defining the jndi name of the resource.

to get the resource name from your glassfish server please in the admin console type this

asadmin_list_ressource

 

 

 

You can also create ConnectionFactory and Queue by typing this

asadmin_add_ressource

 

 

 

 

to see JMS Resources or create new ones inside the graphical console refer to screen below

glassfish_web_console_view_resource

 

Producer

Producer will act as a message sender


package srvEjb;

import javax.annotation.Resource;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.jms.JMSConnectionFactory;
import javax.jms.JMSContext;
import javax.jms.Queue;

import com.srv.RemoteMessageProducer;

/**
 * Stateless Enterprise Java Bean acting as a Message Producer
 *
 * @author Younss AZZAYANI
 *
 */
@Stateless
@Remote(RemoteMessageProducer.class)
public class MessageProducer implements RemoteMessageProducer {
	/**
	 * JMS Context, This combines in a single object the functionality of two
	 * separate objects from the JMS 1.1 API: a Connection and a Session.
	 *
	 */
	@Inject
	@JMSConnectionFactory("jms/TestConnectionFactory")
	JMSContext context;

	/**
	 * Queue
	 */
	@Resource(mappedName = "jms/TestQueue")
	Queue queue;

	/**
	 * Send Message.
	 */
	@Override
	public void sendMessage(String message) {
		/*
		 * createProducer: Creates a new JMSProducer object which can be used to
		 * configure and send messages
		 */
		/*
		 * send: Send a TextMessage with the specified body to the specified
		 * destination, using any send options, message properties and message
		 * headers that have been defined on this JMSProducer.
		 */
		context.createProducer().send(queue, message);
	}
}

inside the sendMessage method we create  JMSProducer  and send the message param to the queue

Consumer
package srvEjb;

import javax.annotation.Resource;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.jms.JMSConnectionFactory;
import javax.jms.JMSContext;
import javax.jms.Queue;

import com.srv.RemoteMessageConsumer;

/**
 * Stateless Enterprise Java Bean acting as a Message Consumer.
 *
 * @author Younss AZZAYANI
 *
 */
@Stateless
@Remote(RemoteMessageConsumer.class)
public class MessageConsumer implements RemoteMessageConsumer {
	/**
	 * JMS Context, This combines in a single object the functionality of two
	 * separate objects from the JMS 1.1 API: a Connection and a Session.
	 *
	 */
	@Inject
	@JMSConnectionFactory("jms/TestConnectionFactory")
	private JMSContext context;
	/**
	 * Queue
	 */
	@Resource(mappedName = "jms/TestQueue")
	Queue queue;

	/**
	 * Receive Message.
	 */
	public String receiveMessage() {
		/*
		 * createConsumer: Creates a JMSConsumer for the specified destination
		 * (queue). A client uses a JMSConsumer object to receive messages that
		 * have been sent to a destination.
		 */
		/*
		 * receiveBody: Receives the next message produced for this JMSConsumer
		 * (context.createConsumer(queue)) and returns its body as an object of
		 * the specified type
		 */
		String message = context.createConsumer(queue)
				.receiveBody(String.class);
		return message;
	}
}

The Servlet (Optionnal):

You can also test your JMS Code by using jUnit or creating a simple App Class with main method.

package com.serv.servlet;

import java.io.IOException;
import java.io.Writer;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.srv.RemoteMessageConsumer;
import com.srv.RemoteMessageProducer;

/**
 * Servlet implementation class JMSServlet
 *
 * @author Younss AZZAYANI
 */

@WebServlet("/jms.html")
public class JMSServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private final static String SENDER_MESSAGE = "message";
	private final static String EMPTY_MESSAGE = "empty message";
	private final static String SPAN_TITLE_BEGIN = "<span style='font-weight:bold;font-style:italic;text-decoration:underline;color:red'>";
	private final static String SPAN_TITLE_END = "</span>";
	private final static String BR = "<br>";
	/**
	 * The producer
	 */
	@EJB
	RemoteMessageProducer producer;
	/**
	 * The Receiver
	 */
	@EJB
	RemoteMessageConsumer consumer;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		/* get */
		String message = request.getParameter(SENDER_MESSAGE);
		if (message == null || message.trim().length() == 0) {
			message = EMPTY_MESSAGE;
		}
		Writer writer = response.getWriter();

		writer.write(SPAN_TITLE_BEGIN + "Producer Message:" + SPAN_TITLE_END
				+ BR);

		writer.write(message + showTime());
		/* sending message */
		producer.sendMessage(message);

		writer.write(BR + SPAN_TITLE_BEGIN + "Consumer message:"
				+ SPAN_TITLE_END + BR);
		/* receiving message */
		String receivedMessage = consumer.receiveMessage();
		writer.write(receivedMessage + showTime());
	}

	private String showTime() {
		return " <span style='font-style:italic;color:green;'>at "
				+ System.currentTimeMillis() + " (Tms)</span>";
	}

}

RemoteMessageProducer and RemoteMessageConsumer are both interfaces implemented respectively by MessageProducer and MessageConsumer

and this is what you have to see when you invoke the servlet

result

Tagged with: , ,
Posted in Java_corner

Devoxx France Java EE 7 Hands on Lab

David Delabassee (@delabassee), Alexis Hassler (@AlexisHassler) and Antoine Sabot-Durand (@antoine_sd) was co animating 

a Lab on Java EE 7 future like Rest, JMS, WebSocket.

see the this link for all the very helpful and useful tutorial.

https://glassfish.java.net/devoxx/

Tagged with: , , , ,
Posted in Java_corner

CKEditor create inner image uploader plugin

I add a new upload plugin to my CKEDITOR that convert image to base64 and attached in the body content of the rich text editor. This is how:

1/in the plugins folder add this Tree

      taswira

        –> image

          –> icon.png
        –> plugin.js

2/ in the plugin.js I added this code:

/*
 * Upload Image
 */
( function() {
	CKEDITOR.plugins
.add(   /* define the plugin name*/
		'taswira',
		{
			requires : [ 'iframedialog' ],
			init : function(editor) {
				var me = this;
				/* define a dialog*/
				CKEDITOR.dialog
					.add(
					'TaswiraDialog',
					function(editor) {
						var lEditor = editor;
						return {
							title : 'Upload Image Dialog',
							minWidth : 550,
							minHeight : 200,
							contents : [ {
								id : 'iframe',
								label : 'Embed Image',
								expand : true,
								elements : [ {
									type : 'html',
									id : 'pageTaswiraEmbed',
									label : 'Embed Image',
									style : 'width : 100%;',
									/* filebrowserImageBrowseLinkUrl is the variable to be set in the config.js, it refer your web image uploader page (servlet or other) that convert your image to Base64 adter submiting form*/
									/* filebrowserImageBrowseLinkUrl (example : uri/imageuploader.html )*/
									html : ''
								} ]
							} ],
							/* when user click on Ok button*/
							onOk : function() {
								for ( var i = 0; i < window.frames.length; i++) {
									if (window.frames[i].name == 'iframeImgEmbed') {
										var content = window.frames[i].document
												.getElementById("taswiraId");
										break;
									}
								}
								/* get the src bas64 value after upload */
								/* <img id="taswiraId" src="data:image/${imageUploadForm.imageType};base64,${sessionScope.imageUploadForm.base64String}"/>*/
								var tmpLink = content.getAttribute('src');
								
								/* give a random id to the uploaded image and update src*/
								var strContent = '<img id="img_id'+ Math.floor(1000 * (Math.random() % 1)) + '" src="'+tmpLink+'"/>';
								var final_html ='MediaEmbedInsertData|---' + escape(strContent) + '---|MediaEmbedInsertData';
								var imgHtml = CKEDITOR.dom.element.createFromHtml(strContent);
								lEditor.insertHtml(strContent);
								var updated_editor_data = editor.getData();
								var clean_editor_data = updated_editor_data.replace(final_html,'<div class="media_embed">'+strContent+'</div>');
								editor.setData(clean_editor_data);

							}
						};
							});

			editor
					.addCommand('taswira',
							new CKEDITOR.dialogCommand(
									'TaswiraDialog'));

			editor.ui.addButton('taswiraBtn', {
				label : 'Embed Image',
				command : 'taswira',
				icon :  this.path + 'image/icon.png'
			});
			}
		});
})();

3 / and then i configure the plugin inside config.js:

...
CKEDITOR.editorConfig = function( config ) {
	config.filebrowserImageBrowseLinkUrl= ckeditorBasePath +'uploadimage.do';
	config.toolbar = [
	              	...
					/* add the button*/
					{ name: 'others', items: [ 'taswiraBtn'] }
	              ];

	              // Toolbar groups configuration.
	              config.toolbarGroups = [
	              	...
					{ name: 'others' }
	              ];
	              config.scayt_autoStartup = false;
				  /* add the plugin*/
	              config.extraPlugins ='iframedialog,taswira';
	             ...

};
...

4/ Voila, everything works fine. i developed an upload servlet/page that convert uploaded image to Base64 string and the plugin reattached to the active ckeditor.

Hope this Help

Posted in Java_corner

Configure DataSource in JBoss Wildfly

I was very surprised when I tried to add a new DataSource (DS) from The WildFly Web console. It’s simply not working like if you try to add a DS in WebSphere ( Strange! yes, but believe me the WebSphere web console is very complete and well documented)

So quickly to add a new DS you have to follow steps below:
(PostgreSQL DB Example):

Inside the module folder at $WILDFLY_HOME/modules add the following sub folders : org/postgresql/main

inside a main folder put the PostgreSQL driver

create an xml file module.xml and copy past the following :

<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:domain:datasources:2.0" name="org.postgresql">
  <resources>
    <resource-root path="postgresql-9.2-1004.jdbc41.jar"/>
  </resources>
  <dependencies>
     <module name="javax.api"/>
     <module name="javax.transaction.api"/>
   </dependencies>
</module>

Go to $WILDFLY_HOME/standalone folder

Edit the file standalone.xml,

inside the tag  <datasources> add the flowing:

<datasource jndi-name="java:jboss/datasources/crmlifeDS" pool-name="crmlifeDS" enabled="true" use-java-context="true">
  <connection-url>jdbc:postgresql://localhost:5432/crmlife_db</connection-url>
  <driver>postgresql</driver>
  <security>
     <user-name>crmlife</user-name>
     <password>crmlife</password>
  </security>
</datasource>

inside the tag  <datasources> add the flowing:

<driver name="postgresql" module="org.postgresql">
  <xa-datasource-class>org.postgresql.xa.PGXADataSource</xa-datasource-class>
</driver>

Start Your server and then test your connection:

wildfly_admin_ds

Posted in Java_corner

Increased Traffic From iOS 7 Users

TechCrunch reported that Onswipe, a “mobile site conversion company that leverages HTML5 to deliver tablet-optimized websites” noticed a “big spike” in traffic from devices running iOS 7.

Tagged with:
Posted in phone