Monday 28 November 2016

java.lang.NoClassDefFoundError: org/eclipse/core/resources/ResourcesPlugin

java.lang.NoClassDefFoundError: org/eclipse/core/resources/ResourcesPlugin

if you create a Debug configuration from your product file, in my case CDOServer.product, then
1. you go an select the Plug-ins tab in the Debug Configuration
2. then click "Add Required plug-ins"

it may build a dependency that just does not work.

It seems you have do step 1 above, then
2. "Deselect All"
3. Select your own package
4. Click "Add Required plug-ins" a few times until the number of required plugins stop increasing, see the display "x out of y selected"





ref : Eclipse

Could not resolve archetype

Could not resolve archetype org.apache.maven.archetypes:maven-archetype-quickstart:RELEASE from any of the configured repositories.

Go to your Maven installation folder C:\apache-maven-3.1.0\conf\ ( For example: here we have installed maven in c:\ drive)
Copy settings.xml to C:\Users\[UserFolder]\.m2 (Your local repository)
Modify the proxy in settings.xml based on the info that you get from the above link.

or delete the repository folder from .m2 folder

and restart the eclipse with default maven setting

Ref : javahonk, Git



your install of php does not have the 'php_curl.dll' extension enabled

your install of php does not have the 'php_curl.dll' extension enabled


Open your php.ini file and set the following setting to a Windows file path:

extension_dir = "X:/path/to/your/php/ext"




Java was started but returned exit code = 1

“Java was started but returned exit code = 1”

go to the eclipse dir and edit eclipse.ini

just before -vmargs paste the following path of the jvm

ex :
...
-vm
C:\path to installed direc \Java\jre1.8.0_40\bin\server\jvm.dll


-vmargs

Wednesday 16 November 2016

Getting started Jersey.

1. Project build and management configuration is described in the pom.xml located in the project root
directory.
REF : pom elements
2. Project sources are located under src/main/java.
3. Project resources are located under src/main/resources.
4. Project web application files are located under src/main/webapp.

5. To compile and package the application into a WAR, invoke the following maven command in your
console:

ex : mvn clean package

logs :

Packaging webapp
[INFO] Assembling webapp [simple-service-webapp] in [.../simple-service-webapp/target/[INFO] Processing war project
[INFO] Building war: .../simple-service-webapp/target/simple-service-webapp.war

Now you are ready to take the packaged WAR (located under ./target/simple-servicewebapp.
war) and deploy it to a Servlet container of your choice.

Jersey dependency maven :

1) jersey-server, jersey-json, jersey-multipart.

Spring dependency :

spring-core,context,context-support,web,aop.

spring security.

security-web,security-config,security-taglib,security-core,security-acl

spring+jersey

spring,core,web,beans,context,asm,aop.

jackson:

jackson-jaxrs-json-provider


apache commons :

utility for string manipulation

connection pool :

dbcp

Apache-commns :

Apache Commons Codec provides implementations of common encoders and decoders such as Base64, Hex, Phonetic and URLs.

Hibernate :

hibernate-core

spring-transaction:

REF : transaction   why we go for spring transaction

hibernate entity manager
table mapping

spring-orm



6. Root Resource Classes
Root resource classes are POJOs (Plain Old Java Objects) that are annotated with @Path

7. @Produces
annotation is used to specify the MIME media types of representations a resource can produce and send back to the
client.
Using multiple output MIME types
@Produces({"application/xml", "application/json"})


@Consumes
annotation is used to specify the MIME media types of representations that can be consumed by a resource.

@QueryParam
is used to extract query parameters from the Query component of the request URL.

@DefaultValue
annotation, will be assigned to the step method parameter. If the
"step" value cannot be parsed as a 32 bit signed integer then a HTTP 404
ex :
 public Response smooth(
4 @DefaultValue("2") @QueryParam("step") int step

@FormParam

it extracts information from a request representation that is of the MIME media type
"application/x-www-form-urlencoded"

@Context HttpHeaders headers,

@Singleton
annotation says that the resource
will be managed as singleton and not in request scope. The sub-resource locator method returns a class which means that the runtime will managed the resource instance and its life-cycle. If the method would return instance instead, the Singleton annotation would have no effect and the returned instance would be used.


Securiry -- done
Multipart  -- progress -- 8.3
Filters -- 9.0







Stateless Authentication with Spring Security


1) for content and format ref :
http://blog.jdriven.com/2014/10/stateless-spring-security-part-2-stateless-authentication/

2) http://www.codingpedia.org/ama/how-to-secure-jersey-rest-services-with-spring-security-and-basic-authentication/
3) http://www.codingpedia.org/ama/tutorial-rest-api-design-and-implementation-in-java-with-jersey-and-spring/


Sunday 4 September 2016

Context initialization failed

Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.scramjet.service.AppUserService edu.scramjet.controller.UserController.appUserService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.scramjet.service.AppUserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Solution :
If you look at stack. Spring container is unable to create bean. for userController. unable to autowire the appUserService.

ex :  public class void UserController {
 
       @Autowired
private AppUserService appUserService;     ///  interface object

      @RequestMapping(value="/create",method=RequestMethod.POST,
produces=MediaType.APPLICATION_JSON_VALUE,
consumes=MediaType.APPLICATION_JSON_VALUE)
public User createAppUser(@RequestBody User user ){
System.out.println(user);

appUserService.createUser();



return user;
}

   
     }

If AppUserService  is object  interface and its autowired. We need to provide Implementation class for bean creation.


public interface AppUserService {

public void createUser();
}

@Service
public interface AppUserService implements  AppUserServiceImpl {

public void createUser() {

}

}

Saturday 27 August 2016

