Rotating BufferedImage to left or right

If you need to rotate an BufferedImage to left or right you can use the following code

BufferedImage originalImage = // some image that you have as file / stream.
BufferedImage rotatedImage = new BufferedImage(originalImage.getHeight(), originalImage.getWidth(), originalImage.getType());

for (int row = 0; row < originalImage.getWidth(); row++) {
     for (int column = 0; column < originalImage.getHeight(); column++) {
         if (rotateLeft) {
              rotatedImage.setRGB(column, originalImage.getWidth() - row - 1, originalImage.getRGB(row, column));
         } else {
              rotatedImage.setRGB(originalImage.getHeight() - column - 1, row, originalImage.getRGB(row, column));
         }
     }
}
Advertisements

Dealing with ViewExpiredException on Regular and Ajax Requests

This is a note to myself mainly ( this is based on Oleg’s post btw, I just tried to simplified a little from here

To deal with ViewExpiredException with regular and ajax requests, do the following:

in faces-config.xml, have the following:


    <factory>
        <exception-handler-factory>
            com.prime.DefaultExceptionHandlerFactory
        </exception-handler-factory>
    </factory>
	
      <lifecycle>
	 <phase-listener>
            com.prime.SecurityPhaseListener
        </phase-listener>
	</lifecycle>

in security.xml for Spring, we add a entry-point-ref as follows:

<http auto-config="false" access-denied-page="/accessDenied.xhtml"
		entry-point-ref="authenticationProcessingFilterEntryPoint">

where authenticationProcessingFilterEntryPoint is :

<beans:bean id="authenticationProcessingFilterEntryPoint"
		class="com.prime.AuthenticationProcessingFilterEntryPoint">
		<beans:property name="loginFormUrl" value="/login.xhtml" />
		<beans:property name="useForward" value="true" />
	</beans:bean>

ok, now our java codes;

the SecurityPhaseListener is defined as:

package com.prime;

import java.io.IOException;

import javax.faces.FacesException;
import javax.faces.FactoryFinder;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.faces.render.RenderKit;
import javax.faces.render.RenderKitFactory;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.primefaces.context.DefaultRequestContext;

public class SecurityPhaseListener implements PhaseListener {

	private static final long serialVersionUID = -101374487855763803L;

	public void afterPhase(PhaseEvent event) {
	}

	public void beforePhase(PhaseEvent event) {
		FacesContext fc = event.getFacesContext();
		String loginPage = (String) fc.getExternalContext().getRequestMap().get(AuthenticationProcessingFilterEntryPoint.ATTRIBUTE_LOGIN_PAGE);
		if (StringUtils.isNotBlank(loginPage)) {
			doRedirect(fc, loginPage);
		}
	}

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

	public void doRedirect(FacesContext fc, String redirectPage) throws FacesException {
		ExternalContext ec = fc.getExternalContext();

		try {
			if (ec.isResponseCommitted()) {
				return;
			}

			ec.redirect(ec.getRequestContextPath() + (redirectPage != null ? redirectPage : ""));

		} catch (IOException e) {
			throw new FacesException(e);
		}
	}
}

our AuthenticationProcessingFilterEntryPoint code is as follows:

package com.prime;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;

/**
 * Extended Spring AuthenticationProcessingFilterEntryPoint for playing together with JSF Ajax redirects.
 */
public class AuthenticationProcessingFilterEntryPoint extends LoginUrlAuthenticationEntryPoint
{
    public static final String ATTRIBUTE_LOGIN_PAGE = "com.myproject.login.page";


      @Override
    public void afterPropertiesSet() throws Exception {
        super.afterPropertiesSet();
    }
    
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

    	if(request.getParameter("javax.faces.partial.ajax") != null )
    		request.setAttribute(ATTRIBUTE_LOGIN_PAGE, getLoginFormUrl());
        super.commence(request, response, authException);
    }
}

ok finally, the DefaultExceptionHandlerFactory classes which are as follows:

package com.prime;

import java.util.Iterator;

import javax.faces.FacesException;
import javax.faces.application.ViewExpiredException;
import javax.faces.context.ExceptionHandler;
import javax.faces.context.ExceptionHandlerWrapper;
import javax.faces.context.FacesContext;
import javax.faces.event.ExceptionQueuedEvent;
import javax.faces.event.ExceptionQueuedEventContext;
import javax.servlet.http.HttpSession;

public class DefaultExceptionHandler extends ExceptionHandlerWrapper {

