Null pointer exception using weblogic 10g bean injection jpa/ejb - java

I have a problem with my EJB / JPA project. I use netbeans, weblogic 10g and Java EE app.
My problem is, I create "Entity classes from database" and after that I create "session beans for entity classes" which are basically my facades.
Then I go over my war project and say "JSF pages for entity classses" Netbeans creates all the classes nicely.
At the beginning it says I have to have a persistence provider and for that aim I add the library "Hibernate JPA".
Here is my ArchJpaController:
package JPAControllerS;
import JPAControllerS.exceptions.NonexistentEntityException;
import JPAControllerS.exceptions.RollbackFailureException;
import entities.Arch;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import javax.transaction.UserTransaction;
public class ArchJpaController implements Serializable {
public ArchJpaController(UserTransaction utx, EntityManagerFactory emf) {
this.utx = utx;
this.emf = emf;
}
private UserTransaction utx = null;
private EntityManagerFactory emf;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Arch arch) throws RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
em.persist(arch);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Arch arch) throws NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
arch = em.merge(arch);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = arch.getId();
if (findArch(id) == null) {
throw new NonexistentEntityException("The arch with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
Arch arch;
try {
arch = em.getReference(Arch.class, id);
arch.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The arch with id " + id + " no longer exists.", enfe);
}
em.remove(arch);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public List<Arch> findArchEntities() {
return findArchEntities(true, -1, -1);
}
public List<Arch> findArchEntities(int maxResults, int firstResult) {
return findArchEntities(false, maxResults, firstResult);
}
private List<Arch> findArchEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
Query q = em.createQuery("select object(o) from Arch as o");
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Arch findArch(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(Arch.class, id);
} finally {
em.close();
}
}
public int getArchCount() {
EntityManager em = getEntityManager();
try {
Query q = em.createQuery("select count(o) from Arch as o");
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
And here is my ArchController:
package JSFClasses;
import entities.Arch;
import JSFClasses.util.JsfUtil;
import JSFClasses.util.PaginationHelper;
import JPAControllerS.ArchJpaController;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.transaction.UserTransaction;
#ManagedBean(name = "archController")
#SessionScoped
public class ArchController implements Serializable {
#Resource
private UserTransaction utx = null;
#PersistenceUnit(unitName = "IBB_Latest-warPU")
private EntityManagerFactory emf = null;
private Arch current;
private DataModel items = null;
private ArchJpaController jpaController = null;
private PaginationHelper pagination;
private int selectedItemIndex;
public ArchController() {
}
public Arch getSelected() {
if (current == null) {
current = new Arch();
selectedItemIndex = -1;
}
return current;
}
private ArchJpaController getJpaController() {
if (jpaController == null) {
jpaController = new ArchJpaController(utx, emf);
}
return jpaController;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return getJpaController().getArchCount();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(getJpaController().findArchEntities(getPageSize(), getPageFirstItem()));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (Arch) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new Arch();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getJpaController().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ArchCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (Arch) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}
public String update() {
try {
getJpaController().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ArchUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (Arch) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
recreatePagination();
recreateModel();
return "List";
}
public String destroyAndView() {
performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}
private void performDestroy() {
try {
getJpaController().destroy(current.getId());
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ArchDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getJpaController().getArchCount();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getJpaController().findArchEntities(1, selectedItemIndex).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
private void recreatePagination() {
pagination = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(getJpaController().findArchEntities(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(getJpaController().findArchEntities(), true);
}
#FacesConverter(forClass = Arch.class)
public static class ArchControllerConverter implements Converter {
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
ArchController controller = (ArchController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "archController");
return controller.getJpaController().findArch(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Arch) {
Arch o = (Arch) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Arch.class.getName());
}
}
}
}
Finally my exception:
java.lang.NullPointerException
at JPAControllerS.ArchJpaController.getEntityManager(ArchJpaController.java:43)
at JPAControllerS.ArchJpaController.findArchEntities(ArchJpaController.java:132)
at JPAControllerS.ArchJpaController.findArchEntities(ArchJpaController.java:128)
at JSFClasses.ArchController$1.createPageDataModel(ArchController.java:66)
at JSFClasses.ArchController.getItems(ArchController.java:166)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at javax.el.BeanELResolver.getValue(BeanELResolver.java:261)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at com.sun.el.parser.AstValue.getValue(AstValue.java:118)
at com.sun.el.parser.AstEqual.getValue(AstEqual.java:41)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:192)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at javax.faces.component.UIComponentBase.isRendered(UIComponentBase.java:413)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1750)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1756)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:401)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:410)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:292)
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:27)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:43)
at weblogic.servlet.internal.RequestEventsFilter.doFilter(RequestEventsFilter.java:27)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:43)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3496)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(Unknown Source)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2180)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2086)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1406)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)
If someone could help me on this issue I would be greatly appreciated.

