Pages

Moving a directory with its content in java

Sometimes we want to move a folder with its content from one location to another location but there is no native method in java(upto java7) to move a directory with its content. We can only move an empty directory

To move the directory with its content use the apache common io.

The code snippest is given below-


public class FileMove {
       private String destination;

    public void moveFile(File dir) {


    File destDir = new File(destination);

    try {

        FileUtils.moveDirectoryToDirectory(dir, destDir, false);


    } catch (IOException e) {

        e.printStackTrace();
    }
    }



Connecting to Alfresco repository using OpenCmis

This is the code snippest for accessing Alfresco repository using Apache Chemistry OpenCmis library for java. In this code we have used AtomPub protocal for binding. 
The url for AtomPub binding is"http://192.168.1.103:8081/alfresco/cmisatom"

package com.esc.cmis.client.services;

import java.util.List;
import java.util.HashMap;
import java.util.Map;

import org.apache.chemistry.opencmis.client.api.CmisObject;
import org.apache.chemistry.opencmis.client.api.Document;
import org.apache.chemistry.opencmis.client.api.Folder;
import org.apache.chemistry.opencmis.client.api.ItemIterable;
import org.apache.chemistry.opencmis.client.api.Repository;
import org.apache.chemistry.opencmis.client.api.Session;
import org.apache.chemistry.opencmis.client.api.SessionFactory;
import org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl;
import org.apache.chemistry.opencmis.commons.SessionParameter;
import org.apache.chemistry.opencmis.commons.data.RepositoryInfo;
import org.apache.chemistry.opencmis.commons.enums.BindingType;
import org.apache.chemistry.opencmis.commons.exceptions.CmisConnectionException;
import org.apache.chemistry.opencmis.commons.exceptions.CmisRuntimeException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 *
 * @author Ashutosh kumar
 *
 */
public class AlfrescoService {

 private static Session session;

   
 public Session connect() {
  System.out.println("Trying to connect Fo alfresco.......");
  SessionFactory sessionFactory=SessionFactoryImpl.newInstance();

  //Connection parameter
  Map<String, String> parameter = new HashMap<>();

  parameter.put(SessionParameter.USER, "admin");
  parameter.put(SessionParameter.PASSWORD, "admin");
  parameter.put(SessionParameter.ATOMPUB_URL,
                     "http://192.168.1.103:8081/alfresco/cmisatom");
  parameter.put(SessionParameter.BINDING_TYPE,
                                    BindingType.ATOMPUB.value());
  parameter.put(SessionParameter.OBJECT_FACTORY_CLASS,
      "org.alfresco.cmis.client.impl.AlfrescoObjectFactoryImpl");

  List<Repository> repositories = sessionFactory

                                     .getRepositories(parameter);

  // Establish a seesion to a repository

  System.out.println("Connection establishes to FO alfresco");
  session = repositories.get(0).createSession();

  // Get some repository info

  System.out.println("Repository Name: "
                + session.getRepositoryInfo().getName());
  System.out.println("Repository ID: "
                + session.getRepositoryInfo().getId());
  System.out.println("CMIS Version: "
                + session.getRepositoryInfo().getCmisVersion());
  RepositoryInfo i = session.getRepositoryInfo();
  System.out.println(i.getDescription());
  System.out.println(i.getProductName());
  return session;
        // company home
        // Folder folder = session.getRootFolder();
        // return folder;
    }

  

    public void createFolder() {

    }


  public void listFolder(Folder folder) {


    ItemIterable<CmisObject> children = folder.getChildren();

        for (CmisObject o : children) {
            System.out.println(o.getName());
            System.out.println(o.getId());
        }
    }

   public CmisObject getCmisObject(String path) {

     CmisObject cmisObject = session.getObjectByPath(path);
     return cmisObject;
    }

   // Getting the id of an object from its path

   public void getId(String path) {
     String path1 = "/vvf";
     Document doc = (Document) session.getObjectByPath(path1);
     String id = doc.getId();
     System.out.println(id + "''''''''");
    }

