Deleting a Record in OFBiz using Java

This is an example on how to delete a record in OFBiz using Java. I am assuming that the you have created the service of this method in you service.xml.

public static Map deletePerson(DispatchContext dctx, Map context) {
Map resultMap = ServiceUtil.returnSuccess();
String id = (String) context.get("id");

try {
GenericValue personGV = delegator.findOne("Person", UtilMisc.toMap("id", id), false);
if (personGV != null && !personGV.isEmpty()) {
personGV.remove();
}
} catch (GenericEntityException e) {
return ServiceUtil.returnError("Failed. " +e.getMessage());
}
return resultMap;
}

Updating a Record in OFBiz using Java

This is an example on how to update a record in OFBiz using Java as engine. I am assuming that the you have created the service of this method in you service.xml.

public static Map updatePerson(DispatchContext dctx, Map context) {
Map resultMap = ServiceUtil.returnSuccess();

//this is how you fetch the values from the request
String id = (String) context.get("id");
String firstName = (String) context.get("firstName");
String lastName = (String) context.get("lastName");
String gender = (String) context.get("gender");
String email = (String) context.get("email");

try {
GenericValue personGV = delegator.findOne("Person", UtilMisc.toMap("id", id), false);
if (personGV != null && !personGV.isEmpty()) {
personGV.put("firstName", firstName);
personGV.put("lastName", lastName);
personGV.put("gender", gender);
personGV.put("email", email);
personGV.store();
}
} catch (GenericEntityException e) {
return ServiceUtil.returnError("Failed. " +e.getMessage());
}
return resultMap;
}

Creating a New Record in OFBiz using Java

This is an example on how to create a record in OFBiz using Java as engine.

First, you have to create a service containing the attributes/values to be passed in your Java method. This service is invoked in your controller.xml.

<service name=“addPerson” engine=“java” location=“org.ofbiz.person.PersonServices” invoke=“addPerson” auth=“true”>
<description>Add Person Service</description>
<attribute name=“firstName” mode=“IN” type=“String” optional=“true”></attribute>
<attribute name=“lastName” mode=“IN” type=“String” optional=“true”></attribute>
<attribute name=“gender” mode=“IN” type=“String” optional=“true”></attribute>
<attribute name=“email” mode=“IN” type=“String” optional=“true”></attribute>
</service>

Once you have the service in your xml. Create the method with the same name as the value of the invoke attribute in the xml.

public static Map addPerson(DispatchContext dctx, Map context) {
Map resultMap = ServiceUtil.returnSuccess();

//this is how you fetch the values from the request
String firstName = (String) context.get("firstName");
String lastName = (String) context.get("lastName");
String gender = (String) context.get("gender");
String email = (String) context.get("email");

try {
//delegator.getNextSeqId(String EntityName) for auto-increment id
Map personValue = UtilMisc.toMap("id", delegator.getNextSeqId("Person"),
"firstName", firstName,
"lastName", lastName,
"gender", gender,
"email", email);

GenericValue personGV = delegator.makeValue("Person", personValue);
personGV.create();
} catch (GenericEntityException e) {
return ServiceUtil.returnError("Failed. " +e.getMessage());
}
return resultMap;
}

JVM Performance

In Java, making your code running is just a part of the development. Aside from that, you must also consider the performance of your system. Your system should response immediately even at unusually high or peak loads. Therefore, you must be aware of the things your code might bring because Memory leaks, heap fragmentation and others are actually caused by your own code.

Here's a PDF file I found on the net on how to reduce time and space consumption in your Java Virtual Machine. This will help you on how to optimize your code and making your system OK even though the demand is beyond the normal usage. Click here to download.

Factorial Code Snippet

Here's a Java code example for Factorial. In this example, we will compute for the Factorial of 6 which is denoted by variable n:

int n = 6; // where n is a non-negative integer
int count=1, product=1, factor=1;
do{
product = product * factor++;
count++;
}while(count <= n);