Java 8 JDBC

Java 8 : The JDBC-ODBC Bridge has been removed.

There is plenty of option to try. refer the Stackoverflow for futher references. 


Java 1.8 Concurrency feature "ConcurrentHashMap as a Set"

Java 1.8 Concurrency feature "ConcurrentHashMap as a Set"

The feature will return set of key in the map as Set.

public class VoiceConcurrentHashMap {

public static void main(String[] args) {

ConcurrentHashMap<String,String> map = new ConcurrentHashMap<String, String>();
System.out.println(map);
map.put("Lnkedin", "Networking");
map.put("Microsoft", "Windows10");
map.put("facebook", "Social");
map.put("Google", "SearchEngine");

KeySetView<String,String> set = map.keySet();
System.out.println(set);
}

}

Result : [Google, facebook, Microsoft, Lnkedin] .

Image :


ref :
Java API 


Behaviour of ConcurrentHashMap when it has Duplicate key.

Behaviour of ConcurrentHashMap when it has Duplicate key.

ConcurrentHashMap will overwrite previous value for a given key in Map. The object whos reference is lost are eligible for garage collection.

public class VoiceConcurrentHashMap {

public static void main(String[] args) {

ConcurrentHashMap<String,String> map = new ConcurrentHashMap<String, String>();
System.out.println(map);
map.put("Lnkedin", "profile");
map.put("Lnkedin", "profile");
map.put("Lnkedin", "jagdeesh");

}
}

ref :
1. Java API
2. Stackoverflow


Wednesday 24 August 2016

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

When supplying json object from postman. if Class contain a list object. Provide it as a array [].
ex :
{
    "name" : "raman",
    "employeeId" : 12345,
"orderList" : {"orderId" : 1,"orderName" : "rest json book"}
}
solution :
{
"name" : "raman",
"employeeId" : 12345,
"orderList" : [{"orderId" : 1,"orderName" : "rest json book"}]
}

@JsonIgnore

@JsonIgnore

If we want to serialize object to json, during this process some of the property can be null/empty can be ignored.
this can be achived using @jsonIgnore.

ex :
1. @JsonIgnore(Include.NON_NULL)
2. @JsonIgnore(Include.NON_EMPTY)
3. @JsonIgnore(Include.NON_DEFAULT)

Ref : wilddiary

use of @JsonSerialize

use of @JsonSerialize

A pojo class which is participating is serialisationtion should be annoted with @JsonSerialize

com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException


com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException
SEVERE: The exception contained within MappableContainerException could not be mapped to a response, re-throwing to the HTTP container
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
 at [Source: org.apache.catalina.connector.CoyoteInputStream@76ab2e75; line: 3, column: 25] (through reference chain: com.group.dto.EmployeeDto["orderDto"])

Solution :
1. Json mapping should be done, when list object is added as property.

ex : Customer {
private int id;
private int name;
// missing json mapping annotation
private List<OrderDto> orderDto;
}
OrderDto {
pivate int orderId;
private String orderName;

}
2. Changes add @JsonProperty("orderList")

Customer {
private int id;
private int name;
// missing json mapping annotation
private List<OrderDto> orderDto;
}

Tuesday 23 August 2016

Please initialize the log4j system properly.

Eroor :

log4j:WARN No appenders could be found for logger (com.group.api.EmployeeService).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

Solution :
1. In maven based. create log4j.properties file in folder /src/main/resources.
2. add following lines.

# Root logger option
log4j.rootLogger=DEBUG, stdout, file

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n



Monday 22 August 2016

Failed to load class "org.slf4j.impl.StaticLoggerBinder".

Logging.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

Solution :

1. Inlcude the following maven dependency.
       
       <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-api</artifactId>
   <version>1.7.21</version>
</dependency>
    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-log4j12</artifactId>
   <version>1.7.21</version>
</dependency>




Sunday 21 August 2016

The ResourceConfig instance does not contain any root resource classes

When created a  maven web project.
1. Make sure to delete all the jsp file. 
2. Refresh and build

Method 2 :
1. In eclipse right click go to properties
2. Go ro java build path
3. Order and export
4. Add "JRE and system library","Maven library". and click ok
5. Right click on project
5.1 Go to run.
5.2 maven install.

Thursday 7 July 2016

spring jersey intigration

steps 1 :

in web.xml :

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name>Archetype Created Web Application</display-name>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>\WEB-INF\ApplicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
<servlet-name>jerseyService</servlet-name>
<servlet-class> com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.spi.spring.container.servlet.SpringServlet</param-name>
<param-value>com.jersey.api</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jerseyService</servlet-name>
<url-pattern>/v1/*</url-pattern>
</servlet-mapping>

</web-app>

step 2: application context in web-inf folder.
include namepace for spring module.
ref : http://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/xsd-config.html

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
 
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd " >

<context:component-scan base-package="com.jersey.api" />

 
</beans>

step 3: configure pom with spring,spring-jersey depencdency

<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/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.myjersey</groupId>
  <artifactId>Onejersey</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>Onejersey Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <properties>
  <jersey.spring>1.9</jersey.spring>
  </properties>
 




  <dependencies>


  <!-- spring  -->
 
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>4.1.4.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-beans</artifactId>
   <version>4.1.3.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>4.1.3.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-web</artifactId>
   <version>4.1.3.RELEASE</version>
</dependency>


 

  <!-- spring  -->


  <!-- jersey  -->
  <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-server</artifactId>
   <version>1.9</version>
</dependency>
<dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-json</artifactId>
   <version>1.9</version>
</dependency>
<dependency>
   <groupId>com.sun.jersey.contribs</groupId>
   <artifactId>jersey-multipart</artifactId>
   <version>1.9</version>
</dependency>


  <!-- jersey -->
 
    <!-- spring-jersey  -->
  <dependency>
   <groupId>com.sun.jersey.contribs</groupId>
   <artifactId>jersey-spring</artifactId>
   <version>${jersey.spring}</version>
   <exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-asm</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</exclusion>
   
   </exclusions>
</dependency>

<!-- jackson -jaxrs  -->
<dependency>
   <groupId>com.fasterxml.jackson.jaxrs</groupId>
   <artifactId>jackson-jaxrs-json-provider</artifactId>
   <version>2.5.5</version>
</dependency>
<!-- jackson -jaxrs  -->


    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>Onejersey</finalName>
  </build>
</project>






step 4 : java application



/**
 *
 */
