Display datatable on clicking a button - java

I'm writing a webapp where in there is a table that is to be generated using Ajax. This data is actually pulled from the database. And here I want to use jquery datatable plugin.
Index.jsp
<html>
<head>
</head>
<body>
<marquee>
<h1>This is an example of ajax</h1>
</marquee>
<form name="vinform">
Enter id:<input type="button" id="somebutton" value="Click Me">
</form>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Case Number</th>
<th>Case Owner</th>
<th>Status</th>
<th>Issue</th>
<th>Reason</th>
<th>Date/Time Opened</th>
<th>Age</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Case Number</th>
<th>Case Owner</th>
<th>Status</th>
<th>Issue</th>
<th>Reason</th>
<th>Date/Time Opened</th>
<th>Age</th>
</tr>
</tfoot>
</table>
<span id="somediv"> </span>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="tableGenerator.js"></script>
</body>
</html>
tableGenerator.js
$('#somebutton').click(function() {
$(document).ready(function() {
$('#example').DataTable({
"ajax" : "Controller",
"columns" : [ {
"data" : "userBean.caseNumber"
}, {
"data" : "userBean.caseOwner"
}, {
"data" : "userBean.status"
}, {
"data" : "userBean.issue"
}, {
"data" : "userBean.reason"
}, {
"data" : "userBean.age"
} ]
});
});
});
UserBean.java
package org.bean;
public class UserBean {
private int age;
private String caseOwner, status, issue, reason, dateOpened, caseNumber, resolution, finalStatus, startDate,
endDate;
private Double totalTimeTaken;
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getCaseNumber() {
return caseNumber;
}
public void setCaseNumber(String caseNumber) {
this.caseNumber = caseNumber;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCaseOwner() {
return caseOwner;
}
public void setCaseOwner(String caseOwner) {
this.caseOwner = caseOwner;
}
public String getStatus() {
return status;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public void setStatus(String status) {
this.status = status;
}
public String getIssue() {
return issue;
}
public void setIssue(String issue) {
this.issue = issue;
}
public String getDateOpened() {
return dateOpened;
}
public void setDateOpened(String dateOpened) {
this.dateOpened = dateOpened;
}
public String getResolution() {
return resolution;
}
public void setResolution(String resolution) {
this.resolution = resolution;
}
public String getFinalStatus() {
return finalStatus;
}
public void setFinalStatus(String finalStatus) {
this.finalStatus = finalStatus;
}
public double getTotalTimeTaken() {
return totalTimeTaken;
}
public void setTotalTimeTaken(Double totalTimeTaken) {
this.totalTimeTaken = totalTimeTaken;
}
public UserBean() {
}
public UserBean(String caseNumber, String caseOwner, String issue, int age, String reason, String dateOpened,
String status, String finalStatus, String resolution, String startDate, String endDate,
Double totalTimeTaken) {
this.caseNumber = caseNumber;
this.caseOwner = caseOwner;
this.issue = issue;
this.reason = reason;
this.age = age;
this.dateOpened = dateOpened;
this.status = status;
this.resolution = resolution;
this.finalStatus = finalStatus;
this.startDate = startDate;
this.endDate = endDate;
this.totalTimeTaken = totalTimeTaken;
}
}
Controller.java(Servlet)
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.bean.UserBean;
import com.dao.DataDao;
import com.google.gson.Gson;
#WebServlet("/Controller")
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// String id = request.getParameter("val");
DataDao dataDao = new DataDao();
ArrayList<UserBean> list = dataDao.getFrameWork();
String searchList = new Gson().toJson(list);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(searchList);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
DBUtility.java
package com.dao;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBUtility {
private static Connection connection = null;
public static Connection getConnection() throws Exception {
if (connection != null)
return connection;
else {
// Store the database URL in a string
String userName = "sa";
String password = "T!ger123";
String url = "jdbc:sqlserver:XXXXXX;DatabaseName=TEST";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// set the url, username and password for the databse
connection = DriverManager.getConnection(url, userName, password);
return connection;
}
}
}
DataDao.java
package com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.bean.UserBean;
public class DataDao {
private Connection connection;
public DataDao() throws Exception {
connection = DBUtility.getConnection();
}
public ArrayList<UserBean> getFrameWork() throws SQLException {
ArrayList<UserBean> list = new ArrayList<UserBean>();
PreparedStatement ps = null;
try {
ps = connection.prepareStatement("select * from statusTable");
// ps.setString(1, frameWork);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
UserBean userBean = new UserBean();
userBean.setCaseNumber(rs.getString(1));
userBean.setCaseOwner(rs.getString(2));
userBean.setStatus(rs.getString(3));
userBean.setIssue(rs.getString(4));
userBean.setReason(rs.getString(5));
userBean.setDateOpened(rs.getString(6));
userBean.setAge(rs.getInt(7));
list.add(userBean);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return list;
}
}
When I click on the button, instead of displaying the table data, it is showing nothing apart from the Basic html skeleton created in my index file.
Instead of using
$('#somebutton').click(function() {
$(document).ready(function() {
$('#example').DataTable({
"ajax" : "Controller",
"columns" : [ {
"data" : "userBean.caseNumber"
}, {
"data" : "userBean.caseOwner"
}, {
"data" : "userBean.status"
}, {
"data" : "userBean.issue"
}, {
"data" : "userBean.reason"
}, {
"data" : "userBean.age"
} ]
});
});
});
when i used
$('#somebutton').click(
function() {
$.getJSON('Controller', function(searchList) {
var $table = $('<table>').appendTo($('#somediv'));
$.each(searchList, function(index, userBean) {
$('<tr>').appendTo($table).append(
$('<td>').text(userBean.caseNumber)).append(
$('<td>').text(userBean.caseOwner)).append(
$('<td>').text(userBean.status)).append(
$('<td>').text(userBean.issue)).append(
$('<td>').text(userBean.reason)).append(
$('<td>').text(userBean.age));
});
});
});
A normal html table is getting displayed.
Please let me know how can i display this data.
Thanks

Related

Send JSon object without 'root'

Using Java RestEasy JSon API,
in the next WebService Client code I want to ask you if it is possible to send de JSon object this way:
{
"title" : "Some title book",
"author" : "Some author",
"price" : 99.9
}
... instead of this:
{
"book" :
{
"title" : "Some title book",
"author" : "Some author",
"price" : 99.9
}
}
I mean I dont want to send the 'root' element "book".
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlRootElement(name = "book")
#XmlType(propOrder = {"title", "author", "price"})
public class Book {
private String title;
private String author;
private Double price;
public Book() {
super();
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
}
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import com.fasterxml.jackson.databind.ObjectMapper;
public class BookClient {
public static void main(String[] args) {
Response httpResponse = null;
try {
String url = "http://someserver/somepath/etc";
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target(url);
Book libro1 = new Book();
libro1.setAuthor("Some author");
libro1.setPrice(99.9);
libro1.setTitle("Some title book");
String jsonEnviado = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(libro1);
Entity<Book> entidad = Entity.entity(libro1, "application/json");
httpResponse = target.request().post(entidad);
Respuesta respuesta = httpResponse.readEntity(Respuesta.class);
if (respuesta != null) {
String jsonRecibido = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(respuesta);
}
int status = httpResponse.getStatus();
if (status == 200) {
logTexto = "OK. Status: " + status;
System.out.println(logTexto);
} else {
logTexto = "KO. Status: " + status;
throw new Exception(logTexto);
}
} catch(Exception e) {
System.out.println("EXCEPTION! " + e.getMessage());
e.printStackTrace();
} finally {
if (httpResponse != null) {
try {
httpResponse.close();
} catch (Exception e) {
//IGNORE IT
}
}
}
}
}
Thanks!
Finally I use this to avoid sending root element 'book':
//Entity<Book> entidad = Entity.entity(libro1, "application/json");
//httpResponse = target.request().post(entidad);
Entity<String> entidad = Entity.entity(jsonEnviado, "application/json");
httpResponse = target.request().post(entidad);

JAVA REST jersy + Eclipse + MYSQL insert data into db

I am new to webservices,
inside chrome debugger getting error:
http://localhost:8080/CRUDrestApp/REST/WebService/addUser 500 (Internal Server Error)
And in postman app getting error:
http://localhost:8080/CRUDrestApp/REST/WebService/addUser?regUserName=a
status: 415 Unsupported Media Type
To fix this errors what necessary changes I have to do?
FeedService.java>>
package webService;
import java.util.ArrayList;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import model.ProjectManager;
import model.AddUserManager;
import model.GetUserManager;
import com.google.gson.Gson;
import dto.FeedObjects;
import dto.AddUserObject;
#Path("/WebService")
public class FeedService {
//for insert query
#POST
#Path("/addUser")
#Consumes("application/json")
#Produces("application/json")
public void reguserdata(AddUserObject reguserData)
{
String feeds = null;
try
{
//StringBuffer sb = new StringBuffer();
System.out.println("Inside reguserdata");
Gson gson = new Gson();
System.out.println("Inside add User web service::"+gson.toJson(reguserData));
feeds = gson.toJson(reguserData);
AddUserManager projectManager= new AddUserManager();
projectManager.SetFeeds(feeds);
} catch (Exception e)
{
System.out.println("error");
}
}
}
AddUser.Java>>>
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import dto.AddUserObject;
public class AddUser {
public ArrayList<AddUserObject> GetFeeds(Connection connection, String receivedData) throws Exception
{
ArrayList<AddUserObject> regData = new ArrayList<AddUserObject>();
String receivedData1 = receivedData;
try
{
//String uname = request.getParameter("uname");
//PreparedStatement ps = connection.prepareStatement("SELECT * from users");
//ps.setString(1,uname);
//PreparedStatement ps = connection.prepareStatement("insert into users(username,password,hint1,hint2,emailid,uid) values(?,?,?,?,?,?)");
PreparedStatement ps = connection.prepareStatement("insert into users (username) values (?)");
AddUserObject feedObject = new AddUserObject();
System.out.println("Add>>receivedData1.valueOf(0):"+receivedData1.valueOf(0));
feedObject.setRegUserName(receivedData1.valueOf(0));
System.out.println("Add>>getRegUserName:"+feedObject.getRegUserName());
ps.setString(1, feedObject.getRegUserName());
// ps.setString(2, feedObject.getRegPassword());
// ps.setString(3, feedObject.getRegHint1());
// ps.setString(4, feedObject.getRegHint2());
// ps.setString(5, feedObject.getRegEmail());
// ps.setString(6, feedObject.getRegUid());
regData.add(feedObject);
ps.executeUpdate();
ps.close();
return regData;
}
catch(Exception e)
{
throw e;
}
}
}
AddUserObject.java>>>
package dto;
public class AddUserObject {
private String regId;
private String regusername;
private String regpassword;
private String reghint1;
private String reghint2;
private String regemail;
private String reguid;
/**
* #return the url
*/
public String getRegId() {
return regId;
}
/**
* #param reguid to set
*/
public void setRegId(String regId) {
this.regId = regId;
}
/**
* #return the title
*/
public String getRegUserName() {
return regusername;
}
/**
* #param title the title to set
*/
public void setRegUserName(String regusername) {
this.regusername = regusername;
}
/**
* #return the description
*/
public String getRegPassword() {
return regpassword;
}
/**
* #param description the description to set
*/
public void setRegPassword(String regpassword) {
this.regpassword = regpassword;
}
/**
* #return the url
*/
public String getRegHint1() {
return reghint1;
}
/**
* #param url the url to set
*/
public void setRegHint1(String reghint1) {
this.reghint1 = reghint1;
}
/**
* #return the url
*/
public String getRegHint2() {
return reghint2;
}
/**
* #param url the url to set
*/
public void setRegHint2(String reghint2) {
this.reghint2 = reghint2;
}
/**
* #return the url
*/
public String getRegEmail() {
return regemail;
}
/**
* #param reguid to set
*/
public void setRegEmail(String regemail) {
this.regemail = regemail;
}
/**
* #return the url
*/
public String getRegUid() {
return reguid;
}
/**
* #param reguid to set
*/
public void setRegUid(String reguid) {
this.reguid = reguid;
}
}
AddUserManeger.java>>>
package model;
import java.sql.Connection;
import java.util.ArrayList;
import dao.Database;
import dao.AddUser;
import dto.AddUserObject;
public class AddUserManager {
public static ArrayList<AddUserObject> SetFeeds(String feeds2)throws Exception {
ArrayList<AddUserObject> feeds = null;
String receivedData = feeds2;
try {
Database database= new Database();
Connection connection = database.Get_Connection();
AddUser project= new AddUser();
feeds=project.GetFeeds(connection , receivedData);
} catch (Exception e) {
throw e;
}
return feeds;
}
}
app.js>>
var app = angular.module("mainApp", ['ngRoute','ngAnimate']);
var baseUrl ="http://localhost:8080/CRUDrestApp/REST/WebService";
console.log("Inside App js");
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'home.html',
controller: 'homeCtrl'
}).
when('/register', {
templateUrl: 'register.html',
controller: 'registerCtrl'
}).
when('/login', {
templateUrl: 'login.html',
controller: 'loginCtrl'
}).
otherwise({
templateUrl: 'home.html',
controller: 'HomeCtrl'
});
}]);
app.controller('NavController', function ($scope, $location) {
$scope.isCollapsed = true;
$scope.$on('$routeChangeSuccess', function () {
$scope.isCollapsed = true;
});
$scope.getClass = function (path) {
if(path === '/') {
if($location.path() === '/') {
return "active";
} else {
return "";
}
}
if ($location.path().substr(0, path.length) === path) {
return "active";
} else {
return "";
}
}
});
app.controller('homeCtrl', function($http, $scope, $timeout) {
});
app.controller('loginCtrl', function($http, $scope, $timeout) {
});
console.log("after route provider");
app.controller('registerCtrl', function($http, $scope, $timeout) {
console.log('inside registerAppCtrl controller');
$scope.addUser = function() {
var userdetails = JSON.stringify($scope.userAdd);
console.log("$scope.userAdd::"+userdetails);
if($scope.userAdd.regUserName == "" || $scope.userAdd.regUserPass == "" || $scope.userAdd.regUserCPass == "" || $scope.userAdd.regHint1 == "" || $scope.userAdd.regHint2 == ""){
console.log('Insert mandatory field values');
}
else{
$.ajax({
url: baseUrl + '/addUser',
dataType: 'json',
type: 'post',
contentType: 'application/json ',
data: userdetails,
success: function( data, textStatus, jQxhr ){
//$('#response pre').html( data );
console.log("successfully retrived response from server:::"+data);
/* console.log(data); */
$scope.userAdd = '';
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
}
};
});
Register.html
<section id="" ng-controller="registerCtrl">
<form>
<div>
User Name
</div>
<div>
<input type="text" ng-model="userAdd.regUserName" required>
</div>
<div>
Password
</div>
<div>
<input type="password" ng-model="userAdd.regUserPass" >
</div>
<div>
Confirm Password
</div>
<div>
<input type="password" ng-model="userAdd.regUserCPass" >
</div>
<div>
Enter Hint1
</div>
<div>
<input type="text" ng-model="userAdd.regHint1" >
</div>
<div>
Enter Hint2
</div>
<div>
<input type="text" ng-model="userAdd.regHint2" >
</div>
<div>
Enter UID
</div>
<div>
<input type="text" ng-model="userAdd.regUid" >
</div>
<div>
<input type="submit" name="Register" value="Register" ng-click="addUser()">
</div>
<div>
Login
</div>
</form>
</section>
make an empty constructor in your AddUserObject.java
public AddUserObject(){}

Output of Java code is not getting in WSO2 logs

I am unable to see the output of the below java code in WSO2 logs.
package com.esb.integration.mediators;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMText;
import org.apache.synapse.MessageContext;
import org.apache.synapse.mediators.AbstractMediator;
public class DbLookup extends AbstractMediator {
private String url;
private String userName;
private String password;
private String database;
private String status;
private String action;
private String DSP;
private String USER;
private String PID;
private String PMJ;
private String PMT;
private String NZPO;
private String PD;
private String SD;
public boolean mediate(MessageContext context) {
String url = (String) context.getProperty("url");
String userName = (String) context.getProperty("userName");
String password = (String) context.getProperty("password");
String database = (String) context.getProperty("database");
String status = (String) context.getProperty("status");
String action = (String) context.getProperty("action");
try {
System.out.println("Inside DB Extractor");
System.out.println("Action: "+action);
Class.forName("com.access.JDBCDriver");
Connection conn = DriverManager.getConnection(url,userName,password);
Statement stmt = conn.createStatement();
System.out.println("After getting connection");
if (action.equals("updateData")){
System.out.println("Inside if: "+action);
int result =0;
DSP = (String) context.getProperty("DSP");
USER = (String) context.getProperty("USER");
PID = (String) context.getProperty("PID");
PMJ = (String) context.getProperty("PMJ");
PMT = (String) context.getProperty("PMT");
NZPO = (String) context.getProperty("NZPO");
PD = (String) context.getProperty("PD");
SD = (String) context.getProperty("SD");
String updateQuery = "Update Table Set DSP = '"+DSP+"',USER = '"+USER+"',PID = '"+PID+"',PMJ="+PMJ+",PMT="+PMT+" Where DSP<>'Y' AND NZPO='"+NZPO+"' AND PD='"+PD+"' AND SD="+SD;
System.out.println("Query String: "+updateQuery);
result = stmt.executeUpdate(updateQuery);
if(result>0){
String response = "successfully updated "+result+" rows";
System.out.println("successfully added "+result);
context.setProperty("status",response);
return true;
}
else{
System.out.println("failed");
context.setProperty("status","0 rows were updated");
return true;
}
}
else {
context.setProperty("status","Failed");
return false;
}
}catch (Exception e) {
System.out.println("Got an exception! ");
System.out.println(e.getMessage());
context.setProperty("status","Failed");
return false;
}
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDatabase() {
return database;
}
public void setDatabase(String database) {
this.database = database;
}
public String getstatus() {
return status;
}
public void setstatus(String status) {
this.status = status;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getDSP() {
return DSP;
}
public void setDSP(String DSP) {
DSP = DSP;
}
public String getUSER() {
return USER;
}
public void setUSER(String USER) {
USER = USER;
}
public String getPID() {
return PID;
}
public void setPID(String PID) {
PID = PID;
}
public String getPMJ() {
return PMJ;
}
public void setPMJ(String PMJ) {
PMJ = PMJ;
}
public String getPMT() {
return PMT;
}
public void setPMT(String PMT) {
PMT = PMT;
}
public String getNZPO() {
return NZPO;
}
public void setNZPO(String NZPO) {
NZPO = NZPO;
}
public String getPD() {
return PD;
}
public void setPD(String PD) {
PD = PD;
}
public String getSD() {
return SD;
}
public void setSD(String SD) {
SD = SD;
}
}
Here is the proxy service:-
<proxy xmlns="http://ws.apache.org/ns/synapse" name="TestProxy" transports="jms" statistics="disable" trace="disable" startOnLoad="true">
<inSequence>
<property name="userName" value="****"></property>
<property name="password" value="****"></property>
<property name="url" value="********"></property>
<property name="action" value="updateData"></property>
<iterate id="Item" expression="//itemList/item" sequential="true">
<target>
<sequence>
<property name="DSP" expression="//DSP/text()"></property>
<property name="USER" expression="//USER/text()"></property>
<property name="PID" expression="//PID/text()"></property>
<property name="PMJ" expression="//PMJ/text()"></property>
<property name="PMT" expression="//PMT/text()"></property>
<property name="NZPO" expression="//NZPO/text()"></property>
<property name="PD" expression="//PD/text()"></property>
<property name="SD" expression="//SD/text()"></property>
<class name="com.esb.integration.mediators.DbLookup"></class>
<log separator=",**after updatedb call**" description=""></log>
</sequence>
</target>
</iterator>
</inSequence>
<loopback/>
<outSequence/>
<parameter name="transport.jms.ContentType">application/json</parameter>
<parameter name="transport.jms.Destination">TestProxy.Q</parameter>
</proxy>
But,I can only see the "after updatedb call" message in logs when the query is executing successfully.
What should I add/modify above to get the message(which are written as System.out.println(" ")) in the WSO2 logs?
In [ESB_HOME]\repository\conf\log4j.properties put this:
log4j.logger.package=INFO, CARBON_LOGFILE, CARBON_MEMORY
Where package = the package of your class, in my case:
log4j.logger.org.softdevelop.test=INFO, CARBON_LOGFILE, CARBON_MEMORY
Restart the server and try with:
if (log.isInfoEnabled()) {
log.info("First Element log : " + firstElement.getLocalName());
}
System.out.println("First Element Text syso : " + firstElement.getText());
In my case the log print:
[2017-03-13 12:16:30,010] INFO - testIterateProperty First Element log : jsonObject
First Element Text syso :
log.info("whatever you want");

Auto-generation of email with username and random password on creation of new user

I have created a class NewUserEmail to auto generate an email with username and password while creating a new user. I am able to create the password but whenever I am trying to log in with that password, its not logging in. I am not able to generate my mail. Please guide me and let me know what is wrong with my code:
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.jscript.ClasspathScriptLocation;
import org.alfresco.repo.node.NodeServicePolicies;
import org.alfresco.repo.policy.JavaBehaviour;
import org.alfresco.repo.policy.PolicyComponent;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.apache.log4j.Logger;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
public class NewUserEmail implements NodeServicePolicies.OnCreateNodePolicy {
private Logger logger = Logger.getLogger(NewUserEmail.class);
private PolicyComponent policyComponent;
private NodeService nodeService;
private PersonService personService;
private ServiceRegistry serviceRegistry;
protected String userName = null;
protected String password = null;
protected String email = null;
protected String subject = null;
protected String body = null;
private static final String NEW_USER_EMAIL_TEMPLATE = "alfresco/module/demoact1-repo/template/new_user_email.ftl";
private static final String EMAIL_FROM = "no-reply#eisenvault.com";
public void init() {
this.email = "";
this.userName = "";
this.password = "";
this.subject = "New User Alfresco";
this.body = "";
this.policyComponent.bindClassBehaviour(
QName.createQName(NamespaceService.ALFRESCO_URI, "onCreateNode"),
ContentModel.TYPE_PERSON,
new JavaBehaviour(this, "ReportUser", org.alfresco.repo.policy.JavaBehaviour.NotificationFrequency.EVERY_EVENT)
);
}
public void onCreateNode(ChildAssociationRef childAssocRef) {
if (logger.isInfoEnabled()) logger.info(" NewUserEmail Node create policy fired");
}
public void setNodeService(NodeService nodeService) {
this.nodeService = nodeService;
}
public void setPolicyComponent(PolicyComponent policyComponent) {
this.policyComponent = policyComponent;
}
public void setServiceRegistry(ServiceRegistry serviceRegistry) {
this.serviceRegistry = serviceRegistry;
}
public String getSubject() {
return this.subject;
}
public String getBody() {
return this.body;
}
public String getEmail() {
return this.email;
}
public String getUserName() {
return this.userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void ReportUser(ChildAssociationRef childAssocRef) {
NodeRef personRef = childAssocRef.getChildRef();
this.userName = (String) this.nodeService.getProperty(personRef, ContentModel.PROP_USERNAME);
this.email = (String) this.nodeService.getProperty(personRef, ContentModel.PROP_EMAIL);
sendEmail();
}
public void sendEmail() throws AlfrescoRuntimeException {
Map<String, Object> templateModel = new HashMap<String, Object>();
if (getEmail() != null && getEmail() != "") {
Set<NodeRef> result = serviceRegistry.getPersonService().getPeopleFilteredByProperty(ContentModel.PROP_EMAIL, getEmail(), 1);
if (result.size() == 1) {
changePassword(getUserName());
ClasspathScriptLocation location = new ClasspathScriptLocation(NEW_USER_EMAIL_TEMPLATE);
try {
if (location.getInputStream() != null) {
// Check that there is a template
templateModel.put("userName", getUserName());
templateModel.put("password", getPassword());
this.body = serviceRegistry.getTemplateService().processTemplate("freemarker", NEW_USER_EMAIL_TEMPLATE, templateModel);
}
} catch (AlfrescoRuntimeException e) {
// If template isn't found, email is constructed "manually"
logger.error("Email Template not found " + NEW_USER_EMAIL_TEMPLATE);
this.body = "<html> <body> <p> A new User has been created.</p>" +
"<p>Hello, </p><p>Your username is " + getUserName() + " and your " +
"password is " + getPassword() + "</p> " +
"<p>We strongly advise you to change your password when you log in for the first time.</p>" +
"Regards</body> </html>";
//send();
}
}
}
}
protected void send() {
MimeMessagePreparator mailPreparer = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws MessagingException {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
message.setTo(getEmail());
message.setSubject(getSubject());
message.setText(getBody(), true);
message.setFrom(EMAIL_FROM);
}
};
}
public void changePassword(String password) {
AuthenticationUtil.setRunAsUserSystem();
Set<NodeRef> result = serviceRegistry.getPersonService().getPeopleFilteredByProperty(ContentModel.PROP_EMAIL, getEmail(), 1);
if (result.size() == 1) {
Object[] userNodeRefs = result.toArray();
NodeRef userNodeRef = (NodeRef) userNodeRefs[0];
String username = (String) serviceRegistry.getNodeService().getProperty(userNodeRef, ContentModel.PROP_USERNAME);
// Generate random password
String newPassword = Password.generatePassword();
char[] cadChars = new char[newPassword.length()];
for (int i = 0; i < newPassword.length(); i++) {
cadChars[i] = newPassword.charAt(i);
}
serviceRegistry.getAuthenticationService().setAuthentication(username, newPassword.toCharArray());
setPassword(newPassword);
System.out.println("Password is :" + newPassword);
}
}
}
Below is a working solution.
resource/alfresco/extension/new-user-email-context.xml:
<?xml version='1.0' encoding='UTF-8'?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="newUserEmail" class="demo.NewUserEmail">
<property name="policyComponent" ref="policyComponent"/>
<property name="nodeService" ref="nodeService"/>
<property name="personService" ref="personService"/>
<property name="passwordGenerator" ref="passwordGenerator"/>
<property name="authenticationService" ref="authenticationService"/>
</bean>
</beans>
demo.NewUserEmail.java:
package demo;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.node.NodeServicePolicies;
import org.alfresco.repo.policy.*;
import org.alfresco.repo.security.authentication.PasswordGenerator;
import org.alfresco.service.cmr.repository.*;
import org.alfresco.service.cmr.security.*;
import org.alfresco.util.PropertyCheck;
import org.springframework.beans.factory.InitializingBean;
public class NewUserEmail implements
NodeServicePolicies.OnCreateNodePolicy, InitializingBean {
#Override
public void onCreateNode(ChildAssociationRef childAssocRef) {
notifyUser(childAssocRef);
}
private void notifyUser(ChildAssociationRef childAssocRef) {
NodeRef personRef = childAssocRef.getChildRef();
// get the user name
String username = (String) this.nodeService.getProperty(
personRef, ContentModel.PROP_USERNAME);
// generate the new password (Alfresco's rules)
String newPassword = passwordGenerator.generatePassword();
// set the new password
authenticationService.setAuthentication(username, newPassword.toCharArray());
// send default notification to the user
personService.notifyPerson(username, newPassword);
}
private PolicyComponent policyComponent;
private NodeService nodeService;
private PersonService personService;
private PasswordGenerator passwordGenerator;
private MutableAuthenticationService authenticationService;
public void setPolicyComponent(PolicyComponent policyComponent) {
this.policyComponent = policyComponent;
}
public void setNodeService(NodeService nodeService) {
this.nodeService = nodeService;
}
public void setPersonService(PersonService personService) {
this.personService = personService;
}
public void setPasswordGenerator(PasswordGenerator passwordGenerator) {
this.passwordGenerator = passwordGenerator;
}
public void setAuthenticationService(AuthenticationService authenticationService) {
if (authenticationService instanceof MutableAuthenticationService) {
this.authenticationService = (MutableAuthenticationService) authenticationService;
}
}
#Override
public void afterPropertiesSet() throws Exception {
PropertyCheck.mandatory(this, "policyComponent", policyComponent);
PropertyCheck.mandatory(this, "nodeService", nodeService);
PropertyCheck.mandatory(this, "passwordGenerator", passwordGenerator);
PropertyCheck.mandatory(this, "authenticationService", authenticationService);
PropertyCheck.mandatory(this, "personService", personService);
this.policyComponent.bindClassBehaviour(
NodeServicePolicies.OnCreateNodePolicy.QNAME,
ContentModel.TYPE_PERSON,
new JavaBehaviour(this,
NodeServicePolicies.OnCreateNodePolicy.QNAME.getLocalName(),
Behaviour.NotificationFrequency.TRANSACTION_COMMIT
)
);
}
}

SQL syntax error in pagination query

I'm trying to make pagination in my jsp page. But I didn't get data from Database. I got an error "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-10, 5' at line 1".
I didn't understand what's wrong. would you please check my code and help me to solve the problem?
BooksInfo.java
package com.sreejonee.books;
import java.sql.Date;
import java.sql.Timestamp;
public class BooksInfo {
private int book_id;
private String bookName;
private String filename;
private String writerName;
private String book_details;
private Timestamp date_time;
private int rating;
private int parentscat_id;
private String parentscat_name;
private String thumCoverImag;
private String filePath;
public int getBook_id() {
return book_id;
}
public void setBook_id(int book_id) {
this.book_id = book_id;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getWriterName() {
return writerName;
}
public void setWriterName(String writerName) {
this.writerName = writerName;
}
public String getBook_details() {
return book_details;
}
public void setBook_details(String book_details) {
this.book_details = book_details;
}
public Timestamp getDate_time() {
return date_time;
}
public void setDate_time(Timestamp date_time) {
this.date_time = date_time;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public int getParentscat_id() {
return parentscat_id;
}
public void setParentscat_id(int parentscat_id) {
this.parentscat_id = parentscat_id;
}
public String getParentscat_name() {
return parentscat_name;
}
public void setParentscat_name(String parentscat_name) {
this.parentscat_name = parentscat_name;
}
public String getThumCoverImag() {
return thumCoverImag;
}
public void setThumCoverImag(String thumCoverImag) {
this.thumCoverImag = thumCoverImag;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
BooksInfoDAO.java
package com.sreejonee.books;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import com.sreejonee.db.ConnectionFactory;
import com.sreejonee.db.DBConnector;
public class BooksInfoDAO {
Connection connection;
Statement stmt;
private int noOfRecords;
private static Connection getConnection()
throws SQLException,
ClassNotFoundException
{
Connection con = ConnectionFactory.
getInstance().getConnection();
System.out.println("connected!");
return con;
}
public List<BooksInfo> viewAllBooksInfo(int offset, int noOfRecords) {
String query = "select SQL_CALC_FOUND_ROWS * from library ORDER by date_time DESC limit"+ offset + ", " + noOfRecords;
List<BooksInfo> bookslist = new ArrayList<BooksInfo>();
BooksInfo books = null;
try {
connection = getConnection();
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
books = new BooksInfo();
books.setBook_id(rs.getInt("book_id"));
books.setBook_details(rs.getString("book_details"));
books.setBookName(rs.getString("bookName"));
books.setWriterName(rs.getString("writerName"));
books.setDate_time(rs.getTimestamp("date_time"));
books.setParentscat_id(rs.getInt("parentscat_id"));
books.setParentscat_name(rs.getString("parentscat_name"));
books.setFilename(rs.getString("filename"));
books.setFilePath(rs.getString("filePath"));
books.setRating(rs.getInt("rating"));
books.setThumCoverImag(rs.getString("thumCoverImag"));
bookslist.add(books);
}
rs.close();
rs = stmt.executeQuery("SELECT FOUND_ROWS()");
if (rs.next())
this.noOfRecords = rs.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e2) {
e2.printStackTrace();
}
}
return bookslist;
}
public int getNoOfRecords() {
return noOfRecords;
}
}
Servlet:
BooksInfoServlet.java
package com.sreejonee.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sreejonee.books.BooksInfo;
import com.sreejonee.books.BooksInfoDAO;
#WebServlet("/BooksInfoServlet")
public class BooksInfoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public BooksInfoServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int page = 1;
int recordsPerPage = 5;
if(request.getParameter("page") != null)
page = Integer.parseInt(request.getParameter("page"));
BooksInfoDAO booksInfoDAO = new BooksInfoDAO();
List<BooksInfo> bookslist = booksInfoDAO.viewAllBooksInfo((page-1)*recordsPerPage, recordsPerPage);
int noOfRecords = booksInfoDAO.getNoOfRecords();
int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);
request.setAttribute("booksList", bookslist);
request.setAttribute("noOfPages", noOfPages);
request.setAttribute("currentPage", page);
RequestDispatcher view = request.getRequestDispatcher("user.jsp");
view.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
JSP page:
<c:forEach var="books" items="${bookslist}">
<div id="${books.filename}" class="single_midlecontent_component">
<div class="socialicon_on_post">
<h4>
<i class="fa fa-facebook-square"></i>
</h4>
</div>
<div class="title_of_post ">
<a href="#" class="media-left">
<img class="media-object" src="${books.getFilePath()+File.separator+books.getThumCoverImag()}" alt="...">
</a>
<h5 class="media-body ">
<span>${books.getBookName()}</span>
</h5>
<h5 class="media-body ">
<span>by ${books.getWriterName()}</span>
</h5>
<p class="date_time media-body">${books.getDate_time()}</p>
</div>
<div class="body_of_post">
<p>${books.getBook_details()}</p>
<img src="" class="img-responsive" alt="Responsive image">
</div>
<div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data-layout="standard" data-action="like" data-show-faces="true" data-share="true"></div>
<div class="download_book">
<form action="DownloadFileServlet" method="post">
<input type="hidden" name="filename" value="${books.getFilename()}">
<div>
<input type="hidden" name="parentscat_name" value="${books.getParentscat_name()}">
</div>
<div class="download_button">
<input class="btn btn-default " type="submit" value="Download">
</div>
</form>
</div>
<div class="bottom_of_post"></div>
</div>
I can see two errors here.
First one:
String query = "select SQL_CALC_FOUND_ROWS * from library ORDER by date_time DESC limit"+ offset + ", " + noOfRecords;
There is a space missing after limit -- the way you wrote it, it will generate ... limit10, 5.
Second one:
I think the caller of viewAllBooksInfo() gives a wrong offset argument. Based on the error, I assume that offset is -10 which is illegal because the arguments to the limit clause in MySQL need to be non-negative.
In your updated question, you show this code:
if(request.getParameter("page") != null)
page = Integer.parseInt(request.getParameter("page"));
BooksInfoDAO booksInfoDAO = new BooksInfoDAO();
List<BooksInfo> bookslist = booksInfoDAO.viewAllBooksInfo((page-1)*recordsPerPage, recordsPerPage);
Obviously, because recordsPerPage is 5, and offset is -10, page seems to be -1. You have not shown the Code for the page which calls the BooksInfoServlet, but I guess you have entered -1 as the requested page number there.
You should have looked yourself before asking this question. It is expected from you that you should first try to remove these error yourself.
If you would look into the error stack, it says:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-10, 5' at line 1"
If you can look carefully, the limit options are "-10, 5". Limit arguments in MySQL should be non-negative.
And in BooksInfoDAO.java code:
public List<BooksInfo> viewAllBooksInfo(int offset, int noOfRecords) {
String query = "select SQL_CALC_FOUND_ROWS * from library ORDER by date_time DESC limit"+ offset + ", " + noOfRecords;
...
you are missing a space between the limit clause and the offset parameter.

Categories

Resources