    public void moveDocument() {

    }
}

Some points about Web Browser


As all of us aware of the term “Web Browser”. Web Browser is the most widely used software. Web Browser is an application porgram which we used to access the internet.

There are many types of web browsers. Some most commonly used web browsers are-
FireFox, Google Chrome, IE , Opera, Safari.

In this post I will tell you some internal of web browsers , like what is the main component of browsers and How they works?

As we know that browser shows web page. Web pages are either html source file or html rendered page on browser.

Components of Web Broewser:
Browsers have many components but here I will tell you some important components of browser.





  • HTML parser
  • JavaScript Engine/Interpreter
  • Rendering Engine


HTML parser Html parser parse the html document and create the DOM(Document Object Model) tree.

Rendering Engine: The main responsbility of this engine to display the content whic is requested by the user.

By default this engine can display HTML , XML and images. This can also shows the other type of document like PDf using Browser plugin. Rendering engine uses html parser to create DOM tree from html.

Rendering starts working after getting the requested content from the networking layer. The basic flow of rendering engine something like this






Firstly it parse the HTML to crete DOM and also parse the external css nad inline css of the document. The combination of styling information with the visual information is used to create the render tree.

Types of Rendering Engine: There are more than one type of rendering engine. Different browser uses differnt rendering engine. This the reason same web page look different in differnt browser. 

 

Points to Remember about xml

Important points concerning xml.

1. First line of xml document should be
   <?xml version="1.0" encoding="utf-8" ?> this is the xml declaration known as "prolog" This shows  the version and encoding about xml document.

2. xml document must have root element, and all other node are child element.

    <employee>
      <emp1>xyz</emp1>
      <emp1>abc</emp1>
   </employee>

3. All xml elements must have closing tag.

    <emp1>xyz</emp1>
    </ > referred to as closing tag

4. xml tags(opening and closing tag) are case sensitive

    <emp1>xyz</Emp> incorrect
    <emp1>xyz</emp1> correct

5. xml attribute value must be quoted

    <emp1 id="101">xyz</emp1> right
    <emp1 id=101>xyz</emp1> wrong.
6. xml have not any predefined tag. user define our own tag.

7. xml elements must be properly nested

8. white space is preserved in xml

9. meta-characters(special characters in xml) in xml

    <, > , </

 do not use these character directly in your xml document because these character
 are the meta-character for xml.

use these &lt; , &gt; instead of <, >

10. xml can be used to store data

11. xml can be used to exchange data

12. Comments in xml

<!-- This is comment -->

Application specific logger using log4j in spring mvc and jboss 7.1

Hello friends,

In this tutorial i will show you how to create a logger for your web app without using default behavior which is provided by jboss AS7.

some time in production mode we want to separate logger for our web app or application specific logger and not want to use server default logger.

As we know that jboss also uses log4j for logging. So if we want to use our log4j specification for a app we have to override or disable the log4j default specification which is provided by the jboss.

Steps to implement the log4j for application specific

1. create log4j.properties file in side resource folder under src.


2. Define log4j propety inside log4j.properites




3. Now create a file "jboss-deployment-structure.xml" inside WEB-INF folder


 
4. Disable the log4j module for only this application by writing the content on "jboss-deployment-structure.xml"

sample of file-

<jboss-deployment-structure>

    <deployment>

        <exclusions>

            <module name="org.apache.log4j" />

        </exclusions>

    </deployment>

</jboss-deployment-structure>


5. Add the log4j jar into your lib folder under WEB-INF

6. Load the properties file by typing the content on your web.xml

<context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/classes/resources/log4j.properties</param-value>
    </context-param>
  
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

How to Deploy Web Application on Jboss 7 server in stand alone mode

Hello guys,

In the previous post I have told you, How to Install the jboss-7 Application sever on ubuntu 12.04. In this post I will tell you to deploy and run your web application using jboss 7.

Steps to deploy Web Application

1. Craete the .war file of your web application.

2. Run your jboss-7 Application server by typing-