package com.jersey.api;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;

import org.springframework.stereotype.Service;

/**
 * @author voice
 *
 */
@Service
@Path("/hello")
public class Employee {

@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response helloWorld(){
ResponseBuilder rs = Response.status(Status.OK);
System.out.println("HI this is jagdeesh");
return rs.build();
}

}





ref :
spring-jersey
spring module

Saturday 2 July 2016

difference betweeh length and length() in java

difference betweeh length and length() in java

description : To find the length of array we use legth.

ex : define and intiger array and find the length of the array.
int[] number =  new int[3];
number[0] = 1;
number[1] = 3;
number[2] = 5;

int secondHighest = number.length;
output : 3

description : To find the length of string we use legth().

String name = "voice";
System.out.println(name.length() + " length");

output : 5

Friday 1 July 2016

Several ports (8005, 8080, 8009) required by Tomcat Server at localhost are already in use


Several ports (8005, 8080, 8009) required by Tomcat Server at localhost are already in use

do : netstat -a -o -n

kill process id : taskkill /F /PID 6532

ref : stackoverflow

Wednesday 29 June 2016

RDS in aws.

RDS in aws.

Three steps to launch mysql on RDS.
1.Launch.
2.Connect.
3.Manage and moniter.

step 1. launch
a. create db instance.
b. Select engine :
Select db instance from option ex : here we choose mysql from option. (amazon aurora/mariadb/postgresql/oracle/sqlserver).
c. Production :
DEV/test (mysql/amazon aurora).
d. specify db details.
click on (Only show options that are eligible for RDS Free Tier) its a db.t2.micro instance.
select :
DB Instance Identifier* : mydbname
Master Username* : myusername
Master Password : mypassword
Confirm Password : mypassword

version : 5.6.29

select default security group:
default
give DB name.

Click on launch.

Monday 27 June 2016

java.lang.IllegalStateException: LifecycleProcessor not initialized

java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: Root WebApplicationContext: startup date


check the configuration in
1. applicationcontext.xml
2.pom.xml

observation :
1. make sure to upgrade dependency to 4.0 release or 3.0 release.




Thursday 23 June 2016

Unknown provider: $stateProvider

[$injector:unpr] Unknown provider: $stateProvider <- $state <- LoginCtrl

problem :
missing angular-ui-router.js

<script src="bower_components/angular-ui-router/release/angular-ui-router.js"></script>


steps :
1.
go the project folder and from commandline.

cmd :  bower install angular-ui-router

ref : git

the above command will download package

2. start grunt server

cmd : grunt serve

Wednesday 22 June 2016

start writing a project in yoman for angular js project

start writing a project in yeoman for angular js project

IN the app folder.

project structure is


1. images.
2. script
2.1 controller folder (all the controller are stored here.)
2.2 app.js (for routing the pages.)
3.style.
4. views. (all the static html stored here.)

create a module address.

1. Create a listItem in index.html in the navigation bar.
ex : <li><a ng-href="#/address">Address</a></li>

2. create a route in app.js

ex :

.when('/address', {
 templateUrl : 'views/address.html',
 controller : 'AdressCtrl',
 controllerAs : 'contact'
 })
3. create address.js in script/controller folder and write adress controller.
ex :
angular.module('scjavaApp')
.controller('AdressCtrl',function(){
console.log("Hhi this from controller");

});

4. In view folder create address.html
<div>
HI this from address page.
</div>

start grunt server and check

Wednesday 15 June 2016

Jersey java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer

Jersey java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer


solution : In eclipse 
go to  project -> properties -> development assembly -> add -> java build path entries.

src/main/java not visible in project folder eclipse

src/main/java not visible in project folder eclipse

steps :
1) right click on project.
2) click on build path.
3) select configure buildpath.
4) select order and export
5) click and select.
a) jre system lib.
b) maven dependency 

creating a maven web project from commandline

1)
a. creating a maven project from commandline

mvn archetype:generate -DgroupId={project-packaging}
-DartifactId={project-name}
-DarchetypeArtifactId=maven-archetype-webapp
-DinteractiveMode=false

ref : maven

b) need to create sample web application

ex : mvn archetype:generate -DarchetypeGroupId=com.sample.voice -DarchetypeArtifactId=maven-archetype-webapp -DarchetypeVersion= voice


mvn archetype:generate -DgroupId=com.voice -DartifactId=sample -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

Tuesday 14 June 2016

Previously created MySQL Schema ` ` was found. Statement ignored. ERROR: Previously created MySQL Table

Previously created MySQL Schema ` ` was found. Statement ignored. ERROR: Previously created MySQL Table

scenario : When performing reverse engineering in workbench. If there are multiple instance of DB created in workbench we get the error.
solution :  Make sure workbench dashboard only have one connection in open, to communicate with DB.

Wednesday 8 June 2016

not-null property references a null or transient value

