Archive for 2014
EJB Transaction Management
Cannot use an EntityTransaction while using JTA
I found this was useful to fix that scenario Cannot use an
EntityTransaction while using JTA.
Bean Managed Transactions
In Bean Managed Transactions, Transactions can be managed by handling exceptions at application level. Following are the key points to be considered
- Start - When to start a transaction in a business method.
- Sucess - Identify success scenario when a transaction is to be committed.
- Failed - Identify failure scenario when a transaction is to be rollback.
Example
package com.tutorialspoint.txn.bmt;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.transaction.UserTransaction;
@Stateless
@TransactionManagement(value=TransactionManagementType.BEAN)
public class AccountBean implements AccountBeanLocal {
@Resource
private
UserTransaction userTransaction;
public void
transferFund(Account fromAccount, double fund ,
Account
toAccount) throws Exception{
try{
userTransaction.begin();
confirmAccountDetail(fromAccount);
withdrawAmount(fromAccount,fund);
confirmAccountDetail(toAccount);
depositAmount(toAccount,fund);
userTransaction.commit();
}catch
(InvalidAccountException exception){
userTransaction.rollback();
}catch
(InsufficientFundException exception){
userTransaction.rollback();
}catch
(PaymentException exception){
userTransaction.rollback();
}
}
private void
confirmAccountDetail(Account account)
throws
InvalidAccountException {
}
private void
withdrawAmount() throws InsufficientFundException {
}
private void
depositAmount() throws PaymentException{
}
}
In this example, we made use of UserTransaction interface to mark beginning of transaction usinguserTransaction.begin() method call. We mark completion of transaction by usinguserTransaction.commit() method and if any exception occured during transaction then we rollback the complete transaction using userTransaction.rollback() method call.
Reference : http://www.tutorialspoint.com/ejb/ejb_transactions.htm
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<script>
</script>
<script>
$(document).ready(function(){
$("td").dblclick(function(){
document.getElementById("dialog").innerHTML = $(this).text();
$( "#dialog" ).dialog();
});
}); </script>
<body>
<table border="1">
<tr><td>re</td><td >dsf f ds fd
g</td></tr>
<tr><td>as</td><td>rt</td></tr>
</table>
<div id="dialog" title="Basic dialog" style="display:none;" >
<p>
</p>
</div>
</body>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<script>
</script>
<script>
$(document).ready(function(){
$("td").dblclick(function(){
document.getElementById("dialog").innerHTML = $(this).text();
$( "#dialog" ).dialog();
});
}); </script>
<body>
<table border="1">
<tr><td>re</td><td >dsf f ds fd
g</td></tr>
<tr><td>as</td><td>rt</td></tr>
</table>
<div id="dialog" title="Basic dialog" style="display:none;" >
<p>
</p>
</div>
</body>
Send/Raed Email using JAVA
package createbwimagenojairender;
/**
*
* @author Mukunth
*/
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMailTLS {
public static void main(String[] args) {
final String username = "username@gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from-email@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-email@gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
-------------------------------------------------------------------------------------------------------
Read Email using java
package createbwimagenojairender;
/**
*
* @author Mukunth
*/
import java.util.*;
import javax.mail.*;
public class ReadingEmail {
public static void main(String[] args) {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap.gmail.com", "username@gmail.com", "password");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message msg = inbox.getMessage(inbox.getMessageCount());
Address[] in = msg.getFrom();
for (Address address : in) {
System.out.println("FROM:" + address.toString());
}
Multipart mp = (Multipart) msg.getContent();
BodyPart bp = mp.getBodyPart(0); (0---> mail content in console 1--->mail content in Html format )
System.out.println("SENT DATE:" + msg.getSentDate());
System.out.println("SUBJECT:" + msg.getSubject());
System.out.println("CONTENT:" + bp.getContent());
} catch (Exception mex) {
mex.printStackTrace();
}
}
}
--------------------------------------------------------------------------------------------------------
Mail box home page
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class HttpUrlConnectionExample {
private List<String> cookies;
private HttpsURLConnection conn;
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
String url = "https://accounts.google.com/ServiceLoginAuth";
String gmail = "https://mail.google.com/mail/";
HttpUrlConnectionExample http = new HttpUrlConnectionExample();
// make sure cookies is turn on
CookieHandler.setDefault(new CookieManager());
// 1. Send a "GET" request, so that you can extract the form's data.
String page = http.GetPageContent(url);
String postParams = http.getFormParams(page, "username@gmail.com", "password");
// 2. Construct above post's content and then send a POST request for
// authentication
http.sendPost(url, postParams);
// 3. success then go to gmail.
String result = http.GetPageContent(gmail);
System.out.println(result);
}
private void sendPost(String url, String postParams) throws Exception {
URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
// Acts like a browser
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Host", "accounts.google.com");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
for (String cookie : this.cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Referer", "https://accounts.google.com/ServiceLoginAuth");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
conn.setDoOutput(true);
conn.setDoInput(true);
// Send post request
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + postParams);
System.out.println("Response Code : " + responseCode);
BufferedReader in =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// System.out.println(response.toString());
}
private String GetPageContent(String url) throws Exception {
URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
// default is GET
conn.setRequestMethod("GET");
conn.setUseCaches(false);
// act like a browser
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
if (cookies != null) {
for (String cookie : this.cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
}
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Get the response cookies
setCookies(conn.getHeaderFields().get("Set-Cookie"));
return response.toString();
}
public String getFormParams(String html, String username, String password)
throws UnsupportedEncodingException {
System.out.println("Extracting form's data...");
Document doc = Jsoup.parse(html);
// Google form id
Element loginform = doc.getElementById("gaia_loginform");
Elements inputElements = loginform.getElementsByTag("input");
List<String> paramList = new ArrayList<String>();
for (Element inputElement : inputElements) {
String key = inputElement.attr("name");
String value = inputElement.attr("value");
if (key.equals("Email"))
value = username;
else if (key.equals("Passwd"))
value = password;
paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
}
// build parameters list
StringBuilder result = new StringBuilder();
for (String param : paramList) {
if (result.length() == 0) {
result.append(param);
} else {
result.append("&" + param);
}
}
return result.toString();
}
public List<String> getCookies() {
return cookies;
}
public void setCookies(List<String> cookies) {
this.cookies = cookies;
}
}
CRUD
------------------------------------------------------------------------------------------------------------
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.Mk.bean;
import com.Mk.dao.customerDao;
import com.Mk.daoImpl.customerDaoImpl;
import com.Mk.entity.Customer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.RowEditEvent;
import org.primefaces.model.LazyDataModel;
@ManagedBean(name = "customer")
@SessionScoped
public class customerBean {
private String customerName;
private String customerEmail;
private String customerPhoneNo;
private String customerAddress;
private String customerCity;
private String customerPincode;
private String customerState;
private String customerCountry;
private String customerWebsite;
private String customerComments;
private Customer selectedcust;
public Customer getSelectedcust() {
return selectedcust;
}
public void setSelectedcust(Customer selectedcust) {
this.selectedcust = selectedcust;
}
public String getCustomerAddress() {
return customerAddress;
}
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}
public String getCustomerCity() {
return customerCity;
}
public void setCustomerCity(String customerCity) {
this.customerCity = customerCity;
}
public String getCustomerPincode() {
return customerPincode;
}
public void setCustomerPincode(String customerPincode) {
this.customerPincode = customerPincode;
}
public String getCustomerState() {
return customerState;
}
public void setCustomerState(String customerState) {
this.customerState = customerState;
}
public String getCustomerCountry() {
return customerCountry;
}
public void setCustomerCountry(String customerCountry) {
this.customerCountry = customerCountry;
}
public String getCustomerWebsite() {
return customerWebsite;
}
public void setCustomerWebsite(String customerWebsite) {
this.customerWebsite = customerWebsite;
}
public String getCustomerComments() {
return customerComments;
}
public void setCustomerComments(String customerComments) {
this.customerComments = customerComments;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerEmail() {
return customerEmail;
}
public void setCustomerEmail(String customerEmail) {
this.customerEmail = customerEmail;
}
public String getCustomerPhoneNo() {
return customerPhoneNo;
}
public void setCustomerPhoneNo(String customerPhoneNo) {
this.customerPhoneNo = customerPhoneNo;
}
private void addMessage(FacesMessage message) {
FacesContext.getCurrentInstance().addMessage(null, message);
}
public void addCustomer() {
customerDao dao=new customerDaoImpl();
Customer cust=new Customer();
cust.setCustomerName(customerName);
cust.setCustomerEmail(customerEmail);
cust.setCustomerPhoneNo(customerPhoneNo);
cust.setCustomerAddress(customerAddress);
cust.setCustomerCity(customerCity);
cust.setCustomerComments(customerComments);
cust.setCustomerPincode(customerPincode);
cust.setCustomerWebsite(customerWebsite);
cust.setCustomerCountry(customerCountry);
cust.setCustomerState(customerState);
dao.insertCustomer(cust);
addMessage(new FacesMessage(FacesMessage.SEVERITY_INFO, customerName
+ " Details Was Saved Successfully!!!", null));
}
public void resetCustomer() {
this.customerName=null;
this.customerEmail=null;
this.customerPhoneNo=null;
this.customerAddress=null;
this.customerCity=null;
this.customerComments=null;
this.customerPincode=null;
this.customerWebsite=null;
this.customerCountry=null;
this.customerState=null;
}
private List<Customer> allCustomer;
public List<Customer> findAll() {
allCustomer=new ArrayList<Customer>();
customerDao dao=new customerDaoImpl();
allCustomer=dao.viewCustomer();
return allCustomer;
}
public void editCustomer(RowEditEvent event) {
customerDao dao=new customerDaoImpl();
dao.editCustomer((Customer) event.getObject());
}
@SuppressWarnings("empty-statement")
public void onEdit(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Customer Edited", ((Customer) event.getObject()).getCustomerName());
customerDao dao=new customerDaoImpl();
dao.editCustomer((Customer) event.getObject());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Customer Cancelled", ((Customer) event.getObject()).getCustomerName());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public List<Customer> remove(Customer c) {
customerDao dao=new customerDaoImpl();
dao.removeCustomer(c);
allCustomer=dao.viewCustomer();
return allCustomer;
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.Mk.bean;
import com.Mk.dao.customerDao;
import com.Mk.daoImpl.customerDaoImpl;
import com.Mk.entity.Customer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.RowEditEvent;
import org.primefaces.model.LazyDataModel;
@ManagedBean(name = "customer")
@SessionScoped
public class customerBean {
private String customerName;
private String customerEmail;
private String customerPhoneNo;
private String customerAddress;
private String customerCity;
private String customerPincode;
private String customerState;
private String customerCountry;
private String customerWebsite;
private String customerComments;
private Customer selectedcust;
public Customer getSelectedcust() {
return selectedcust;
}
public void setSelectedcust(Customer selectedcust) {
this.selectedcust = selectedcust;
}
public String getCustomerAddress() {
return customerAddress;
}
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}
public String getCustomerCity() {
return customerCity;
}
public void setCustomerCity(String customerCity) {
this.customerCity = customerCity;
}
public String getCustomerPincode() {
return customerPincode;
}
public void setCustomerPincode(String customerPincode) {
this.customerPincode = customerPincode;
}
public String getCustomerState() {
return customerState;
}
public void setCustomerState(String customerState) {
this.customerState = customerState;
}
public String getCustomerCountry() {
return customerCountry;
}
public void setCustomerCountry(String customerCountry) {
this.customerCountry = customerCountry;
}
public String getCustomerWebsite() {
return customerWebsite;
}
public void setCustomerWebsite(String customerWebsite) {
this.customerWebsite = customerWebsite;
}
public String getCustomerComments() {
return customerComments;
}
public void setCustomerComments(String customerComments) {
this.customerComments = customerComments;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerEmail() {
return customerEmail;
}
public void setCustomerEmail(String customerEmail) {
this.customerEmail = customerEmail;
}
public String getCustomerPhoneNo() {
return customerPhoneNo;
}
public void setCustomerPhoneNo(String customerPhoneNo) {
this.customerPhoneNo = customerPhoneNo;
}
private void addMessage(FacesMessage message) {
FacesContext.getCurrentInstance().addMessage(null, message);
}
public void addCustomer() {
customerDao dao=new customerDaoImpl();
Customer cust=new Customer();
cust.setCustomerName(customerName);
cust.setCustomerEmail(customerEmail);
cust.setCustomerPhoneNo(customerPhoneNo);
cust.setCustomerAddress(customerAddress);
cust.setCustomerCity(customerCity);
cust.setCustomerComments(customerComments);
cust.setCustomerPincode(customerPincode);
cust.setCustomerWebsite(customerWebsite);
cust.setCustomerCountry(customerCountry);
cust.setCustomerState(customerState);
dao.insertCustomer(cust);
addMessage(new FacesMessage(FacesMessage.SEVERITY_INFO, customerName
+ " Details Was Saved Successfully!!!", null));
}
public void resetCustomer() {
this.customerName=null;
this.customerEmail=null;
this.customerPhoneNo=null;
this.customerAddress=null;
this.customerCity=null;
this.customerComments=null;
this.customerPincode=null;
this.customerWebsite=null;
this.customerCountry=null;
this.customerState=null;
}
private List<Customer> allCustomer;
public List<Customer> findAll() {
allCustomer=new ArrayList<Customer>();
customerDao dao=new customerDaoImpl();
allCustomer=dao.viewCustomer();
return allCustomer;
}
public void editCustomer(RowEditEvent event) {
customerDao dao=new customerDaoImpl();
dao.editCustomer((Customer) event.getObject());
}
@SuppressWarnings("empty-statement")
public void onEdit(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Customer Edited", ((Customer) event.getObject()).getCustomerName());
customerDao dao=new customerDaoImpl();
dao.editCustomer((Customer) event.getObject());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Customer Cancelled", ((Customer) event.getObject()).getCustomerName());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public List<Customer> remove(Customer c) {
customerDao dao=new customerDaoImpl();
dao.removeCustomer(c);
allCustomer=dao.viewCustomer();
return allCustomer;
}
}
------------------------------------------------------------------------------------------------------------
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.Mk.bean;
import java.io.IOException;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
/**
*
* @author manoj
*/
@ManagedBean(name = "login")
@SessionScoped
public class loginbean {
String username;
String Password;
//<f:event listener="#{login.sessiontest(login.username)}" type="preRenderView" />
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 validate()
{
FacesContext fc = FacesContext.getCurrentInstance();
String user = (String) fc.getExternalContext().getSessionMap().put("user", username);
if ("admin".equals(username) && "admin".equals(Password))
{
return "/faces/registration?faces-redirect=true";
}
if (!"admin".equals(username) || !"admin".equals(Password))
{ show();}
return null;
}
public void show()
{
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage("Login failed","Invalid Details"));
}
public String sessiontest() throws IOException
{
FacesContext fc = FacesContext.getCurrentInstance();
String user = (String) fc.getExternalContext().getSessionMap().get("user");
if (user==null)
{
redirect("login.xhtml");
}
return null;
}
private void redirect(String url) throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
fc.getExternalContext().redirect(url);
}
public String logout()
{
((HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true)).invalidate();
return "/faces/login?faces-redirect=true";
}
}
------------------------------------------------------------------------------------------------------------
DAO
------------------------------------------------------------------------------------------------------------
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.Mk.dao;
import com.Mk.entity.Customer;
import java.util.List;
public interface customerDao {
public void insertCustomer(Customer cust);
public List<Customer> viewCustomer();
public void editCustomer(Customer cust);
public List<Customer> removeCustomer(Customer cust);
}
------------------------------------------------------------------------------------------------------------
DAO impl
------------------------------------------------------------------------------------------------------------
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.Mk.daoImpl;
import com.Mk.dao.customerDao;
import com.Mk.entity.Customer;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class customerDaoImpl implements customerDao {
@Override
public void insertCustomer(Customer cust) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("SampleCrudJSFPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
try {
em.persist(cust);
em.getTransaction().commit();
}
catch (Exception e) {
e.printStackTrace();
em.getTransaction().rollback();
} finally {
em.close();
}
}
@Override
public List<Customer> viewCustomer() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("SampleCrudJSFPU");
EntityManager em = emf.createEntityManager();
List<Customer> allCustomer=null;
try {
em.getTransaction().begin();
allCustomer = em.createNamedQuery("Customer.findAll").getResultList();
em.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
em.getTransaction().rollback();
} finally {
em.close();
}
return allCustomer;
}
@Override
public void editCustomer(Customer cust) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("SampleCrudJSFPU");
EntityManager em = emf.createEntityManager();
try {
em.getTransaction().begin();
em.merge(cust);
em.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
em.getTransaction().rollback();
} finally {
em.close();
}
}
@Override
public List<Customer> removeCustomer(Customer cust) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("SampleCrudJSFPU");
EntityManager em = emf.createEntityManager();
List<Customer> allCustomer=null;
try {
em.getTransaction().begin();
em.remove(em.find(Customer.class, cust.getCustomerid()));
em.flush();
em.getTransaction().commit();
}
catch (Exception e) {
e.printStackTrace();
em.clear();
em.close();
}
return allCustomer;
}
}
------------------------------------------------------------------------------------------------------------
entity
------------------------------------------------------------------------------------------------------------
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.Mk.entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author manoj
*/
@Entity
@Table(name = "customer")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Customer.findAll", query = "SELECT c FROM Customer c"),
@NamedQuery(name = "Customer.findByCustomerid", query = "SELECT c FROM Customer c WHERE c.customerid = :customerid"),
@NamedQuery(name = "Customer.findByCustomerEmail", query = "SELECT c FROM Customer c WHERE c.customerEmail = :customerEmail"),
@NamedQuery(name = "Customer.findByCustomerName", query = "SELECT c FROM Customer c WHERE c.customerName = :customerName"),
@NamedQuery(name = "Customer.findByCustomerPhoneNo", query = "SELECT c FROM Customer c WHERE c.customerPhoneNo = :customerPhoneNo"),
@NamedQuery(name = "Customer.findByCustomerAddress", query = "SELECT c FROM Customer c WHERE c.customerAddress = :customerAddress"),
@NamedQuery(name = "Customer.findByCustomerCity", query = "SELECT c FROM Customer c WHERE c.customerCity = :customerCity"),
@NamedQuery(name = "Customer.findByCustomerPincode", query = "SELECT c FROM Customer c WHERE c.customerPincode = :customerPincode"),
@NamedQuery(name = "Customer.findByCustomerState", query = "SELECT c FROM Customer c WHERE c.customerState = :customerState"),
@NamedQuery(name = "Customer.findByCustomerCountry", query = "SELECT c FROM Customer c WHERE c.customerCountry = :customerCountry"),
@NamedQuery(name = "Customer.findByCustomerWebsite", query = "SELECT c FROM Customer c WHERE c.customerWebsite = :customerWebsite"),
@NamedQuery(name = "Customer.findByCustomerComments", query = "SELECT c FROM Customer c WHERE c.customerComments = :customerComments")})
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "Customer_id")
private Integer customerid;
@Column(name = "customerEmail")
private String customerEmail;
@Column(name = "customerName")
private String customerName;
@Column(name = "customerPhoneNo")
private String customerPhoneNo;
@Column(name = "customerAddress")
private String customerAddress;
@Column(name = "customerCity")
private String customerCity;
@Column(name = "customerPincode")
private String customerPincode;
@Column(name = "customerState")
private String customerState;
@Column(name = "customerCountry")
private String customerCountry;
@Column(name = "customerWebsite")
private String customerWebsite;
@Column(name = "customerComments")
private String customerComments;
public Customer() {
}
public Customer(Integer customerid) {
this.customerid = customerid;
}
public Integer getCustomerid() {
return customerid;
}
public void setCustomerid(Integer customerid) {
this.customerid = customerid;
}
public String getCustomerEmail() {
return customerEmail;
}
public void setCustomerEmail(String customerEmail) {
this.customerEmail = customerEmail;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerPhoneNo() {
return customerPhoneNo;
}
public void setCustomerPhoneNo(String customerPhoneNo) {
this.customerPhoneNo = customerPhoneNo;
}
public String getCustomerAddress() {
return customerAddress;
}
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}
public String getCustomerCity() {
return customerCity;
}
public void setCustomerCity(String customerCity) {
this.customerCity = customerCity;
}
public String getCustomerPincode() {
return customerPincode;
}
public void setCustomerPincode(String customerPincode) {
this.customerPincode = customerPincode;
}
public String getCustomerState() {
return customerState;
}
public void setCustomerState(String customerState) {
this.customerState = customerState;
}
public String getCustomerCountry() {
return customerCountry;
}
public void setCustomerCountry(String customerCountry) {
this.customerCountry = customerCountry;
}
public String getCustomerWebsite() {
return customerWebsite;
}
public void setCustomerWebsite(String customerWebsite) {
this.customerWebsite = customerWebsite;
}
public String getCustomerComments() {
return customerComments;
}
public void setCustomerComments(String customerComments) {
this.customerComments = customerComments;
}
@Override
public int hashCode() {
int hash = 0;
hash += (customerid != null ? customerid.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Customer)) {
return false;
}
Customer other = (Customer) object;
if ((this.customerid == null && other.customerid != null) || (this.customerid != null && !this.customerid.equals(other.customerid))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.Mk.entity.Customer[ customerid=" + customerid + " ]";
}
}
Image comparison using MATLAB (edge detection)
Image comparison using MATLAB
(edge detection)
Here is an simple algorithm for image comparison based on edge detection algorithm.
oq=imread('1.jpg'));
odprz=imresize(oq,[300 300]);
imwrite(odprz,'oq1.jpg');
sw=imread('2.jpg'));
stprz=imresize(sw,[300 300]);
imwrite(stprz,'sw1.png');
pic1 = imread('oq1.jpg');
pic2 = imread('sw1.png');
[x,y,z] = size(pic1);
if(z==1)
;
else
pic1 = rgb2gray(pic1);
end
[x,y,z] = size(pic2);
if(z==1)
;
else
pic2 = rgb2gray(pic2);
end
%applying edge detection on first picture
%so that we obtain white and black points and edges of the objects present
%in the picture.
edge_det_pic1 = edge(pic1,'canny');
%%applying edge detection on second picture
%so that we obtain white and black points and edges of the objects present
%in the picture.
edge_det_pic2 = edge(pic2,'canny');
%definition of different variables to be used in the code below
%initialization of different variables used
matched_data = 0;
matched_data1 = 0;
white_points = 0;
black_points = 0;
x=0;
y=0;
l=0;
m=0;
%for loop used for detecting black and white points in the picture.
for a = 1:1:256
for b = 1:1:256
if(edge_det_pic1(a,b)==1)
white_points = white_points+1;
else
black_points = black_points+1;
end
end
end
%for loop comparing the white (edge points) in the two pictures
for i = 1:1:256
for j = 1:1:256
if(edge_det_pic1(i,j)==1)&(edge_det_pic2(i,j)==1)
matched_data = matched_data+1;
else
matched_data1 = matched_data1+1;
end
end
end
%calculating percentage matching.
total_data = white_points;
total_matched_percentage = (matched_data/total_data)*100;
om=min(odprz);
sm=min(stprz);
if om==255
total_matched_percentage=0;
elseif sm==255
total_matched_percentage=0;
end
disp(total_matched_percentage)
disp('process completed')