Sunday, 12 June 2016

Java 9 and Project Jigsaw

Standard








What is modularity : as defination
  Designed with standardized units or dimensions, as for easy assembly and repair or flexible arrangement and use: modular furniture; modular homes.
  In Technial We can say develop independed modules which comunicate using standardised interface (separation of concerns,loose coupling)
  Modularity composed of standardized, self-contained units for easy construction and flexible use.
 


Packages vs module
 
   Package: It is bunch of class(.java) file which is separate by their function or their name. so it is also help for naming,A package is a namespace; it let's you handle naming conflicts.
  
   Module: Large applications are typically built in several parts, which are more tightly connected to each other than to the outside. Therefore, one would like to give these parts more access to each other than the outside world has. One might also want these parts reused at many points in the system without worrying about the synchronization of shared data. this part is called module in java. WAR,EAR jar etc are called module in java language.

Why is modularity required? 
Better encapsulation:  Currently, every public class/interface and every public method is published to the world.  If the intention is to only make a method or class available among more than one package within an application it cannot be encapsulated without carefully omitting said classes from whatever jars a library publishes to client applications.  With a proper module system, a package may be marked as internal to the module and its contents available throughout the module but not to the outside world.  This in turn imposes discipline and makes it much easier for developers to publish more compact APIs, since potentially only one package out of several internal packages could be made visible to the outside world.

  • Versioning: Currently, Java developers much publish versions by hacking the manifest file within a Jar file.  This means there is no intrinsic support for publishing versions or making dependencies among modules clear.   With modularity, it becomes possible for module B to publish that it requires module A version 3 (or versions 3-4), and that any module A version lower than 2 will possibly break module B's functionality.  The lack of such a mechanism is one of the causes of "jar hell" experienced by Java developers.  There are ways around this, such as using the file system (ex a sub-directory of a package directory is the version identifier), but they're far less elegant than a proper module system.
  • Compile-time and runtime symmetry:  Java compile time and runtime dependencies are orthogonal, which causes problems such as the potential for ClassDefNotFound errors.   A proper module system guarantees that compile time and runtime dependencies are satisfied atomically.
  • Tooling:  IDEs should be able to more easily manage a project's dependencies.
  • Deployment and module repositories:  Given the compile time and runtime symmetry above, it will be possible to publish modules within repositories, either on the web or internally on a company network.   This will eliminate a whole host of deployment issues as this mechanism is greatly superior to the currently one of managing jars and classpaths by hand (or within scrips), or any workaround involving an internal filesystem.   Caching of remote modules also becomes possible.
  • Separate Release Schedules:  It should be possible for Oracle to release various libraries separately, according to their own schedules, instead of waiting for the window where the entirely next version of the JDK is deployed.   For example, a new version of a concurrency library with desirable improvements could be published between JDK releases.
  • Quarantine of legacy APIs:  The JDK is currently a monolithic blob of unrelated functionality that's packaged together.  This means if all I want is to run a simple Java program, I need to download CORBA, Swing, the legacy Date/Time API, etc, (especially APIs that have been marked deprecated) even if I only use a subset of the functionality.   What's more, with every new version of the JDK, this functionality must be kept up to date and the commitment has been made to maintain all of these classes.  With modules, this legacy functionality can be quarantined from the rest of the JDK and put into strict maintenance mode, to be used only by those who need them and Oracle's backward compatibility burden could potentially be significantly reduced.
What is Jigsaw

 Java Platform Module System – commonly known as Project Jigsaw, or JSR 376 – is that it has been used to break apart the monolithic Java runtime into smaller modules.
 JEP 201: Modular Source Code


 Class loaders - Jigsaw will not use class loader; it's up to runtimes (such as application servers or OSGi) to work with modules and class loaders

Dependencies - Jigsaw will allow to specify dependency on modules by name but not at the package level