    private ExceptionHandler wrapped;

    public DefaultExceptionHandler(ExceptionHandler wrapped) {
        this.wrapped = wrapped;
    }

    @Override
    public ExceptionHandler getWrapped() {
        return this.wrapped;
    }

    @Override
    public void handle() throws FacesException {

        FacesContext facesContext = FacesContext.getCurrentInstance();
        Iterator<ExceptionQueuedEvent> eventIterator = getUnhandledExceptionQueuedEvents().iterator();

        ViewExpiredException viewExpiredException = getViewExpiredException(getUnhandledExceptionQueuedEvents());
        if (viewExpiredException != null) {
            String redirectUrl = invalidateSessionAndGetErrorPage(facesContext, viewExpiredException);
            redirectToTheErrorPage(facesContext, redirectUrl);
        } else if (eventIterator.hasNext()) {

            String redirectUrl = "/error.html";

            redirectToTheErrorPage(facesContext, redirectUrl);
        }
    }


    private String invalidateSessionAndGetErrorPage(FacesContext facesContext, ViewExpiredException throwable) {

        HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
        if (session != null) {
            session.invalidate();
        }

        return "/dashboard.xhtml";
    }

    private void redirectToTheErrorPage(FacesContext facesContext, String redirectUrl) {
        SecurityPhaseListener spl = new SecurityPhaseListener();
        spl.doRedirect(facesContext, redirectUrl);

    }

    private ViewExpiredException getViewExpiredException(Iterable<ExceptionQueuedEvent> unhandledExceptionQueuedEvents) {
        for (ExceptionQueuedEvent event : unhandledExceptionQueuedEvents) {
            ExceptionQueuedEventContext queuedEventContext = event.getContext();
            if (queuedEventContext.getException() instanceof ViewExpiredException) {
                return (ViewExpiredException) queuedEventContext.getException();
            }
        }
        return null;
    }

}

and our DefaultExceptionHandlerFactory is

package com.prime;

import javax.faces.context.ExceptionHandler;
import javax.faces.context.ExceptionHandlerFactory;

public class DefaultExceptionHandlerFactory extends ExceptionHandlerFactory {
	private ExceptionHandlerFactory parent;

	public DefaultExceptionHandlerFactory(ExceptionHandlerFactory parent) {
		this.parent = parent;
	}

	@Override
	public ExceptionHandler getExceptionHandler() {
		ExceptionHandler eh = parent.getExceptionHandler();
		eh = new DefaultExceptionHandler(eh);

		return eh;
	}
}

the codes in DefaultExceptionHandlerFactory can be changed to customize.

just a note myself.

Better ajax operations and callbacks in JSF with PrimeFaces

One of the nicest feature of PrimeFaces is you can add some parameters to your ajax calls ( callbacks ) and can decide on what to update while executing your actions on your managed beans.

Think of following common scenario, we want to create a new user object with a dialog and show it in a datatable when user clicks on save button and do all these stuff with Ajax. Let’s think you as a developer want to do this using a p:dialog as follows:

<p:dialog  widgetVar="userFormDialog" >

   <p:outputPanel id="editDialog">
      <h:panelGrid>
         <h:outputLabel for="userName" value="Username" />
         <p:inputText id="userName"  
                        value="#{userManagementBean.user.username}" />
					
         <h:outputLabel for="password" value="Password"/>
         <p:inputText autocomplete="false" id="password"
                       value="#{userManagementBean.user.password}"/>
									
      </h:panelGrid>
   </p:outputPanel>

   <p:commandButton value="Save!" 
                       actionListener="#{userManagementBean.save}"
                       process="editDialog" update="userTable messages" 
                       oncomplete="userFormDialog.hide();"/>
</p:dialog>
                  
<p:messages id="messages"/>

<p:outputPanel id="userTable">
      <p:dataTable value="#{userManagementBean.all}" var="user" >
	<p:column>
          <f:facet name="header">Username</f:facet>
          #{user.username}
	</p:column>
     </p:datatable>
</p:outputPanel>

so what this code does it, when user clicks on save, the dialog should be closed, a message should be shown for successful creating and the p:datatable which shows all the users should be updated.

what happens if user just clicks save button w/o entering any data? what happens if the userName that the user entered is already in the database and saving the new one fails? what happens if there is a pb somewhere? When something unusual occurs, the dialog should stay opened and a message should be shown to the user right? This is the situation where PrimeFaces useful RequestContext API becomes handy.

