Saturday, May 12, 2018

Collection Framework in Java Script -

A Collection Framework class contains all basic classes like Stack, Queue, HashMap, ArrayList, Set Download Here
define(['require','CONSTANT'], 
    function ( require, CONSTANT ) {
        /**
		 * A Collection Framework class contains all basic classes like Stack, Queue, HashMap, ArrayList, Set
		 * @name Collections
		 * @class Collections
		 * @example require('Collections')
		 * @exports Collections
		 * @version 1.0
		 * @module Collections
		 * @augments CONSTANT
		 **/
		var Collections = {
			
			 /**
			 * Object types provided by Collections 
			 * @name TYPE
			 * @class TYPE
			 * @example require('Collections').TYPE.STACK
			 * @example require('Collections').TYPE.ARRAYLIST
			 * @example require('Collections').TYPE.HASHMAP
			 * @example require('Collections').TYPE.SET
			 * @example require('Collections').TYPE.QUEUE
			 * @example require('Collections').TYPE.TREE
			 * @exports TYPE
			 * @version 1.0
			 * @module Collections
			 * @memberOf Collections
			 * @field
			 **/
			TYPE:{
				/** @constant*/
				STACK:"Stack",
				ARRAYLIST:"ArrayList",
				HASHMAP:"HashMap",
				SET:"Set",
				QUEUE:"Queue",
				TREE:"Tree"
			},
	        /**
			 * A Stack is a Collection that contains duplicate values. Last In First Out. 
			 * @name Stack
			 * @class Stack
			 * @example require('Collections').Stack()
			 * @exports Stack
			 * @version 1.0
			 * @module Collections
			 * @memberOf Collections
			 **/
			Stack: 	function () {
				var stac = [];
				var stackObj = {
					/**
					 * @name pop
					 * @memberOf Collections.Stack
					 * @method 
					 * @description removes the top item from teh stacks
					 * @return {Object} item 
					 * @function
					 */
					pop : function() {
						return stac.pop();
					},
					/**
					 * @name push
					 * @memberOf Collections.Stack
					 * @method 
					 * @description removes the top item from teh stacks
					 * @param {Object} item
					 * @return {null}  
					 * @function
					 */
					push : function(item) {
						stac.push(item);
					},
					/**
					 * @name isEmpty
					 * @memberOf Collections.Stack
					 * @method 
					 * @description returns true if teh Stack is empty.
					 * @return {boolean}  
					 * @function
					 */
					isEmpty : function() {
						return stac.length == 0;
					},
					/**
					 * @name objType
					 * @memberOf Collections.Stack
					 * @method 
					 * @description returns teh Object type as "Stack"
					 * @return {String} ObjectType  
					 * @function
					 */
					objType : function(){
						return "Stack";
					},
					/**
					 * @name getElements
					 * @memberOf Collections.Queue
					 * @method 
					 * @description returns teh Elemnts in the Queue
					 * @return {Object[]} itemArray  
					 * @function
					 */
					getElements : function(){
						return stac.clone();
					},
					/**
					 * @name toString
					 * @memberOf Collections.Stack
					 * @method 
					 * @description returns the JSON data of teh Object
					 * @return {String} ObjectType  
					 * @function
					 */
					toString : function(){
						return "["+stac.join()+"]";
					},
					/**
					 * @name clone
					 * @memberOf Collections.Stack
					 * @method 
					 * @description returns Collection.Stack a new Stack with the cloned object of the items.
					 * @return {Collections.Stack}
					 * @function
					 */
					clone:function(){
						var Collection = require('Collections');
						var cloneStack = Collection.Stack();
						var elements = stac;
						for(var i=0;i=0; i--){
							if(elements[i].clone)
								cloneQueue.add(elements[i].clone());
							else
								cloneQueue.add(elements[i]);
						}
						return cloneQueue;
					}
				};
				return queueObj;
			},
			/**
			 * An ArrayList is a Collection that contains duplicate values. 
			 * @name ArrayList
			 * @class ArrayList
			 * @example require('Collections').ArrayList()
			 * @exports ArrayList
			 * @version 1.0
			 * @module ArrayList
			 * @memberOf Collections
			 **/
			ArrayList : function() {
				var arr = [];
				var array = {
					/**
					 * @name add
					 * @memberOf Collections.ArrayList
					 * @method 
					 * @description insert an Item to the ArrayList, it adds to the last of the array, It allows duplicate values in the list.
					 * @param {Object} item
					 * @return {null} 
					 * @function
					 */
					add : function(item) {
						arr.push(item);
					},
					/**
					 * @name addAll
					 * @memberOf Collections.ArrayList
					 * @method 
					 * @description insert an array of Items to the ArrayList, it adds to the last of the array, It allows duplicate values in the list.
					 * @param {Object[]} itemArray
					 * @return {null} 
					 * @function
					 */
					addAll : function(items) {
						for(var i=0; i< items.length; i++)
							this.add(items[i]);
					},
					/**
					 * @name indexOf
					 * @memberOf Collections.ArrayList
					 * @method 
					 * @description returns teh index of teh item in the ArrayList, if item not found it returns -1.
					 * @param {Object} item
					 * @return {integer} 
					 * @function
					 */
					indexOf : function(item) {
						return arr.indexOf(item);
					},
					/**
					 * @name contains
					 * @memberOf Collections.ArrayList
					 * @method 
					 * @description returns whether the item present in the ArrayList.
					 * @param {Object} item
					 * @return {boolean} 
					 * @function
					 */
					contains:function(item){
						return arr.indexOf(item) != -1;
					},
					/**
					 * @name remove
					 * @memberOf Collections.ArrayList
					 * @method 
					 * @description remove an item from the array, then the remaining items will be shifted left, and their index will be reduced by 1.
					 * @param {Object} item
					 * @return {null} 
					 * @function
					 */
					remove : function(item) {
						if (arr.indexOf(item) >= 0)
							arr.splice(arr.indexOf(item), 1);
					},
					/**
					 * @name size
					 * @memberOf Collections.ArrayList
					 * @method 
					 * @description returns the number of the Elements present in the ArrayList.
					 * @return {integer} 
					 * @function
					 */
					size:function(){
						return arr.length;
					},
					/**
					 * @name get
					 * @memberOf Collections.ArrayList
					 * @method 
					 * @description returns the object at the prvided index.
					 * @param {integer} index
					 * @return {Object} item 
					 * @function
					 */
					get : function(index){
						return arr[index];
					},
					/**
					 * @name set
					 * @memberOf Collections.ArrayList
					 * @method 
					 * @description set an item at the specified location
					 * @param {integer} index
					 * @param {Object} Item
					 * @return {null}  
					 * @function
					 */
					set:function(index, item){
						if(index<0) throw "Index out of bound exception";
						arr[index]=item;
					},
					/**
					 * @name getElements
					 * @memberOf Collections.ArrayList
					 * @method 
					 * @description returns teh Elemnts in the ArrayList
					 * @return {Object[]} itemArray  
					 * @function
					 */
					getElements : function(){
						return arr.clone();
					},
					/**
					 * @name objType
					 * @memberOf Collections.ArrayList
					 * @method 
					 * @description returns teh Object type as "ArrayList"
					 * @return {String} ObjectType  
					 * @function
					 */
					objType:function(){
						return "ArrayList";
					},
					/**
					 * @name toString
					 * @memberOf Collections.ArrayList
					 * @method 
					 * @description returns the JSON data of teh Object
					 * @return {String} ObjectType  
					 * @function
					 */
					toString : function(){
						return "["+arr.join()+"]";
					},
					/**
					 * @name json
					 * @memberOf Collections.ArrayList
					 * @method 
					 * @description returns the JSON string
					 * @return {String} json  
					 * @function
					 */
					json :function(){
						var jsonArr=[];
						for(var i=0; i

Thursday, May 10, 2018

How to set the max size of upload file in Spring Boot embedded Apache Tomcat

Error in spring boot : org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field uploadfile exceeds its maximum permitted size of 1048576 bytes. I found the solution at Expert Exchange, which worked well.
@Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize("124MB");
        factory.setMaxRequestSize("124MB");
        return factory.createMultipartConfig();
    }
Expert Exchange

Wednesday, November 8, 2017

Error while connecting Hive

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/hive/service/rpc/thrift/TCLIService$Iface
 at org.apache.hive.jdbc.HiveDriver.connect(HiveDriver.java:107)
 at java.sql.DriverManager.getConnection(Unknown Source)
 at java.sql.DriverManager.getConnection(Unknown Source)
 at io.saagie.example.hive.Main.main(Main.java:39)
Caused by: java.lang.ClassNotFoundException: org.apache.hive.service.rpc.thrift.TCLIService$Iface
 at java.net.URLClassLoader.findClass(Unknown Source)
 at java.lang.ClassLoader.loadClass(Unknown Source)
 at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
 at java.lang.ClassLoader.loadClass(Unknown Source)
 ... 4 more

Thursday, October 26, 2017

Execute Shell script in Java Program


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;

import org.apache.log4j.Logger;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;

public class ExecuteScriptInServer {
 private static final Logger logger = Logger.getLogger(ExecuteScriptInServer.class);

 public static void main(String[] args) {
  JSch jsch = new JSch();
  Session session = null;
  try {
   InetAddress addr = InetAddress.getLocalHost();
   logger.info("Local HostAddress: " + addr.getHostAddress());
   String hostname = addr.getHostName();
   logger.info("Local host name: " + hostname);
   session = jsch.getSession("root", "10.1.11.4", 22);//UserName, Pasword, Port
   jsch.setKnownHosts(new FileInputStream(new File("known_hosts.txt")));// This file can be generated using ssh-keygen -t rsa Command in the Unix Machine.
   UserInfo ui = new MyUserInfo();
   session.setUserInfo(ui);
   logger.info("Connecting...");
   session.setPassword("password".getBytes());
   session.connect();
   System.out.println("Connected");
   executeCommand(session, "pwd");
   session.disconnect();

   logger.info("Connected");
  } catch (JSchException e) {
   logger.info(e.getMessage());
   e.printStackTrace();
  } catch (Exception e) {
   e.printStackTrace();
   logger.info(e.getMessage());
  } finally {
   session.disconnect();
   logger.info("Disconnected....");
  }
 }

 private static void executeCommand(Session session, String command) throws JSchException, IOException {
  Channel channel = session.openChannel("exec");
  ((ChannelExec) channel).setCommand(command);
  channel.setInputStream(null);
  ((ChannelExec) channel).setErrStream(System.err);
  InputStream in = channel.getInputStream();

  channel.connect();

  byte[] tmp = new byte[1024];
  while (true) {
   while (in.available() > 0) {
    int i = in.read(tmp, 0, 1024);
    if (i < 0)
     break;
    System.out.print(new String(tmp, 0, i));
   }
   if (channel.isClosed()) {
    System.out.println("exit-status: " + channel.getExitStatus());
    break;
   }
   try {
    Thread.sleep(1000);
   } catch (Exception ee) {
   }
  }
  channel.disconnect();
 }

 public static class MyUserInfo implements UserInfo, UIKeyboardInteractive {

  @Override
  public String getPassphrase() {
   return null;
  }

  @Override
  public String getPassword() {
   return null;
  }

  @Override
  public boolean promptPassphrase(String arg0) {
   return false;
  }

  @Override
  public boolean promptPassword(String arg0) {
   return false;
  }

  @Override
  public boolean promptYesNo(String arg0) {
   return false;
  }

  @Override
  public void showMessage(String arg0) {
  }

  @Override
  public String[] promptKeyboardInteractive(String arg0, String arg1, String arg2, String[] arg3,
    boolean[] arg4) {
   return null;
  }
 }

}


Tuesday, May 17, 2016

How to send Email using GMail with Java Mail API

I just finished with sending Email using Java Mail by connecting the Gmail SMTP.

package org.core.mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.AddressException;

public class SendEmailUsingGMailSMTP {
 public static void main(String[] args) throws AddressException, MessagingException {
  Properties mailServerProperties;
  Session getMailSession;
  MimeMessage generateMailMessage;
  mailServerProperties = System.getProperties();
  mailServerProperties.put("mail.smtp.port", "465");
  mailServerProperties.put("mail.smtp.socketFactory.port", "465");
  mailServerProperties.put("mail.smtp.socketFactory.class",
    "javax.net.ssl.SSLSocketFactory");
  mailServerProperties.put("mail.smtp.auth", "true");
  mailServerProperties.put("mail.smtp.starttls.enable", "true");
  System.out.println("Mail Server Properties have been setup successfully..");
 
  getMailSession = Session.getDefaultInstance(mailServerProperties, null);
  generateMailMessage = new MimeMessage(getMailSession);
  generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress("to@gmail.com"));
  generateMailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress("cc@gmail.com"));
  generateMailMessage.setSubject("Test Mail from Java Mail");
  String emailBody = "Test email by Java Mail JavaMail API example. " + "\n Regards, \nAdmin";
  generateMailMessage.setContent(emailBody, "text/html");
  System.out.println("Mail Session has been created successfully..");
 

  Transport transport = getMailSession.getTransport("smtp");
 
  transport.connect("smtp.gmail.com", "mail@gmail.com", "password");
  transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
  transport.close();
 }
}

Please ensure the Gmail account is NOT using Gmail 2 Step Verification, and allow less secure apps to have access,

Because Java Mail works here as a Less secure App.
You can do it using following Link

https://www.google.com/settings/security/lesssecureapps


If we want to sent the HTML content Email with an attachment, try the following
package org.core.mail;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;

public class SendEmailUsingGMailSMTP {
 public static void main(String[] args) throws AddressException, MessagingException, IOException {
  String emailAddress = "fromemail@gmail.com";
  String emailBody = "Test email by Java Mail using JavaMail API example. "
    + "\n Regards, \n Asker";
  //call readFile to read the HTML template file and send it through email, and attach the the image from the resourse we have. 
  //emailBody = readFile()
  sendEmail(emailAddress, emailBody);
 }

 public static void sendEmail(String emailAddress, String emailBody) throws AddressException, MessagingException, IOException {

  // Step1
  System.out.println("\n 1st ===> setup Mail Server Properties..");
  Properties mailServerProperties;
  Session mailSession;
  MimeMessage mailMessage;
  mailServerProperties = System.getProperties();
  mailServerProperties.put("mail.smtp.port", "465");
  mailServerProperties.put("mail.smtp.socketFactory.port", "465");
  mailServerProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  mailServerProperties.put("mail.smtp.auth", "true");
  mailServerProperties.put("mail.smtp.starttls.enable", "true");
  System.out.println("Mail Server Properties have been setup successfully..");

  // Step2
  System.out.println("\n\n 2nd ===> get Mail Session..");
  mailSession = Session.getDefaultInstance(mailServerProperties, null);
  mailMessage = new MimeMessage(mailSession);
  mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress));
  mailMessage.setSubject("Greetings from Asker..");
  System.out.println("Mail Session has been created successfully..");
  
  MimeBodyPart messageBodyPart1 = new MimeBodyPart();
  messageBodyPart1.setHeader("Content-Type", "text/html");
  DataSource dataSourceHtml= new ByteArrayDataSource(emailBody, "text/html");
  messageBodyPart1.setDataHandler(new DataHandler(dataSourceHtml));

  // 4) create new MimeBodyPart object and set DataHandler object to
  // this object
  MimeBodyPart messageBodyPart2 = new MimeBodyPart();
  
  URL url=SendEmailUsingGMailSMTP.class.getResource("lesssecure.jpg");
  DataSource source = new FileDataSource(url.getFile());
  messageBodyPart2.setDataHandler(new DataHandler(source));
  messageBodyPart2.setFileName("My Image.jpg");

  // 5) create Multipart object and add MimeBodyPart objects to this
  // object
  Multipart multipart = new MimeMultipart();
  multipart.addBodyPart(messageBodyPart1);
  multipart.addBodyPart(messageBodyPart2);
  
  mailMessage.setContent(multipart);

  // Step3
  System.out.println("\n\n 3rd ===> Get Session and Send mail");
  Transport transport = mailSession.getTransport("smtp");

  // Enter your correct gmail UserID and Password
  // if you have 2FA enabled then provide App Specific Password
  transport.connect("smtp.gmail.com", "email@gmail.com", "password");
  transport.sendMessage(mailMessage, mailMessage.getAllRecipients());
  transport.close();
 }
  private static String readFile( ) throws IOException, URISyntaxException {
      BufferedReader reader = new BufferedReader( new FileReader (new File(SendEmail.class.getResource("template.html").toURI())));
      String         line = null;
      StringBuilder  stringBuilder = new StringBuilder();
      String         ls = System.getProperty("line.separator");

      try {
          while( ( line = reader.readLine() ) != null ) {
              stringBuilder.append( line );
              stringBuilder.append( ls );
          }
          return stringBuilder.toString();
      } finally {
          reader.close();
      }
  }
}


Askerali Maruthullathil

Sunday, May 15, 2016

How to email the charts generated by google charts or any image.

I had a requirement to send the charts generated by Google Charts to the user email address.
I found the solution as follows.

If we render the image using SVG, i couldnt found an option to send the image, But base64 data can be sent using ajax and the server can save it.

Steps
1.       Render the Chart as follows. It will render image in Base64 format.
      // Wait for the chart to finish drawing before calling the getImageURI() method.
      google.visualization.events.addListener(chart, 'ready', function () {
        chart_div.innerHTML = '<_ _="" id="chartIMG" img="" src="' + chart.getImageURI() + '">';
        console.log(chart_div.innerHTML);
      });
A google provided example here 
2.       Now the chart_div.innerHTML will have the Base64 image,
3.       Send the Base 64 Image to the server on button click or any action.
4.       Create a Servlet to handle the request with Base64 Image data.
5.       Convert the Base64 Image data to a PNG image using the following code.
Base64.Decoder decoder = Base64.getDecoder();
      byte[] imgBytes = decoder.decode(value);
      FileOutputStream osf = new FileOutputStream(new File("MyChart,png"));
      osf.write(imgBytes);
      osf.flush();
6.       Using Java SMTP server send an email with HTML template, add this image link to the email as html email template designed.
7.       Send the email, I used hMailServer to send it, but you can integrate any existing mail server

Some references on How Embedd image in email and its short comings as follows.

  1. Base64 Image sending Issue : https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/
  2. Embedding technique : https://sendgrid.com/blog/embedding-images-emails-facts/


Regards
Asker

Wednesday, March 16, 2016

A Bug with Microsoft Outlook - Showing unread mail in Taskbar

As the email system is configured in different systems like Laptop mobile etc...
Once you read the mail from any one of the device it should be updated on all the devices automatically.

In Outlook it does that, but never removes the notification from the desktop, I feel it is a disturbing thing in desktops, and push you to check what is the new mail is...

To remove this icon the only option in the outlook is close the outlook and reopen it.


Here I have read the mail from mobile, In the list of mails and the inbox is cleared, but it is showing new mail icon in the TaskBar.