org.springframework.dao.DataIntegrityViolationException: not-null property references a null or transient value : entity.VoiceProfile.email; nested exception is org.hibernate.PropertyValueException: not-null property references a null or transient value : entity.voiceProfile.email

 conclustion :
 While persisting into the DB get the users VoicePofile by id or check if any user exist for the voiceprofile or not.
 if exist get and then store in db.

Tuesday 7 June 2016

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column ' ' cannot be null

Let us check scenario of hibernate.
solution :
1.check entity  mapping with table.
2. check the primary key and foreign key relationship.
3. primary key cannot be "not null" in table, it can be null in other table. 

Monday 6 June 2016

com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException

com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException

SEVERE: The exception contained within MappableContainerException could not be mapped to a response, re-throwing to the HTTP container

com.fasterxml.jackson.core.JsonParseException: Unexpected character ('"' (code 34)): was expecting comma to separate OBJECT entries

Ex :
error :
{
"name" : "voice"
"email" : "voice@gmail.com"

}
corrected :
{
"name" : "voice" ,
"email" : "voice@gmail.com"

}

Solution :  In the corrected solution put a comma.

Thursday 2 June 2016

error: failed to push some refs to git

error: src refspec master does not match any.
error: failed to push some refs to 'https://github.com/userid/voice.git'

solution :
1. git add -A
2. git status
3. git commit -m "message"
3.git push origin HEAD:<remoteBranch>

Thursday 26 May 2016

Functional style in java.

Functional style in java.

Function<T,R> function = new  Function<T,R>();
Type Parameters:
T - the type of the input to the function
R - the type of the result of the function

Ref : Oracle

ex :
It is the explicit intent to make it more convenient to program in a functional style in Java. Now, in mathematics, a function is generally written like

f: A -> B
(i.e., a function from As to Bs). This corresponds also to the notation in functional languages, Scala and already existing functional libraries for Java.

Ref : Stackoverflow 

Tuesday 24 May 2016

WARN (SqlExceptionHelper.java:233) - Unknown column 'xxx' in 'field list'

 WARN  (SqlExceptionHelper.java:233) - Unknown column 'EditedOn' in 'field list'

Solution :
1) In hibernate check the entity class.
2) In table check the column names.
3) Compare both the entity and column name.
4.Caused due to spelling mistake.

Saturday 21 May 2016

scope of public,private,protected in java for class method

public : method which are public there scope is available to child and which ever class wants to use it.
protected : scope visible only in child package
private :  scope visible only in class. 

Difference between pathparam and QueryParam in Rest.

Difference between pathparam and QueryParam in Rest.

Pathparam : used get the part of the string from URL.
ex:  @Pathparam("id")
ex : http://localhost:8080/voice{id}

QueryParam  : using this we are able to access the key,value after from URL after "?"
ex:  @QueryParam("id")
ex : http://localhost:8080/voice?id=1009

Log file in tomcat.


1) catalina.log -- logs all the  log at the time of server start
2) localhost_access_log : logs all the request type and URI
ex :
a) 0:0:0:0:0:0:0:1 - - [21/May/2016:11:21:52 +0530] "GET /voice/p1x/network HTTP/1.1" 200 -
3) server.log : logs "ContainerBackgroundProcessor" info and error stack.
4) error.log : logs all the error stack
5) hostmamager.log :
6) manager.log : logs info about HTMLManager,manager,
ex : INFO: HTMLManager: init: Associated with Deployer 'Catalina:type=Deployer,host=localhost'
ex : INFO: HTMLManager: init: Global resources are available
ex : INFO: HTMLManager: list: Listing contexts for virtual host 'localhost'

Friday 20 May 2016

what is purpose of calling chain.doFilter() in servlet


what is purpose of calling chain.doFilter() in servlet
chain.doFilter(request, response);

The name chain suggests that you have a sequence of filters, with each filter doing some processing and then passing on to the next in sequence, so each object has a chain member to point to the next filter in the sequence, which gets called after the filter has performed its own processing. The last in the sequence will then probably have null as the chain value, or it knows on its own that it is the last one in the sequence.

Ref : stackoverflow
author JK

public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
...

chain.doFilter(request, response);
}

after executing the method  on calling chain.doFilter() it will call filter present in web.xml in the order of defination.


<filter>
  <filter-name>VoiceLoginFilter</filter-name>
  <filter-class>com.voice.filters.VoiceLoginFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>VoiceLoginFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

when to use boolean and Boolean in java

when to use boolean and Boolean
1. if you want to have true or false use boolean.
2. if you want to have true or false or Null use boolean.

Ref : stackoverflow

Thursday 19 May 2016

When to use detached criteria and criteria.

When to use detached criteria and criteria.

detached criteria : if we want to create a query wihout any session
Ref : Stackoverflow

another alternative is

If you are using Spring and choose to use HibernateTemplate, it doesn't provide createCriteria() method.

Ref :  spring

Generic Maps in Collections


Generic Maps in Collections
IF we want to restrict the type of object we can go for Generic Map using Map<key,value> pair

Map<String, Object> map = new HashMap<String, Object>();
In the above example the map object will accept key of type string and value of type Object

Friday 13 May 2016

SQL Error: 0, SQLState: null, Cannot create PoolableConnectionFactory (Communications link failure)



2016-05-12 20:37:03,434 [http-bio-8080-exec-3] WARN  (SqlExceptionHelper.java:144) - SQL Error: 0, SQLState: null
2016-05-12 20:37:03,435 [http-bio-8080-exec-3] ERROR (SqlExceptionHelper.java:146) - Cannot create PoolableConnectionFactory (Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.)
2016-05-12 20:37:03,445 [http-bio-8080-exec-3] ERROR (BaseService.java:41) - org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Could not open connection
at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:544)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:457)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)
Here is solution worked for me. provide relevant/correct db credentials and ip address. ex :
DB URL : jdbc:mysql://127.0.0.1:3306/voicedb
username : voice
password : voice