Dynamic Services - The runtime services model provided by OSGi will not be provided by Jigsaw
Jigsaw is not intended to replace and/or compete with any other runtime or build time module system (such as OSGi or Maven). In fact, it's the intention of Jigsaw to be interoperable (somehow) with both.

JEPs
200: The Modular JDK
Module summary
201: Modular Source Code
220: Modular Run-Time Images
260: Encapsulate Most Internal APIs
261: Module System
282: jlink: The Java Linker

http://openjdk.java.net/projects/jigsaw/

Download : https://jdk9.java.net/download/

 Referances :
   http://openjdk.java.net/projects/jigsaw/spec/sotms/
   http://openjdk.java.net/projects/jigsaw/spec/sotms/
   http://www.merriam-webster.com/dictionary/modular
   https://en.wikipedia.org/wiki/Modular_programming
   http://stackoverflow.com/questions/13157377/class-vs-package-vs-module-vs-component-vs-container-vs-service-vs-platform-in-j
   http://ldegruchy.blogspot.com/2014/09/java-9-modularity-is-enough.html
  


Friday, 15 April 2016

Reading email (Gmail,Yahoo,Outlook/live) using java code

Standard
I have requirement to read user email box with user permissions and display contents in single inbox.
Program will ask user input userid/password and we also pass param to identify gmail or yahoo etc.

package com.java.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;

/**
 *
 * @author vaquar.khan@gmail.com
 *
 */
public class EmailReader {

final  private static String MAIL_STORE="mail.store.protocol";
final  private static String IMAP="imaps";
//
final  private static String GMAIL_IMAP="imap.gmail.com";
final  private static String GMAIL_EMAIL_ID="";
final  private static String GMAIL_EMAIL_PASSWORD="";
//
final  private static String YAHOO_IMAP="imap.mail.yahoo.com";
final  private static String YAHOO_EMAIL_ID="";
final  private static String YAHOO_EMAIL_PASSWORD="";
//
final  private static String MICROSOFT_IMAP="imap-mail.outlook.com";
final  private static String MICROSOFT_EMAIL_ID="";
final  private static String MICROSOFT_EMAIL_PASSWORD="";

   public static void main(String args[]) {
   
    readEamil("MICROSOFT") ;
   }


    public static void readEamil(String emailType) {
        Properties props = System.getProperties();
        props.setProperty(MAIL_STORE, IMAP);
        try {
                Session session = Session.getDefaultInstance(props, null);
                Store store = session.getStore(IMAP);

                if(emailType=="GMAIL"){
                // IMAP host for gmail.
                store.connect(GMAIL_IMAP, GMAIL_EMAIL_ID, GMAIL_EMAIL_PASSWORD);
                }else if(emailType=="YAHOO"){
                // IMAP host for yahoo.
                store.connect(YAHOO_IMAP, YAHOO_EMAIL_ID, YAHOO_EMAIL_PASSWORD);
                }else if(emailType=="MICROSOFT"){
                // IMAP host for MICROSOFT.
                store.connect(MICROSOFT_IMAP, MICROSOFT_EMAIL_ID, MICROSOFT_EMAIL_PASSWORD);
                }
                System.out.println(store);

                Folder inbox = store.getFolder("Inbox");
                inbox.open(Folder.READ_ONLY);
               
                BufferedReader optionReader = new BufferedReader(new InputStreamReader(System.in));
                System.out.println("Press (U) to get only unread mails OR Press (A) to get all mails:");
                try {
                    char answer = (char) optionReader.read();
                    if(answer=='A' || answer=='a'){
                        showAllMails(inbox);
                    }else if(answer=='U' || answer=='u'){
                        showUnreadMails(inbox);
                    }
                    optionReader.close();
                } catch (IOException e) {
                    System.out.println(e);
                }
               
        } catch (NoSuchProviderException e) {
            System.out.println(e.toString());
            System.exit(1);
        } catch (MessagingException e) {
            System.out.println(e.toString());
            System.exit(2);
        }

    }
   