System.out.println(n + "! = " + product);

How check your RAM information in Linux

To know your RAM/memory information. First, you need to be root. Then just type the following:

# su
# dmidecode --type 17

JSF Session Timeout Handling

Here's my solution for session handling. When your session timed out, you will be redirected to the index page which is commonly the login page to login again.

package com.mypackage.web.session;

import javax.faces.FacesException;
import javax.faces.application.Application;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

public class SessionPhaseListener implements PhaseListener {

private static final String homepage = "index.jsp";

@Override
public void afterPhase(PhaseEvent event) {
//Do anything
}

@Override
public void beforePhase(PhaseEvent event) {
FacesContext context = event.getFacesContext();
ExternalContext ext = context.getExternalContext();
HttpSession session = (HttpSession) ext.getSession(false);
boolean newSession = (session == null) || (session.isNew());
boolean postback = !ext.getRequestParameterMap().isEmpty();
boolean timedout = postback && newSession;
if (timedout) {
Application app = context.getApplication();
ViewHandler viewHandler = app.getViewHandler();
UIViewRoot view = viewHandler.createView(context, "/" + homepage);
context.setViewRoot(view);
context.renderResponse();
try {
viewHandler.renderView(context, view);
context.responseComplete();
} catch (Throwable t) {
throw new FacesException("Session timed out", t);
}
}
}

@Override
public PhaseId getPhaseId() {
return PhaseId.RESTORE_VIEW;
}
}

Once you created the class above that implements the PhaseListener, add this to you faces-config.xml. Note that the package name depends on your own Java packaging.
<lifecycle>
<phase-listener>com.mypackage.web.session.SessionPhaseListener</phase-listener>
</lifecycle>

How to Handle ViewExpiredException in JSF

Here's the solution on how to handle the ViewExpiredException in JSF. This occurs when your session timed out or you tried to invalidate the session when you logged out. I've used this code to my 2 previous projects and it really worked fine.

First, you just need to add Spring 2.5 to your project libraries. Download Spring 2.5 here and just copy the code below.

import javax.faces.application.ViewExpiredException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;

public class SessionTimeoutFilter implements Filter {

private String homePage = "index.jsp";

@Override
public void init(FilterConfig filter) throws ServletException {
//Filter initialized
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException {
if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
if (isSessionCheckingNeeded(httpServletRequest)) {
if ((isInvalidSession(httpServletRequest))) {
String timeoutUrl = httpServletRequest.getContextPath() + "/faces/" + getHomePage();
httpServletResponse.sendRedirect(timeoutUrl);
return;
}
}
}

try {
chain.doFilter(request, response);
} catch (ViewExpiredException ve) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;

String timeoutUrl = httpServletRequest.getContextPath() + "/faces/" + getHomePage();
httpServletResponse.sendRedirect(timeoutUrl);

} catch (Exception e) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;

String timeoutUrl = httpServletRequest.getContextPath() + "/faces/" + getHomePage();

if (StringUtils.countOccurrencesOf(e.getMessage(), "could not be restored.") > 0) {
httpServletResponse.sendRedirect(timeoutUrl);
return;
}

httpServletResponse.sendRedirect(timeoutUrl);
return;
}
}

private boolean isInvalidSession(HttpServletRequest httpServletRequest) {

boolean sessionInValid = (httpServletRequest.getRequestedSessionId() != null)
&& !httpServletRequest.isRequestedSessionIdValid();
return sessionInValid;
}

private boolean isSessionCheckingNeeded(HttpServletRequest request) {

int counter = StringUtils.countOccurrencesOf(request.getRequestURL().toString(), getHomePage())
+ StringUtils.countOccurrencesOf(request.getRequestURL().toString(), getHomePage());

if (counter > 0) {
return false;
}
return true;
}

@Override
public void destroy() {
//Session destroyed
}

public String getHomePage() {
return homePage;
}

public void setHomePage(String homePage) {
this.homePage = homePage;
}
}