Thursday 12 May 2016

fatal: remote origin already exists.

fatal: remote origin already exists.

git remote add origin https://github.com/voice/voiceApp.git

solution :

1.First remove origin
cmd :  git remote rm origin

2. now add the origin
cmd : git remote add origin https://github.com/voice/voiceApp.git

or

1.set the new git  origin/remote URL
.set the new origin
cmd : git remote set-url origin https://github.com/voice/voiceApp.git


2. Now check origin.

cmd : git remote show origin





Write operations are not allowed in read-only mode (FlushMode.MANUAL)


org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
at org.springframework.orm.hibernate4.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1135)
at org.springframework.orm.hibernate4.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:620)
at org.springframework.orm.hibernate4.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:617)
Below of the piece of code worked for me. Added @Transactional annotation where i was performing insert operation
@Transactional
public void sendVoice(VoiceUser voiceUser) {
                    feedSendVoice.save(voiceUser)
 }

Wednesday 11 May 2016

Can not construct instance of java.util.Date from String value

Can not construct instance of java.util.Date from String value

SEVERE: Servlet.service() for servlet [Jersey Rest Service] in context with path [/voice] threw exception [com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.util.Date from String value '12-01-2016': not a valid representation (error: Failed to parse Date value '12-01-2016': Can not parse date "12-01-2016": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
 at [Source: org.apache.catalina.connector.CoyoteInputStream@aca01d2; line: 6, column: 22] (through reference chain: com.voice.dto.VoiceSurveyRequestDto["feedbackAt"])] with root cause
com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.util.Date from String value '12-01-2016': not a valid representation (error: Failed to parse Date value '12-01-2016': Can not parse date "12-01-2016": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))

From the error stack provide date in following format.
1. yyyy-MM-dd'T'HH:mm:ss.SSSZ"
ex : 2016-10-01T09:45:00.000

2."yyyy-MM-dd'T'HH:mm:ss.SSS'Z'".
ex : 2016-10-01T09:45:00.000

3. "EEE, dd MMM yyyy HH:mm:ss zzz"
ex : 2016-10-01T09:45:00.000

4."yyyy-MM-dd"
ex : 2016-10-01

Saturday 7 May 2016

context,servlet, path info

The servlet engine splits the URI into three useful sections: the context path (application prefix), the servlet path, and the path info.

For example, given an application prefix of '/myapp', the api /myapp/dir/test.jsp/data will be split as follows:

/myapp/dir/test.jsp/datagetRequestURI()
/myappgetContextPath()
/dir/test.jspgetServletPath()
/datagetPathInfo()

REF : Servlet API

why to choose enum in java

why to choose enum in java

This are special data type that enables for a variable to set  predefined constants REF[1]

If you use enums instead of integers (or String codes), you increase compile-time checking and avoid errors from passing in invalid constants, and you document which values are legal to use REF[2]


Let us take an example where you want to send the status code for service call requested.

ex :

define a service class which will take a request

# make a Http request.
@GET
#define the path for request.
@PATH(/voice)
#define mediatype to produce/consume
@Produces(MediaType.APPLICATION_JSON)
#start the service method
public Response VoiceResponse(){
ResponseBuilder responseBuilder = Response.status(ServerStatus.Server_Error);

}



Because they are constants, the names of an enum type's fields are in uppercase letters. REF[1]

define a class of enum type.

public enum ServerStatus {

#define status code
SUCCESS(200,'OK'),

#define server error.
Server_Error(500,'Internal server error')
}





REF :
1.oracle
2. stackoverflow

Friday 6 May 2016

Eclipse shortcuts

Eclipse shortcuts

Navigational Shortcuts:

F10

Main menu:

Shift+ F10 Context menu
Ctrl +F10 View menu

Workspace navigation:

F12 Activate editor
Ctrl+Shift+W Switch editor
Ctrl +F6 Next editor
Ctrl +Shift+ F6 Prev editor
Ctrl F7 Next workspace
Ctrl Shift F7 Prev workspace
Ctrl+ F8 Next perspective
Ctrl +Shift+ F8 Prev perspective
Alt +Left Back
Alt+ Right Forward

Files:

Alt +Shift+ S Show in…
Ctrl+ Shift+ R Jump to file
Ctrl+ N New file
Ctrl +S Save file
Ctrl +Shift+ S Save all files
Ctrl+ F4 Close file
Ctrl+ Shift+ F4 Close all files

Find:

Ctrl +L Goto line
Ctrl +F Find
Ctrl +J Incremental find
Ctrl +Shift+ J Incremental find prev
Ctrl+ K Find next
Ctrl +Shift+ K Find prev
Ctrl +H Search workspace
Ctrl +(dot) Navigate next
Ctrl +(comma) Navigate prev

Java navigation:

F3 Goto declaration
Ctrl+ Shift+ U Find references in file
Ctrl +Shift+ G Find references in workspace
Ctrl+ G Find declarations in workspace
Ctrl +Shift+ P Navigate to matching bracket/brace
Ctrl +T Popup type hierarchy
Ctrl +Shift+ T Open Type
Ctrl +O Outline of current source
Ctrl +F3 Outline of current cursor position
Ctrl +Shift+ Arrow Jump beetween methods up or down
F2 Show Javadoc
F4 Show hierarchy
Ctrl +Alt+ H Open call hierarchy

General editing:

Alt+ Arrow+ Move line(s) up or down
Alt +Shift+ Up Expand selection to enclosing element
Alt +Shift+ Right Expand selection to next element
Alt+ Shift+ Left Expand selection to previous element
Alt +Shift+ Down Restore previous selection
Ctrl +Alt +Arrow Duplicate line(s) up or down
Shift +Enter Insert line below
Ctrl +Shift+ Enter Insert line above
Ctrl +D Delete line
Ctrl +Shift+ Q Toggle Quick Diff
Ctrl +Shift+ Y Convert to lowercase
Ctrl +Shift +X Convert to uppercase

Java editing:

Al+t Shift+ U Remove occurrence annotations
Ctrl +1 Quick fix (works even when there are no errors
Ctrl +Shift+ M Add import
Ctrl +Shift+ F Reformat
Ctrl +Shift+ O Organize Imports
Ctrl +/ Comment
Ctrl +\ UnComment
Ctrl +Shift+ Space Parameter hints
Ctrl Hyperlink identifier
Ctrl+ I Correct indentation
Shift+ Space Incremental content assist

Debugger:

F5 Step into
F6 Step over
F7 Run to return
F8 Resume
F9 Relaunch last
F11 Run/debug last
Ctrl+ F11 Run
Ctrl +Shift+ B Toggle breakpoint
Ctrl+ D Display
Ctrl +Q Inspect
Ctrl +R Run to line
Ctrl +U Run snippet

Refactoring:

Alt+ T Refactoring menu
Ctrl+ Shift+ Z Undo refactor
Ctrl +Shift+ Y Redo refactor
Alt +Shift +R Rename
Alt +Shift+ V Move
Alt +Shift+ I Inline
Alt +Shift+ M Extract method
Alt +Shift+ L Extract local
Alt +Shift+ C Change method signature

Misc:

F5 Refresh
F1 Infopop
F2 Show resizeable hover


Thanks to Sathya

Thursday 5 May 2016

Create public and private keys using ssh-key-gen to connect repository.

Create public and private keys using ssh-key-gen

1. go to your machine.

2. check if ssh key are available or not.
cmd : ls -al ~/.ssh

3. create/genrate new ssh key.
cmd : ssh-keygen -t rsa -C "voice@voice.com"

4)  go to .ssh directory, open new created   id_rsa.pub file, copy the content and save at you local, so we can to other repo
ex : github
ssh dir :  /home/../.ssh

5) open github and paste key in ssh section of github setting and save.

6) now come to machine make a ssh call to git
ex : ssh -vT git@github.com


REF :
1. github
2. video








same procedure follow for git.
how do you access private git repository from jenkins.

Failed to connect to repository : Error performing command: git ls-remote -h in jenkins

Failed to connect to repository : Error performing command: git ls-remote -h git@github.com:voice/voice_Java.git HEAD.

solution : problem might be due to you have not installed git repo on the machine.

install and try again in jenkins when creating a job configuration.

Wednesday 4 May 2016

error: [ng:areq] Argument ' ' is not a function, got undefined

error: [ng:areq] Argument ' ' is not a function, got undefined.

initialize the controller.

solution :

console.log("hi");
 
  var voiceApp =  angular.module("voice",[]);
 
  surveyApp.controller('voiceCTRL', function() {
 
  console.log("hi");
  });

Tuesday 3 May 2016

jprofiler

jprofiler.

install jprofiler.

jprofiler is java profiling tool, it also includes feature to profile cpu,memory,threads.

getting started with jprofiler.

1. download latest version
ref: jprofiler

2) Insatall the software.

3) intigrate with ide(eclipse).
steps to intigrate.

a) start jprofiler.
b) go to session ->IDE intigration ->select IDE-> eclipse (version). click on intigrate.

c) start eclipse.
d) go to windows->prespective->custom prespective->Action set visiblity->check profiler.
intigration is done


2) how to run jprofiler on project.

a) select the project.
b) right click and run ->profile ->profile configuration-> choose the project
c)choose ->apache tomcat-> source (remove the default if there are any).
d)add the project source directory.click on profile.
e) jprofiler will start window with statistics.

Saturday 30 April 2016

SAXParseException hadoop-2.7.2

Caused by: org.xml.sax.SAXParseException; systemId: file:/usr/local/hadoop-2.7.2/etc/hadoop/core-site.xml; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog

solution :

check xml configuration of the file.
cause due not proper closing of tag

hadoop-env.sh missing in hadoop 2.7

hadoop-env.sh missing in hadoop 2.7

earlier location :

/conf/hadoop-env.sh

location is changed to

/etc/hadoop/hadoop-env.sh



install grunt server and start the grunt server


install grunt server and start the grunt server

1) install grunt server.
cmd : npm install -g grunt-cli

2) start grunt server.
note : after creation of yeoman project go to directory
cmd : grunt server

Friday 29 April 2016

angularjs project scaffolding using yeoman

create a project using yo
prerequisite
a) install npm on your box.

1) install yeoman online using npm command.
cmd : npm install -g yo
ref : github (https://github.com/yeoman/yo)
2) create the project scaffolding using yo command.
note : create a project folder "voiceapp" and move to the directory.
cmd : yo  or (yo angular)
3) We get set of options, choose option based on requirement. here we choose angular.
There are some experimental feature like gulp/saas, based on requirement choose yes or no.
a) angular
b) webapp
..
4) include bootstrap choose yes option.
>( ) angular-animate.js
 ( ) angular-aria.js
 ( ) angular-cookies.js
 (*) angular-resource.js
 ( ) angular-messages.js
 (*) angular-route.js
 (*) angular-sanitize.js
 ( ) angular-touch.js