first: What version of JPA are you using? 1.0 or 2.0? If you use 2.0, weblogic by default doesn't support it.
But you can enable making following changes:
locate the file commEnv.cmd(or sh for linux). The file is in WEBLOGIC_HOME/common/bin. Example for windows: C:\Oracle\Middleware\wlserver_10.3\common\bin
Add the following lines to the file
#rem JAR AGREGADOS PARA EL SOPORTE DE JPA2.0 EN WLS
set PRE_CLASSPATH=%MW_HOME%/modules/javax.persistence_1.0.0.0_2-0-0.jar;%MW_HOME%/modules/com.oracle.jpa2support_1.0.0.0_2-0.jar
restart de weblogic server
For inject the persitent unit you can use
#PersistenceContext(unitName = "PersistenceUnitName")
private EntityManager em;
On your facade or dao clasess
You don't need an EntityManagerFactory injection.
I hope this help you.
Sorry for my english... It`s really bad .. :-(

Related

How to use an object that got return in another class

I have this class, that returns an object, if the email, password and category (enum) are correct:
public class LoginManager {
private static LoginManager instance = new LoginManager();
private LoginManager() {
super();
}
public static LoginManager getInstance() {
return instance;
}
public ClientFacade login(String email, String password, ClientType clientType) throws SQLException {
if (clientType == ClientType.Administrator) {
AdminFacade adminFacade = new AdminFacade();
if (adminFacade.login(email, password) == true) {
return adminFacade;
} else {
return null;
}
} else if (clientType == ClientType.Company) {
CompanyFacade companyFacade = new CompanyFacade();
if (companyFacade.login(email, password) == true) {
return companyFacade;
} else {
return null;
}
} else if (clientType == ClientType.Customer) {
CustomerFacade customerFacade = new CustomerFacade();
if (customerFacade.login(email, password) == true) {
return customerFacade;
} else {
return null;
}
} else {
return null;
}
}
}
How do I use that object in another class?
This is the other class, that is supposed to use the object that return:
public class Test {
CouponsDBDAO coupDBD = new CouponsDBDAO();
CouponExpirationDailyJob dailyJob =
new CouponExpirationDailyJob(coupDBD, false);
LoginManager Log = LoginManager.getInstance();
public void testAll() {
try {
Log.login("admin#admin.com", "admin", ClientType.Administrator); {
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
How do I use now the adminFacade for example?
try
LoginManager Log = new LoginManager();
public void testAll() {
try {
ClientFacade facade = Log.login("admin#admin.com", "admin", ClientType.Administrator);
facade.DoSomethingUseful();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}

Xpages: send html email via java using backend document

I found this great Java Bean that allows you to send an html email including attachments via a managed java bean. It works as described when I use it directly form an Xpage.
However, I would like to use this in the backend in a scheduled agent. The problem I have run into is when I try to pass a document to the java bean. The bean is expecting (I think) an XSP document, which I don't have when in the back end, so it throws an error.
I thought I would just send the UNID of the document that I want and then change it so it would work with this bean, however, when I try to set the UNID I get an error:
Unknown member 'setUNID' in Java class 'com.scoular.utls.Email'
I am confused. Seems like this has something to do with a wrapped document, but don't understand.
Here is the faces-config:
<faces-config>
<managed-bean>
<managed-bean-name>Email</managed-bean-name>
<managed-bean-class>com.scoular.utls.Email</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>debugMode</property-name>
<value>true</value>
</managed-property>
</managed-bean>
</faces-config>
Here is a button I am using to test calling the method:
//Need to get email document
var emlView = database.getView("xpViewEmailsAll");
var emlDoc = emlView.getFirstDocument();
if (emlDoc != null) {
//try{
var subject = ""
var senderEmail = supEml
var senderName = supNme
Email.setSendTo("John");
Email.setSubject("subject");
Email.setSenderEmail("John#gmal.com");
Email.setUNID = emlDoc.getUniversalID();
Email.setSenderName("Sender");
//Email.setBackEndDocument(emlDoc);
Email.setFieldName("Body");
Email.send();
//}catch(e){
//print(e.getMessage());
//}
}
And here is the bean:
package com.scoular.utls;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.context.FacesContext;
import lotus.domino.Database;
import lotus.domino.Document;
import lotus.domino.EmbeddedObject;
import lotus.domino.MIMEEntity;
import lotus.domino.MIMEHeader;
import lotus.domino.NotesException;
import lotus.domino.Session;
import lotus.domino.Stream;
import com.ibm.commons.util.NotImplementedException;
import com.ibm.domino.xsp.module.nsf.NotesContext;
import com.ibm.xsp.model.FileRowData;
import com.ibm.xsp.model.domino.wrapped.DominoDocument;
import com.ibm.xsp.model.domino.wrapped.DominoRichTextItem;
import com.ibm.xsp.model.domino.wrapped.DominoDocument.AttachmentValueHolder;
import com.ibm.xsp.persistence.PersistedContent;
public class Email {
private ArrayList<String> sendTo;
private ArrayList<String> ccList;
private ArrayList<String> bccList;
private String senderEmail;
private String senderName;
private String subject;
private DominoDocument document;
private String fieldName;
private String bannerHTML;
private String footerHTML;
private String unid;
private boolean debugMode = false;
private static final Pattern imgRegExp = Pattern.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>");
// -------------------------------------------------------------------------
public Email() {
this.subject = "";
this.sendTo = new ArrayList<String>();
this.ccList = new ArrayList<String>();
this.bccList = new ArrayList<String>();
}
// -------------------------------------------------------------------------
public String getSendTo() {
if (this.isDebugMode()) {
System.out.println("getSendTo() : " + this.sendTo.toString());
}
return this.sendTo.toString().replace("[", "").replace("]", "");
}
public void setSendTo(final String sendTo) {
this.sendTo.add(sendTo);
}
// -------------------------------------------------------------------------
public String getCcList() {
if (this.isDebugMode()) {
System.out.println("getCcList() : " + this.ccList.toString());
}
return this.ccList.toString().replace("[", "").replace("]", "");
}
public void setCcList(final String ccList) {
this.ccList.add(ccList);
}
// -------------------------------------------------------------------------
public String getBccList() {
if (this.isDebugMode()) {
System.out.println("getBccList() : " + this.bccList.toString());
}
return this.bccList.toString().replace("[", "").replace("]", "");
}
public void setBccList(final String bccList) {
this.bccList.add(bccList);
}
// -------------------------------------------------------------------------
public String getSenderEmail() {
return this.senderEmail;
}
public void setSenderEmail(final String senderEmail) {
this.senderEmail = senderEmail;
}
// -------------------------------------------------------------------------
public String getSenderName() {
return this.senderName;
}
public void setSenderName(final String senderName) {
this.senderName = senderName;
}
// -------------------------------------------------------------------------
public String getSubject() {
return this.subject;
}
public void setSubject(final String subject) {
this.subject = subject;
}
// -------------------------------------------------------------------------
public boolean isDebugMode() {
return this.debugMode;
}
public void setDebugMode(final boolean debugMode) {
this.debugMode = debugMode;
}
// -------------------------------------------------------------------------
private Session getCurrentSession() {
NotesContext nc = NotesContext.getCurrentUnchecked();
return (null != nc) ? nc.getCurrentSession() : null;
}
// -------------------------------------------------------------------------
private Database getCurrentDatabase() {
NotesContext nc = NotesContext.getCurrentUnchecked();
return (null != nc) ? nc.getCurrentDatabase() : null;
}
// -------------------------------------------------------------------------
public void send() throws NotesException, IOException, Exception {
Session session = getCurrentSession();
Database database = getCurrentDatabase();
if (null != session && null != database && null != this.sendTo && null != this.subject
&& null != this.senderEmail) {
try {
if (this.isDebugMode()) {
System.out.println("Started send()");
}
session.setConvertMime(false);
Document emailDocument = database.createDocument();
MIMEEntity emailRoot = emailDocument.createMIMEEntity("Body");
if (null != emailRoot) {
MIMEHeader emailHeader = emailRoot.createHeader("Reply-To");
emailHeader.setHeaderVal(this.getSenderEmail());
emailHeader = emailRoot.createHeader("Return-Path");
emailHeader.setHeaderVal(this.getSenderEmail());
final String fromSender = (null == this.getSenderName()) ? this.getSenderEmail() : "\""
+ this.getSenderName() + "\" <" + this.getSenderEmail() + ">";
emailHeader = emailRoot.createHeader("From");
emailHeader.setHeaderVal(fromSender);
emailHeader = emailRoot.createHeader("Sender");
emailHeader.setHeaderVal(fromSender);
emailHeader = emailRoot.createHeader("To");
emailHeader.setHeaderVal(this.getSendTo());
if (!this.ccList.isEmpty()) {
emailHeader = emailRoot.createHeader("CC");
emailHeader.setHeaderVal(this.getCcList());
}
if (!this.bccList.isEmpty()) {
emailHeader = emailRoot.createHeader("BCC");
emailHeader.setHeaderVal(this.getBccList());
}
emailHeader = emailRoot.createHeader("Subject");
emailHeader.setHeaderVal(this.getSubject());
MIMEEntity emailRootChild = emailRoot.createChildEntity();
if (null != emailRootChild) {
final String boundary = System.currentTimeMillis() + "-" + this.document.getDocumentId();
emailHeader = emailRootChild.createHeader("Content-Type");
emailHeader.setHeaderVal("multipart/alternative; boundary=\"" + boundary + "\"");
MIMEEntity emailChild = emailRootChild.createChildEntity();
if (null != emailChild) {
final String contentAsText = this.document.getRichTextItem(this.fieldName)
.getContentAsText();
Stream stream = session.createStream();
stream.writeText(contentAsText);
emailChild.setContentFromText(stream, "text/plain; charset=\"UTF-8\"", MIMEEntity.ENC_NONE);
stream.close();
emailChild = emailRootChild.createChildEntity();
stream = session.createStream();
stream.writeText(this.getHTML());
emailChild.setContentFromText(stream, "text/html; charset=\"UTF-8\"", MIMEEntity.ENC_NONE);
stream.close();
stream.recycle();
stream = null;
}
// add embedded images....
final List<FileRowData> embeddedImages = this.getEmbeddedImagesList();
if (null != embeddedImages && !embeddedImages.isEmpty()) {
if (this.isDebugMode()) {
System.out.println("Adding Embedded Images...");
}
for (FileRowData embeddedImage : embeddedImages) {
emailRootChild = emailRoot.createChildEntity();
if (null != emailRootChild && embeddedImage instanceof AttachmentValueHolder) {
InputStream is = null;
try {
String persistentName = ((AttachmentValueHolder) embeddedImage)
.getPersistentName();
String cid = ((AttachmentValueHolder) embeddedImage).getCID();
emailHeader = emailRootChild.createHeader("Content-Disposition");
emailHeader.setHeaderVal("inline; filename=\"" + persistentName + "\"");
emailHeader = emailRootChild.createHeader("Content-ID");
emailHeader.setHeaderVal("<" + cid + ">");
is = this.getEmbeddedImageStream(persistentName);
Stream stream = session.createStream();
stream.setContents(is);
emailRootChild.setContentFromBytes(stream, embeddedImage.getType(),
MIMEEntity.ENC_IDENTITY_BINARY);
if (this.isDebugMode()) {
System.out.println("Added Embedded Image : " + persistentName);
}
} catch (IOException e) {
if (this.isDebugMode()) {
System.out.println("Adding Embedded Image failed : " + e.getMessage());
}
throw e;
} finally {
if (null != is) {
is.close();
is = null;
}
}
}
}
if (this.isDebugMode()) {
System.out.println("Completed Adding Embedded Images");
}
}
// add attachments....
final List<FileRowData> attachments = this.getDocument().getAttachmentList(this.getFieldName());
if (null != attachments && !attachments.isEmpty()) {
if (this.isDebugMode()) {
System.out.println("Adding Attachments...");
}
for (FileRowData attachment : attachments) {
emailRootChild = emailRoot.createChildEntity();
if (null != emailRootChild && attachment instanceof AttachmentValueHolder) {
InputStream is = null;
try {
String persistentName = ((AttachmentValueHolder) attachment)
.getPersistentName();
String cid = ((AttachmentValueHolder) attachment).getCID();
EmbeddedObject eo = this.getDocument().getDocument().getAttachment(
persistentName);
if (null != eo) {
emailHeader = emailRootChild.createHeader("Content-Disposition");
emailHeader.setHeaderVal("attachment; filename=\"" + persistentName + "\"");
emailHeader = emailRootChild.createHeader("Content-ID");
emailHeader.setHeaderVal("<" + cid + ">");
is = eo.getInputStream();
Stream stream = session.createStream();
stream.setContents(is);
emailRootChild.setContentFromBytes(stream, attachment.getType(),
MIMEEntity.ENC_IDENTITY_BINARY);
if (this.isDebugMode()) {
System.out.println("Added Attachment : " + persistentName);
}
}
} catch (Exception e) {
if (this.isDebugMode()) {
System.out.println("Adding Attachment failed : " + e.getMessage());
}
throw e;
} finally {
if (null != is) {
is.close();
is = null;
}
}
}
}
if (this.isDebugMode()) {
System.out.println("Completed Adding Attachments");
}
}
}
}
emailDocument.send();
session.setConvertMime(true);
if (this.isDebugMode()) {
System.out.println("Completed send()");
}
} catch (NotesException e) {
if (this.isDebugMode()) {
System.out.println("Failed send() with NotesException" + e.getMessage());
}
throw e;
} catch (IOException e) {
if (this.isDebugMode()) {
System.out.println("Failed send() with IOException" + e.getMessage());
}
throw e;
} catch (Exception e) {
if (this.isDebugMode()) {
System.out.println("Failed send() with Exception" + e.getMessage());
}
throw e;
}
}
}
// -------------------------------------------------------------------------
public DominoDocument getDocument() {
return this.document;
}
public void setDocument(final DominoDocument document) {
this.document = document;
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
public String getFieldName() {
return this.fieldName;
}
public void setFieldName(final String fieldName) {
this.fieldName = fieldName;
}
// -------------------------------------------------------------------------
public List<FileRowData> getEmbeddedImagesList() throws NotesException {
if (null != document && null != fieldName) {
return document.getEmbeddedImagesList(fieldName);
}
return null;
}
// -------------------------------------------------------------------------
private InputStream getEmbeddedImageStream(final String fileName) throws NotesException, IOException {
if (null != document && null != fieldName && null != fileName) {
final DominoRichTextItem drti = document.getRichTextItem(fieldName);
if (null != drti) {
final PersistedContent pc = drti.getPersistedContent(FacesContext.getCurrentInstance(), fieldName,
fileName);
if (null != pc) {
return pc.getInputStream();
}
}
}
return null;
}
// -------------------------------------------------------------------------
public String getHTML() {
StringBuffer html = new StringBuffer();
html.append(getBannerHTML());
html.append(getBodyHTML());
html.append(getFooterHTML());
return html.toString();
}
// -------------------------------------------------------------------------
public String getBannerHTML() {
return this.bannerHTML;
}
public void setBannerHTML(final String bannerHTML) {
this.bannerHTML = bannerHTML;
}
// -------------------------------------------------------------------------
public String getBodyHTML() {
if (null != document && null != fieldName) {
if (this.isDebugMode()) {
System.out.println("Started getBodyHTML()");
}
final DominoRichTextItem drti = document.getRichTextItem(fieldName);
if (null != drti) {
try {
String html = drti.getHTML();
if (null != html) {
final List<FileRowData> fileRowDataList = document.getEmbeddedImagesList(fieldName);
if (null != fileRowDataList) {
final Matcher matcher = imgRegExp.matcher(html);
while (matcher.find()) {
String src = matcher.group();
final String srcToken = "src=\"";
final int x = src.indexOf(srcToken);
final int y = src.indexOf("\"", x + srcToken.length());
final String srcText = src.substring(x + srcToken.length(), y);
for (FileRowData fileRowData : fileRowDataList) {
final String srcImage = fileRowData.getHref();
final String cidImage = ((AttachmentValueHolder) fileRowData).getCID();
if (srcText.endsWith(srcImage)) {
final String newSrc = src.replace(srcText, "cid:" + cidImage);
html = html.replace(src, newSrc);
if (this.isDebugMode()) {
System.out.println("CID referenced image: " + srcText + " with CID:"
+ cidImage);
}
}
}
}
}
}
if (this.isDebugMode()) {
System.out.println("Completed getBodyHTML() : " + html);
}
return html;
} catch (Exception e) {
if (this.isDebugMode()) {
System.out.println("Failed getBodyHTML() : " + e.getMessage());
}
}
}
}
return null;
}
public void setBodyHTML(final String bodyHTML) throws NotImplementedException {
if (this.isDebugMode()) {
System.out.println("Method setBodyHTML(string) is not permitted");
}
throw new NotImplementedException();
}
// -------------------------------------------------------------------------
public String getFooterHTML() {
return this.footerHTML;
}
public void setFooterHTML(final String footerHTML) {
this.footerHTML = footerHTML;
}
public String getUnid() {
return unid;
}
public void setUnid(final String unid) {
this.unid = unid;
}
// -------------------------------------------------------------------------
} // end EmailBean
The Email.setUNID statement is wrong. Try:
Email.setUnid(emlDoc.getUniversalID());

multiple update with jpa

I need to upgrade a field of several records in bd. How to do this with JPA?. I tried the following but not working:
#Override
public String estadoPedido(List<DetallePedido> lista) {
int cod;
String mensage = null;
for (DetallePedido ped : lista) {
cod = ped.getIdDetalle();
EntityManager em = emf.createEntityManager();
DetallePedido detPed = new DetallePedido();
try {
em.getTransaction().begin();
detPed = em.find(DetallePedido.class, cod);
detPed.setPedEstado("EN PLAN");
em.merge(detPed);
em.getTransaction().commit();
mensage = "detalle seleccionado";
} catch (Exception e) {
mensage = "Error:/p" + e.getMessage();
} finally{
em.close();
}
}
return mensage;
}
Try the following:
#Override
public String estadoPedido(List<DetallePedido> lista) {
EntityManager em = emf.createEntityManager();
//em.getTransaction().begin(); //Consider using Container managed transactions ,
// if you do remove this line and the line above, and have
//entity manager injected !
String mensage = null;
try {
for (DetallePedido ped : lista) {
detPed.setPedEstado("EN PLAN");
em.merge(detPed);
}
mensage = "detalle seleccionado";
em.getTransaction().commit; //consider removing this line and use Container managed transactions!
} catch (Exception e) {
mensage = "Error:/p" + e.getMessage();
} finally{
em.close();
}
return mensage;
}

JDBC Multi-Row INSERT peformance is horrible

Why would I be getting linear performance on increasing batch sizes for this Spring JDBC implementation. Is there some further tuning I might do (apart from an explain, indice review, and database settings tuning)? I should mention I am running this code against a MySQL 5.6 instance hosted on an AWS db.r3.2xlarge class RDS server.
#Repository
public class JdbcRatePlanLevelCostPriceLogRepository implements Insertable<RatePlanLevelCostPriceLog> {
#Autowired
JdbcTemplate jdbcTemplate;
private static final String INSERT_STATEMENT = InsertStatementBuilder.build();
#Override
public RatePlanLevelCostPriceLog insert(RatePlanLevelCostPriceLog entity) {
jdbcTemplate.execute(INSERT_STATEMENT, new SingleCallbackImpl(entity));
return entity;
}
#Override
public List<RatePlanLevelCostPriceLog> insert(List<RatePlanLevelCostPriceLog> entities) {
jdbcTemplate.batchUpdate(INSERT_STATEMENT, new BatchPreparedStatementSetter() {
#Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
RatePlanLevelCostPriceLog entity = entities.get(i);
PreparedStatementTranslator.translate(ps, entity);
}
#Override
public int getBatchSize() {
return entities.size();
}
});
return entities;
}
private static class InsertStatementBuilder {
static String build() {
StringBuffer colsBuffer = new StringBuffer();
StringBuffer valuesBuffer = new StringBuffer();
colsBuffer.append("INSERT INTO rate_plan_level_cost_price_log(");
valuesBuffer.append("VALUES (");
// handle the #NotNull fields
colsBuffer.append("hotel_id");
colsBuffer.append(",rate_plan_id");
colsBuffer.append(",stay_date");
colsBuffer.append(",rate_plan_level");
colsBuffer.append(",person_count");
colsBuffer.append(",length_of_stay_in_days");
colsBuffer.append(",rpcp_log_seq_num");
colsBuffer.append(",log_action_type_id");
colsBuffer.append(",active_status_type_id");
colsBuffer.append(",supplier_update_date");
colsBuffer.append(",create_date");
colsBuffer.append(",supplier_update_tpid");
colsBuffer.append(",supplier_update_tuid");
colsBuffer.append(",supplier_log_seq_num");
// handle the optional fields
colsBuffer.append(",cost_amount");
colsBuffer.append(",cost_code");
colsBuffer.append(",price_amount");
colsBuffer.append(",change_request_id");
colsBuffer.append(",change_request_id_old");
colsBuffer.append(",lar_amount");
colsBuffer.append(",lar_margin_amount");
colsBuffer.append(",lar_taxes_and_fees_amount");
valuesBuffer.append("?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?");
colsBuffer.append(")");
valuesBuffer.append(")");
return String.join(" ", colsBuffer.toString(), valuesBuffer.toString());
}
}
private static class PreparedStatementTranslator {
static void translate(PreparedStatement ps, RatePlanLevelCostPriceLog entity) throws SQLException {
int i = 0;
// handle the #NotNull fields
ps.setInt(++i, entity.getHotelId());
ps.setInt(++i, entity.getRatePlanId());
ps.setTimestamp(++i, new Timestamp(entity.getStayDate().getTime()));
ps.setInt(++i, entity.getRatePlanLevel());
ps.setInt(++i, entity.getPersonCount());
ps.setInt(++i, entity.getLengthOfStayInDays());
ps.setInt(++i, entity.getRpcpLogSeqNum());
ps.setInt(++i, entity.getLogActionTypeId());
ps.setInt(++i, entity.getActiveStatusTypeId());
ps.setTimestamp(++i, new Timestamp(entity.getSupplierUpdateDate().getTime()));
ps.setTimestamp(++i, new Timestamp(entity.getCreateDate().getTime()));
ps.setInt(++i, entity.getSupplierUpdateTpid());
ps.setInt(++i, entity.getSupplierUpdateTuid());
ps.setInt(++i, entity.getSupplierLogSeqNum());
// handle the optional fields
if (entity.getCostAmount() != null) {
ps.setDouble(++i, entity.getCostAmount());
} else {
ps.setNull(++i, Types.DOUBLE);
}
if (entity.getCostCode() != null) {
ps.setString(++i, entity.getCostCode());
} else {
ps.setNull(++i, Types.VARCHAR);
}
if (entity.getPriceAmount() != null) {
ps.setDouble(++i, entity.getPriceAmount());
} else {
ps.setNull(++i, Types.DOUBLE);
}
if (entity.getChangeRequestId() != null) {
ps.setInt(++i, entity.getChangeRequestId());
} else {
ps.setNull(++i, Types.INTEGER);
}
if (entity.getChangeRequestIdOld() != null) {
ps.setInt(++i, entity.getChangeRequestIdOld());
} else {
ps.setNull(++i, Types.INTEGER);
}
if (entity.getLarAmount() != null) {
ps.setDouble(++i, entity.getLarAmount());
} else {
ps.setNull(++i, Types.DOUBLE);
}
if (entity.getLarMarginAmount() != null) {
ps.setDouble(++i, entity.getLarMarginAmount());
} else {
ps.setNull(++i, Types.DOUBLE);
}
if (entity.getLarTaxesAndFeesAmount() != null) {
ps.setDouble(++i, entity.getLarTaxesAndFeesAmount());
} else {
ps.setNull(++i, Types.DOUBLE);
}
}
}
private class SingleCallbackImpl implements PreparedStatementCallback<Boolean> {
private final RatePlanLevelCostPriceLog entity;
SingleCallbackImpl(RatePlanLevelCostPriceLog entity) {
this.entity = entity;
}
#Override
public Boolean doInPreparedStatement(PreparedStatement ps) throws SQLException,
DataAccessException {
PreparedStatementTranslator.translate(ps, entity);
return ps.execute();
}
}
}
It takes ~250 ms to execute a single record insert and then N * 250 ms for batches of N.

How to call Java object from CDI bean

I have a CDI bean with Java object which I use to display profile data from Database:
Parent Bean
#Named("DCProfileTabGeneralController")
#ViewScoped
public class DCProfileTabGeneral implements Serializable
{
public DCObj dc;
public class DCObj
{
private int componentStatsId; // COMPONENTSTATSID NUMBER(38,0)
........
// Default Constructor
public DCObj(){};
public DCObj(int componentStatsId....)
{
this.componentStatsId = componentStatsId;
.......
}
public int getComponentStatsId()
{
return componentStatsId;
}
public void setComponentStatsId(int componentStatsId)
{
this.componentStatsId = componentStatsId;
}
....
}
// Getters ------------------------------------------------------------------------------------
public DCObj getdcData()
{
return dc;
}
#PostConstruct
public void initData() throws SQLException
{
initDBData();
}
// Generate data Object from Oracle
public void initDBData() throws SQLException
{
dc = new DCObj(result.getInt("COMPONENTSTATSID"),
.........
}
}
Validator
#Named("ValidatorDatacenterController")
#ViewScoped
public class ValidatorDatacenter implements Validator, Serializable
{
public ValidatorDatacenter()
{
}
#Inject
private DCProfileTabGeneral profileTabGeneral;
// Validate Datacenter Name
public void validateDatacenterName(FacesContext context, UIComponent component, Object value) throws ValidatorException, SQLException
{
int componentStatsId = -1;
if (profileTabGeneral != null)
{
DCObj dcData = profileTabGeneral.dc;
if (dcData != null)
{
componentStatsId = dcData.getComponentStatsId();
}
}
if (componentStatsId == -1)
{
return;
}
String l;
String s;
if (value != null && !(s = value.toString().trim()).isEmpty())
{
if (s.length() > 18)
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" Value is too long! (18 digits max)", null));
}
if (ds == null)
{
throw new SQLException("Can't get data source");
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs;
int resComponentStatsId = -1;
try
{
conn = ds.getConnection();
// if componentsstatsid <> edited componentstatsid in jsf -> throw validator exception
ps = conn.prepareStatement("SELECT componentstatsid from COMPONENTSTATS where NAME = ?");
ps.setString(1, s);
rs = ps.executeQuery();
while (rs.next())
{
resComponentStatsId = rs.getInt(1);
}
if (resComponentStatsId != -1 && resComponentStatsId != componentStatsId)
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" '" + s + "' is already in use!", null));
}
}
catch (SQLException x)
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" SQL error!", null));
}
finally
{
if (ps != null)
{
ps.close();
}
if (conn != null)
{
conn.close();
}
}
}
else
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" This field cannot be empty!", null));
}
}
}
I have a custom validator which checks the input values from the profile page into the Database. I tested to get the Java object from the parent page using #Inject and to pass the Ojject to the validator. It turns out that I get empty Java object every time when I use #Inject.
I also tested to get Int using CDI. It works but when I again tested to get the Java Object again I get empty Object.
Can you tell me what is the proper way to call a Java Object from CDI bean? Why I cannot get Java object from CDI bean?
If I recall correctly CDI injection will not work with a validator. Use advanced from Myfaces CODI as the JSF-module from deltaspike is not ready yet. https://cwiki.apache.org/EXTCDI/jsf-usage.html
Or go for deltaspike and use the BeanProvider to get your instance.
BeanProvider.getContextualReference(DCProfileTabGeneral .class, false);

Categories