    static public void showUnreadMails(Folder inbox){      
        try {
            FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
            Message msg[] = inbox.search(ft);
            System.out.println("MAILS: "+msg.length);
            for(Message message:msg) {
                try {
                    System.out.println("DATE: "+message.getSentDate().toString());
                    System.out.println("FROM: "+message.getFrom()[0].toString());          
                    System.out.println("SUBJECT: "+message.getSubject().toString());
                    System.out.println("CONTENT: "+message.getContent().toString());
                    System.out.println("******************************************");
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    System.out.println("No Information");
                }
            }
        } catch (MessagingException e) {
            System.out.println(e.toString());
        }
    }
   
    static public void showAllMails(Folder inbox){
        try {
            Message msg[] = inbox.getMessages();
            System.out.println("MAILS: "+msg.length);
            for(Message message:msg) {
                try {
                    System.out.println("DATE: "+message.getSentDate().toString());
                    System.out.println("FROM: "+message.getFrom()[0].toString());          
                    System.out.println("SUBJECT: "+message.getSubject().toString());
                    System.out.println("CONTENT: "+message.getContent().toString());
                    System.out.println("******************************************");
                } catch (Exception e) {
                    System.out.println("No Information");
                }
            }
        } catch (MessagingException e) {
            System.out.println(e.toString());
        }
    }

}

Saturday, 19 March 2016

Reading multiple html files into folder parse and store into csv file

Standard


Image result for jsoup
Jsoup is a Java library for working with real-world HTML. It provides a very convenient API for extracting and manipulating data, using the best of DOM, CSS, and jquery-like methods.