RequestContext API enables developers to do 2 simple things. 1st you can tell what you want to update in the xhtml based on conditions in actions that you define in your Managed Beans.To update a component from serverside, you can just write:

RequestContext.getCurrentInstance().
              addPartialUpdateTarget("my_component_id");

so when the Ajax request is finished, the component with the id ‘my_component_id’ will be also updated. 2nd you can send parameters to your xhtml so that you can use these values in your javascript code. To pass an object you can use the following code :

RequestContext.getCurrentInstance().addCallbackParam("user", user);

as you can pass objects here, you can access them in your javascript methods in the client side.

So let’s define the requirement more precisely and try to implement it. We want to open a dialog when we want to create a new user for the system, the username and password are required fields and when user does not enter any data to these fields and click save, the dialog should stay visible and messages shown inside the dialog. Also for performance wise, if there is a validation pb, we should not update the datatable but update messages only. if the save is successful, then messages and datatable component should be updated and user should be notified by a message and alert. So our xhtml code will be something like this :

<p:dialog  widgetVar="userFormDialog" >

   <p:outputPanel id="editDialog">
      <h:panelGrid>
         <h:outputLabel for="userName" value="Username" />
         <p:inputText id="userName" value="#{userManagementBean.user.username}"  
                               required="true"/>
          <p:message for="userName"/>
					
         <h:outputLabel for="password" value="Password"/>
         <p:inputText autocomplete="false" id="password" value="#{userManagementBean.user.password}"/>
         <p:message for="password"/>
							
      </h:panelGrid>
   </p:outputPanel>

   <p:commandButton value="Save!" actionListener="#{userManagementBean.save}" process="editDialog"
				oncomplete="handleSaveRequest(xhr, status, args)"/>
</p:dialog>

<h:outputScript target="head">
      function handleSaveRequest(xhr, status, args) {  
           if( args.notValid || args.validationFailed )  
              return;
           userFormDialog.hide();  
           alert('User with username ' +args.user.username+ ' is saved successfully');
   }  
</h:outputScript>
                  
<p:messages id="messages"/>

<p:outputPanel id="userTable">
	<p:dataTable value="#{userManagementBean.all}" var="user" >
		<p:column>
		 <f:facet name="header">#{lbl['username']}</f:facet>
					#{user.username}
		</p:column>
	</p:datatable>
</p:outputPanel>

as you can see here at line 18, we defined a new js method to handle the response from the server. In this method ( starting at line 22 ) we check whether there is a validation error ( args.validationFailed is default set to true by PrimeFaces API ) or we had an error and send a parameter ( args.valid is set to true on server side with backing bean ). We also notified the user with an alert box and tell the user that a new user object is saved successfully by writing the username in the message. RequestContext API allows you to pass objects to js side with serializing them as JSON.

our backing bean will be like this :

@ViewScoped
@ManagedBean
public class UserManagementBean{
	private User user = new User();
	private List<User> users;

	public void save() {
		try{
			// some service to save user
 			// userService.save(user);
			addMessage( "User is Saved!");
			RequestContext.getCurrentInstance().
					addCallbackParam("user", user);
 			RequestContext.getCurrentInstance().
					addPartialUpdateTarget("userTable");
		}catch (SomeException e) {
			RequestContext.getCurrentInstance().
					addCallbackParam("notValid", true);
			addErrorMessage("Problem Occured!");
		}
		RequestContext.getCurrentInstance().
					addPartialUpdateTarget("messages");
	}

	public List<User> getAll() {
		return users;
	}

        // getter setter
}

As you can see that RequestContext API enables developers to decide on what to update and send parameter in Ajax request easily. You can do easier testing with RequestContext API as you can test whether the parameters and partial update request are done when there is an exception occurs or save operation is successful.

Starting a new project with Agile v1

Hi,

we just started working on a new project with a client which is re-implementing the client’s current e-commerce page with Java which is currently written on asp. We will be using Agile Methodologies to implement the project with the help of . In our first meeting with the client, we first tried to get the user stories from the clientand tried to identify the roles. What we tried to do is, creating user stories and doing some estimations on them. This way we tried to estimate how long the project may take to implement and informed the client about this estimation.

What we will do next is meet with client again, prioritize the stories and do a release and iteration plan to start the project and start with iteration 0.

We will be using PrimeFaces 3.0 – JSF 2.0 – Spring 3.0 – Hibernate 3.6 and will be doing it Agile as time will be a important aspect side of the project.

I will be posting images/status of the project next days hopefully.