choose the following angular(resource/route/sanitize).

5) skip if there any option when installation.

angular.js:13550 Error: [ng:areq] Argument 'MynameCtrl' is not a function, got undefined

angular.js:13550 Error: [ng:areq] Argument 'MynameCtrl' is not a function, got undefined

solution :

include controller.js in index file or the required reference file where you are calling

Thursday 28 April 2016

Genrating project scaffolding for angular js using Yeoman.

step 1.
a) install nodejs window/linux machine or based on the os you have.
ref : nodejs
step 2.
a) install Yeoman ,grunt,bower.
ref : Yeoman
cmd :  install yo.
b) From the given choose angular js and click next.

note :
a) Yeoman : for generating project scaffolding.
b) bower : package manager.
c) grunt : to perform repetitive task, minification,unit testing.



Wednesday 27 April 2016

how to Enable EPEL Repository for RHEL linux.

how to Enable EPEL Repository for RHEL linux.
EPEL (Extra Packages for Enterprise Linux)
ref : linux 

Tuesday 26 April 2016

Access denied for user 'ec2-user'@'localhost' (using password: NO)

Access denied for user 'ec2-user'@'localhost' (using password: NO)

ref : ()

a) grep 'temporary password' /var/log/mysqld.log

login with temp password.

b) mysql -u root -p
password : 'temporary password'

(or)

mysql> UPDATE mysql.user SET Password=PASSWORD('your_new_password') WHERE User='root';

ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.

mysql> SET PASSWORD = PASSWORD('your_new_password');

Query OK, 0 rows affected, 1 warning (0.01 sec)

follow step - b.

ref : stackoverflow for a
stackoverflow : for b.



install/install mysql in rhel linux

install/install mysql in rhel linux
ref :
https://dev.mysql.com/doc/mysql-repo-excerpt/5.6/en/linux-installation-yum-repo.html
1) get the URL for the mysql rpm
sudo wget http://dev.mysql.com/get/mysql57-community-release-el7-8.noarch.rpm

2) sudo yum install mysql57-community-release-el7-8.noarch.rpm


3) now install the server.
cmd : sudo yum install mysql-community-server

4) sudo service mysqld start

5) remove the mysql server.
cmd : yum remove mysql mysql-server

install tomcat on linux


install tomcat

go to /temp dir
sudo wget http://redrockdigimark.com/apachemirror/tomcat/tomcat-7/v7.0.69/bin/apache-tomcat-7.0.69.tar.gz

2) unzip file
tar xzf apache-tomcat-7.0.69.tar.gz

3) move the folder to tomcat7

mv apache-tomcat-7.0.69 /usr/local/tomcat7

4) start the tomcat server.
go to the ./bin/startup.sh

output :
cmd : ./bin/startup.sh
Using CATALINA_BASE:   /usr/local/tomcat7/apache-tomcat-7.0.69
Using CATALINA_HOME:   /usr/local/tomcat7/apache-tomcat-7.0.69
Using CATALINA_TMPDIR: /usr/local/tomcat7/apache-tomcat-7.0.69/temp
Using JRE_HOME:        /usr/java/jdk1.8.0_45/jre
Using CLASSPATH:       /usr/local/tomcat7/apache-tomcat-7.0.69/bin/bootstrap.jar:/usr/local/tomcat7/apache-tomcat-7.0.69/bin/tomcat-juli.jar
Tomcat started.

5) set up user account in conf/tomcat-users.xml.

<!-- user manager can access only manager section -->
<role rolename="manager-gui" />
<user username="manager" password="abc" roles="manager-gui" />

<!-- user admin can access manager and admin section both -->
<role rolename="admin-gui" />
<user username="admin" password="def" roles="manager-gui,admin-gui" />


6) change the port to 8082

go to conf/server.xml  and change the default port from 8080 t0 8082

 <Connector port="8082" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />

7) connect to tomcat :
http://xx.xxx.xxx.xxx:8082/manager/html

Monday 25 April 2016

set the java path permanently in linux

c) set the java path

export JAVA_HOME=/usr/java/jdk1.8.0_45

d) Setup JRE_HOME Variable

export JRE_HOME=/usr/java/jdk1.8.0_45/jre

e) Setup PATH Variable

export PATH=$PATH:/usr/java/jdk1.8.0_45/bin:/usr/java/jdk1.8.0_45/jre/bin

environment variable :

/etc/environment

to set the variable permanently.

go to directory
/etc
open profile.
cmd : vi profile

set all the variable at the bottom of the pofile.
check from new command window weather you are able to see the path.

find java path in linux.

find java path in linux.

a) which java
output : /usr/bin/java.

b) readlink -f $(which java)
output : /usr/java/jdk1.8.0_45/jre/bin/java

can we redownload the .pem file, for a key-value pair in aws ec2 instance.

Q) can we redownload the .pem file, for a key-value pair in aws ec2 instance.
A) no. it can be downloaded only once. you  have to create new key-value pair.
ref : stackoverflow 

know which is the user loggedin.

know which is the user loggedin.

syntax : who [OPTION]... [ FILE | ARG1 ARG2 ]

cmd  : who
ref : ibm

intsall nodejs in rhel linux .

intsall nodejs in rhel linux .
command :
1) sudo rpm -ivh epel-release-7-6.noarch.rpm
2) sudo yum install npm
3) node --version

recover terminated instance ec2

Recover terminated instance ec2

1) login to the aws account.
2) go to the instance.
3) go to the elastic block store
a) create a volume.
b) create a snapshot.


REF : aws


Sunday 24 April 2016

How to set up mongodb

How to set up mongodb
download the mongodb sodtware from the site, based on the OS.
Currently OS used is windows7 - 64bit