Example :

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class HTMLParser {

public static void main(String[] args) {
Document doc = null;

{
FileWriter writer =null;
System.out.println("--------------------------Program started--------------------------");
try {
writer = new FileWriter("c:\\Temp\\abc_search_data.csv");

       File input = new File("C:\\My Web     Sites\\http___www.abcd.com_\\www.abcd.com\\library\\html\\");

File[] st = input.listFiles();

for (int i = 0; i < st.length; i++) {
if (st[i].isFile()) {// other condition like name ends in
// html

// parse(st[i]);

doc = Jsoup.parse(st[i], null);

// get page title
String title = doc.title();
System.out.println("title : " +"["+i+"]"+ title);
//
String ownText = doc.body().ownText();
String text = doc.body().text();
//
//System.out.println("ownText" + ownText + "\n");
//System.out.println("text" + text);
//
 
     writer.append("title : "+"["+i+"]");
     writer.append(',');
     writer.append(title);
     writer.append('\n');

    /* writer.append("ownText");
     writer.append(',');
     writer.append(ownText);
     writer.append('\n');*/
     
     writer.append("text : "+"["+i+"]");
     writer.append(',');
     writer.append(text);
       writer.append('\n');

}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
writer.flush();
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println("--------------------------Program End--------------------------");
}

}

Tuesday, 15 March 2016

Magic Tool JHpster

Standard
What Is JHipster?


 +  +  = 
The term 'JHipster' comes from 'Java Hipster', as its initial goal was to use all the modern and 'hype' tools available at the time.[Today, it has reached a more enterprise goal, with a strong focus on developer productivity, tooling and quality.
Major functionalities
  • Generate a full stack application, with many options
  • Generate CRUD entities
  • Database migrations with Liquibase
  • NoSQL databases support (Cassandra, MongoDB)
  • Elasticsearch support
  • Websockets support
  • Automatic deployment to CloudFoundry, Heroku, OpenShift

Technology stack
  • HTML5 Boilerplate
  • Twitter Bootstrap
  • AngularJS
  • Full internationalization support with Angular Translate
  • Optional Compass / Sass support for CSS design
  • Optional WebSocket support with Spring Websocket
On the server side:
  • Spring Boot
  • Spring Security
  • Spring MVC REST + Jackson
  • Monitoring with Metrics
  • Optional WebSocket support with Spring Websocket
  • Spring Data JPA + Bean Validation
  • Database updates with Liquibase
  • Elasticsearch support
  • MongoDB support
Out-of-the-box auto-configured tooling:
  • Yeoman
  • Grunt or Gulp.js
  • BrowserSync
  • Maven or Gradle


jHipster, generates full stack web application using Angular and Spring ! Look at the great questions it asks when creating jHipster application !
Imagine the comfort you get by having all these dependencies in your app right there when you start the development !
Hmm.. There are so many technologies embedded as a inherient part of jHipster.
HTML5BoilerPlate- So you dont have to worry adding things like Modernizer on your own. This boiler plate takes care of old browsers too, so many old-school browsers got taken care of.
Twitter Bootstrap: Need to talk anything about this most popular project on Github ?
Bower: Dependency management on client side ! Very popular now a days !
Karma, PhantomJS: When it is angular, no need to really mention this as it comes part of Angular. But just not to forget !
Following on server side !
Boot should be mentioned again and again because Boot was mentioned again and again in this year's SpringOne (which I did not attend btw :) , for architecture style of Micro-service. Spring guys have Boot everywhere now a days !
And when it is Spring world, I dont have to mention Spring Security, Spring MVC etc Right ?
I am also so much impressed with what jHipster has for production readiness ! Monitoring with Metrix (which I dont know !) , caching with something called HazerCast (sorry, Dont kno

JHipster is a Yeoman generator, used to create a Spring Boot + AngularJS project. 
JHipster provides tools to generate a project with a Java stack on the server side (using Spring Boot) and a responsive Web front-end on the client side (with AngularJS and Bootstrap).
What is the base name of your application?
Would you like to use Maven or Gradle? -So, decide your server side build manager 
What is your default Java package name?
Do you want to use Java 8? -Cool !
Which *type* of authentication would you like to use? -Superb ! You can also choose OAuth
Which *type* of database would you like to use?SQL / NoSQL ?
Do you want to use Hibernate 2nd level cache? -Hardcore server side engineers know how it helps !
Do you want to use clustered HTTP sessions?So by default, very minimal in session, almost stateless which is need for scalability.
Do you want to use WebSockets?Applause 
Which *production* database would you like to use?Means, you can have different databases already configured in production and development.
Which *development* database would you like to use?
Would you like to use Grunt or Gulp.js for building the frontend?Cool - Options here too Would you like to use the Compass CSS Authoring Framework?Incredible ! Compass is most advanced tool to generate CSS.

Sakai

Standard

Sakai is a free, community source, educational software platform designed to support teaching, research and collaboration. Systems of this type are also known as Course Management Systems (CMS), Learning Management Systems (LMS), or Virtual Learning Environments (VLE). Sakai is developed by a community of academic institutions, commercial organizations and individuals. It is distributed under the Educational Community License (a type of open source license).


Sakai setup

1) download java 8
2) download tomca t8
3) download sakai 10 demo

Set environment variable  

CATALINA_HOME
C:\apache-tomcat-8.0.30
JAVA_HOME
C:\Program Files\Java\jdk1.8.0_65
JRE_HOME
C:\Program Files\Java\jre1.8.0_66
PATH
C:\Users\vaqua_000\AppData\Roaming\npm;C:\Program Files\Java\jdk1.8.0_65\bin;C:\Program Files (x86)\Java\jre1.8.0_66\bin;C:\apache-tomcat-8.0.30\bin


Go to oracle.com and install java jre 8(check not be installed java 6 plz)

After that go to C:/Program files/java/jre8/bin

Here create an folder called "Server" (without " ")

Now go into the C:/Program files/java/jre7/bin/client folder

COPY all data of this folder into the new C:/Program files/java/jre8/bin/Server



Wait 10 min to start tomcat server then open in  browser 


Default sakai password is admiin/admin