    $ $JBOSS_HOME/bin
    sh standalone.sh

3. Open the browser an type on address bar http://{host}:{port}(for example
     http://localhost:8080 ).

    Note by default jboss run 8080 port. you can change the default port.

   A welcome page of jboss will open.

Here is the sample of welcome page.


4. Now click on Administration console link of welcome page. It will ask you for
    User Name and Password for "Managment Realm". In the previous  post I
    have already told you, How to create user for ManagmentRealm. Enter the
    User Name and Password for it.

authentication

5. Now a new page will appear on browser. In the right you will see
    Deployments, Expand it and click on Manage Deployments.



6. Now click on Add content button as shown in the image below.

add content


7. When you will click on Add Content button a new page will appear. Sample is
    given below. Now browse the location of your .war file and click on Next
    button.
 
upload 

 8. After the above step verification window will open which defines key for your
     application and Runtime Name. you can change Run Time name of your app.
     Now click on Save button.






9. Name of your web app will appear on next window as shown in the screen
    shot.


10. Now click on Enable button as shown in image. Now Your app web app
      succesfully deploy on jboss7 Application server.

enable your web app in jboss7



11. Now you can access or run your web app by typing typing the
      http://{host}:{port}/TDesk/ in browser.

installing jboss7 in ubuntu


Hello friends,
In this post i will tell you, How to install jboss7 Application server in ubuntu 12.04, And how to run the jboss Application sever also how to add an user in jboss7.

To install jboss in ubuntu /linux follow the given steps-
1. Install java.

Note: to install java on linux ubuntu follow the give link-

2. Download jboss tar.

3. Untar the jboss tar ball where you want to install. In my case this is /usr/local
    you need root permission for this location. Ask your administrator for this-

$ sudo -s // to switch on root user from your terminal
$ tar -xvzf Jboss.tar.gz -C /usr/local
$ chmod 777 -R jboss

4. Set environment variable for jboss JBOSS_HOME.
$ sudo gedit /etc/profile
add in the last
JBOSS_HOME=/usr/local/jboss
export JBOSS_HOME

5. Set the PATH system variable
sudo gedit /etc/environment
PATH ="usr/local/jboss/bin"

Running jboss server


1. Go to the location where you install jboss- {jboss.home/bin}

sh standalone.sh // To run the jboss in stanalone mode.

             OR
sh domain.sh // To run jboss in cluster mode

Here we use standalone mode

3. Type the url in browser http://localhost:8080
    if everything is ok main page of server will display.

4. create a managment user/admin user for deploying application

Add user in Server

Management User
The default name of the realm for management users is ManagementRealm, when the utility prompts for the realm name just accept the default unless you have switched to a different realm.

   $ $JAVA_HOME/bin ./add-user.sh

Follow the step  which are shown on screen shot-

mangment realm
To add Application user follw the above step and chosse option b). 

Storm installation in production mode



 In this tutorial you will learn how to set up storm cluster in production mode.
  
 
storm cluster
 
 
Prerequisits
 1. Java 
 2. Storm0.8.2
 3. zookeeper 
 4.Atleast 2 system One for master node runs nimbus daemon , zookeeper node and other for 
    worker node(s) runs supervisor daemon
   Here the host name of my master node is 'nimbus'.
   you can check your hostname by typing 'hostname' command on your terminal.
  
Setup master node and zookeeper node
 
     a) Install Java 
         Note: To install java on linux/ubuntu folllow the given link


    b) Install storm-0.8.2
 
        1. Download storm release (in my case storm-0.8.2) from the following link-


       2. Extract the downloaded storm release using the following command

              $ tar -xvzf ~/Downloads/storm-0.8.2/ -C /usr/local

       3. Set the path of bin directory of storm release to access the storm command from anywhere,
        without typing the full path.

       4. Create  a local , storm configuration, where we will tell about our nimbus host. 
        To do it follow these steps-

            $ mkdir -p ~/.storm
            $ cat > storm.yaml
            $ nimbus.host: "192.168.1.99" // ip of your nimbus host

   C)Install the following native library-

      1.To install ZeroMQ type the following command