1)
Install mongo, by click on exe file

Open the command prompt
Now go to installation directory and start the mongo server by providing the db path and port number.

ex : mongod -dbpath C:\mongodb\data\db -port 13627

> go to the bin directory and check the logs file once the server is started

C:\mongodb\log

output :
[websvr] admin web console waiting for connections on port 28017


2)
Now start the mongo client or connect to mongodb

C:\mongodb\bin\mongo

output :

MongoDB shell version: 2.4.5
connecting to: test

> go to bin directory and check the log when we start the mongodb
C:\mongodb\log

output :
connection accepted from 127.0.0.1:50142 #2 (1 connection now open)


2.1 ) For help content

command : db.help()

2.2) to see the database

command  : show dbs

2.3) create collections/db in mongo

command :  use collectionName (if not exixting it will create)


2.4)  To list all collections:

command : show collections


3) Create Collection/table in mongo

ex :  db.createCollection("FirstCollection")
{ "ok" : 1 }

Check in logs file :

[FileAllocator] done allocating datafile \data\db\yourDB.1, size: 128MB,  took 0.249 secs


3.1) see the collection/table created in db
command : show collections
output :
FirstCollection
system.indexes

3.2) for inserting the data
command :
db.FirstCollection.insert({item:"shoes",id:"10"})
output:
{ "_id" : ObjectId("56fd238aecaeb8e797ff4a09"), "item" : "shoes", "id" : "10" }

3.3)
for select the data.
ex :
db.FirstCollection.find()
db.FirstCollection.find()



3.4)fetching specifics record

ex : db.FirstCollection.find({item:"shoes"})
output :
{ "_id" : ObjectId("56fd238aecaeb8e797ff4a09"), "item" : "shoes", "id" : "10" }


3.5) update the record

ex : > db.FirstCollection.update({item:"shoes"},{$set:{item:"11"}})

3.6) update the record if it not exist :

ex : db.FirstCollection.update({item:"shirt"},{id:"22"},{upsert:"true"})

3.7) delete a record

ex : db.FirstCollection.remove({item:"15"})

Saturday 23 April 2016

getting started puppet modules.

getting started puppet modules.


Modules are self-contained bundles of code(each individual is manifest) and data.
REF : puppet
Nearly all Puppet manifests belong in modules.
deafault module directory : /etc/puppet/modules

1)puppet help module.
cmd : puppet help module

def : This subcommand can find, install, and manage modules from the Puppet Forge,
a repository of user-contributed Puppet code. It can also generate empty
modules, and prepare locally developed modules for release on the Forge.

USAGE: puppet module <action> [--environment production ]
[--modulepath $basemodulepath ]

2) module action.
ACTIONS:
  build        Build a module release package.
  changes      Show modified files of an installed module.
  generate     Generate boilerplate for a new module.
  install      Install a module from the Puppet Forge or a release archive.
  list         List installed modules
  search       Search the Puppet Forge for a module.
  uninstall    Uninstall a puppet module.
  upgrade      Upgrade a puppet module.

3) puppet module directory
module directory : /etc/puppet/modules

4) createing the boilerplate for your module
cmd : sudo puppet module generate my-voice
The below will render the metadata of the module my-voice
result :
{
  "name": "my-voice",
  "version": "0.1.0",
  "author": "my",
  "summary": null,
  "license": "Apache 2.0",
  "source": "",
  "project_page": null,
  "issues_url": null,
  "dependencies": [
    {"name":"puppetlabs-stdlib","version_requirement":">= 1.0.0"}
  ]
}


5) list the puppet module.

cmd : sudo puppet module list

Warning: Missing dependency 'puppetlabs-stdlib':
  'my-voice' (v0.1.0) requires 'puppetlabs-stdlib' (>= 1.0.0)
/etc/puppet/modules
├── accounts (???)
└── my-voice (v0.1.0)

6) Install the module from the puppetlab
"puppetlabs-stdlib"
cmd : sudo puppet module install puppetlabs-stdlib
output :
Notice: Preparing to install into /etc/puppet/modules ...
Notice: Downloading from https://forgeapi.puppetlabs.com ...
Notice: Installing -- do not interrupt ...
/etc/puppet/modules
└── puppetlabs-stdlib (v4.11.0)

7) search puppet module in puppetlabs.
output :
Notice: Searching https://forgeapi.puppetlabs.com ...
NAME                   DESCRIPTION                                                                             AUTHOR        KEYWORDS
sharumpe-apache2       Module to manage Apache2 v2.4 in OpenSuSE 13.1                                          @sharumpe
puppetlabs-apache      Installs, configures, and manages Apache virtual hosts, web services, and modules.      @puppetlabs   web httpd rhel apache2 ssl wsgi proxy
nodes-php              Puppet module to manage PHP, PECL & PEAR on debian / ubuntu - easily expandable to ...  @nodes        php pecl pear apc curl gd ssh2 apache2 fpm
saz-php                UNKNOWN                                                                                 @saz          apache debian ubuntu php apache2 fpm cli
mstanislav-apache_yum  UNKNOWN

8) install puppetlabs-apache.
sudo puppet module install puppetlabs-apache

a) sudo puppet module install puppetlabs-apt
Notice: Preparing to install into /etc/puppet/modules ...
Notice: Downloading from https://forgeapi.puppetlabs.com ...
Notice: Installing -- do not interrupt ...
/etc/puppet/modules
└─┬ puppetlabs-apt (v2.2.2)
  └── puppetlabs-stdlib (v4.11.0)


9) puppet module upgrade.
cmd : sudo puppet module upgrade puppetlabs-apt