make sure that libtool, autoconf, automake, g++ is installed on your machine wget http://download.zeromq.org/zeromq-2.1.7.tar.gz tar -xvzf zeromq-2.1.7.tar.gz cd zeromq-2.1.7 ./configure NOTE: If you see this error message on your terminal configure: error: cannot link with -luuid, install uuid-dev, then install theuuid-dev by
using the command sudo apt -get install uuid-dev make sudo make install
2) To install JZMQ,
git clone https://github.com/nathanmarz/jzmq.git cd jzmq ./autogen.sh ./configure make sudo make install
3) set the storm .yaml file. #storm.yaml
// name of the machine where you install zookeeper in my case this is nimbus storm.zookeeper.servers: - "nimbus" # - "server2" // name of the machine which you make your nimbus or master machine in my case this is also
// "nimbus" nimbus.host: "nimbus" 
Install Zookeeper
 Type the commond to install zookeeper-

      $ sudo apt-get install zookeeper 
 
Setup worker node
 
      a) Install Java 

     Note: To install java on linux/ubuntu folllow the given link



     b) Install storm-0.8.2

         1. Download storm release (in my case storm-0.8.2) from the following link-

                 https://github.com/nathanmarz/storm

        2. Extract the downloaded storm release using the following command

              $ tar -xvzf ~/Downloads/storm-0.8.2/ -C /usr/local

        3. Set the path of bin directory of storm relase to access the storm command from anywhere,
            without typing the full path.

        4. Create  a local , storm configuration, where we will tell about our nimbus host. 
             To do it follow these steps-

                $ mkdir -p ~/.storm
                $ cat > storm.yaml
                $ nimbus.host: "192.168.1.99" // ip of your nimbus host

 
    C)Install the following native library-

        1. To install ZeroMQ type the following command
 
make sure that libtool, autoconf, automake, g++ is installed on your machine wget http://download.zeromq.org/zeromq-2.1.7.tar.gz tar -xvzf zeromq-2.1.7.tar.gz cd zeromq-2.1.7 ./configure NOTE: If you see this error mesage on your terminal configure: error: cannot link with -luuid, install uuid-dev, then install theuuid-dev byusing the command
       sudo apt -get install uuid-dev  
       make
       sudo make install 
      2. To install JZMQ,

git clone https://github.com/nathanmarz/jzmq.git cd jzmq ./autogen.sh ./configure make sudo make install
     3. set the storm .yaml file.

       #storm.yaml
// name of the machine where you install zookeeper in my case this is nimbus storm.zookeeper.servers: - "nimbus" # - "server2" // name of the machine which you make your nimbus or master machine in my case this is also
// "nimbus" nimbus.host: "nimbus" 

Storm framework terminology

Storm is free associate degree open supply, big-data process system that differs from alternative systems therein it's supposed for distributed real-time operation. Storm works on streaming further as static knowledge.Unlike Hadoop, that solely works on execution.

Storm has several use cases: realtime analytics, on-line machine learning, continuous computation, distributed RPC, ETL, and more. Storm is fast: a benchmark clocked it at over 1,000,000 tuples processed per second per node. 


storm cluster


Storm Cluster

A storm cluster contains 2 forms of nodes. One is Master node and other is worker node and uses Zookeeper node to co-ordinate to every alternative.

Master node runs a dameon referred to as "Nimbus" and worker node runs a daemon referred to as "supervisor". Master (Nimbus) assign the work for worker node and distribute the code round the cluster and additionally observance for failure.

Worker (supervisor) hear nimbus for work assigned thereto and run worker method to execute the set of a topology.

Each supervisor will run one or additional worker method acoording to configuration outline in storm.yaml. employee method on supervisor hear a specific port. every employee method uses one port to concentrate work assined by the nimbus to supervisor.

Zookeeper node act as a communication bridge between nimbus and supervisor node. All communication between nimbus and supervisor done through zookeeper cluster. nimbus and supervisor area unit homeless and quick fail, all state is kept on  zookeeper on native disk.This means you'll be able to stop Nimbus or the Supervisors and they will begin copy like nothing happened. This style results in Storm clusters being implausibly stable.

Topology: 

 

storm topology

Toplogy is sort of a connected graph of computation. every node in toplogy contains process logic and links between the node outline however proceessed knowledge passed to next node in topolgy.

There area unit 2 element of storm toplogy one is 'spout' and another is 'bolt'.

Spout:

It is the supply of stream that recieves the strems from outside world and pass those stream to bolt for a few process. for instance a spout will receive knowledge kind a computer address that contains files to translate from one indian language to a different indian language.

Bolt:

It is the another element of topology that receives tuples(data/stream) from Spout and do some process on this tuple and should emits new tuples for more proceesing. For eample its invoke a system on a knowledge or tuples comes from spout , that translate this tuple from one indian language to a different indian language.

In a storm topology there is also multiple spouts and bolts. And one bolt more pass tuple to a different bolt for more process.

Tuples:

It is the info structure that is provided by storm framework to pass stream from one element to a different element of storm toplogy. Tuple is associate degree orderted list of object.Storm supports all the primitive varieties, strings, and computer memory unit arrays as tuple field values. To use associate degree object of another sort, you simply ought to implement a serializer for the kind.Tuple will store multiple fields.

A sample of tuple
Object1(filename)  Object2(text)

Above illustration shows a tuple that have 2 fields. initial field stores a computer filename as string object and alternative field store the text of the file as a string object.

since storm could be a distributed framework its ought to acumen arrange and deserialize objects.

By default, Storm will arrange primitive varieties, strings, computer memory unit arrays, ArrayList, HashMap, HashSet, and therefore the Clojure assortment varieties. If you would like to use another sort in your tuples, you'll have to register a custom serializer.

Stream:
A strean is infinite sequence of tuple(data).

Resources

System properties in java

This post contains information concerning, How to access system properties in JAVA ?.

Some times it is necessary to extract the system (OS) dependent information to write down System (OS) independent code.

it show we'd like to access home directory of a user. it is possible that some user uses Linux and a few uses Windows. thus we'd like to access current system setting and that we additionally understand that windows and Linux uses different characters (windows uses '/r/n' and Linux uses '/n') to point out finish of line during a file. thus we'd like to understand these special character to form our program to run in Windows and Linux or anything. for this we tend to used

System.getProperty("path.separator");


instead of using "\r\n"  or "\n" explicity.

exmple
 String lineSeparator = System.getProperty("line.separator"); 
 // all other code goes here

 File out = new File("/tmp/my.txt");
 BufferedWriter bw = new BufferedWriter(new FileWriter(out));

  bw.write(reverseStr);
 bw.write(lineSeparator); // system independent new line

 bw.close();

 

\n = CR (Carriage Return) // Used as a new line character in Unix
\r = LF (Line Feed) // Used as a new line character in Mac OS
\n\r = CR + LF // Used as a new line character in Windows

This table define some most commonly used keys for accessing system property. This tabls is provided by http://docs.oracle.com

Key Meaning
"file.separator" Character that separates components of a file path. This is "/" on UNIX and "\" on Windows.
"java.class.path" Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property.
"java.home" Installation directory for Java Runtime Environment (JRE)
"java.vendor" JRE vendor name
"java.vendor.url" JRE vendor URL
"java.version" JRE version number
"line.separator" Sequence used by operating system to separate lines in text files
"os.arch" Operating system architecture
"os.name" Operating system name
"os.version" Operating system version
"path.separator" Path separator character used in java.class.path
"user.dir" User working directory
"user.home" User home directory
"user.name" User account name