Feeds:
Posts
Comments

Hi,

today I will show you a nice solution to clear or refresh input fields. This solution does this with the Direct-2-Dom abilities of ICEfaces. I would not like to use the Render API of ICEfaces because there are some drawback I would not like to handle with. So this solution does not use any special Rendering API of ICEfaces and is very easy to integrate it into existing code without to much refactoring.

So lets beginn, here is the source code:

public static void cleanBackingBean(String beanName)
{
  try
  {
    ValueExpression binding = context.getApplication().getExpressionFactory().createValueExpression(elContext, "#{" + beanName + "}", Object.class);
    Object object = binding.getValue(elContext);
    object = Class.forName(object.getClass().getName()).newInstance();
    setBackingBean(object, beanName);

    clearSubmittedValues(beanName);
  }
  catch (Exception ex)
  {
    ex.printStackTrace();
  }
}

public static void clearSubmittedValues(String beanName)
{
  FacesContext context = FacesContext.getCurrentInstance();
  UIViewRoot viewRoot = context.getViewRoot();
  List<UIComponent> uiComponentList = viewRoot.getChildren();

  for (UIComponent uiComponent : uiComponentList)
  {
    clearSubmittedValues(uiComponent, beanName, context);
  }
}

private static void clearSubmittedValues(UIComponent component, String beanName, FacesContext context)
{
  if (component instanceof UIInput)
  {
    try
    {
      if (component.getValueExpression("value").getExpressionString().indexOf(beanName) > -1)
      {
         PassThruAttributeRenderer.renderAttributes(context, component, new String[0]);
      }
    }
    catch (NullPointerException ingnore)
    {
      // Nothing to log here. The NullPointerException just means that there is no ValueExpression found with name 'value'.
    }
  }

  List<UIComponent> childenList = component.getChildren();
  if (childenList.size() > 0)
  {
    Iterator<UIComponent> childIter = childenList.iterator();
    while (childIter.hasNext())
    {
      clearSubmittedValues((UIComponent)childIter.next(), beanName, context);
    }
  }
}

The “cleanBackingBean” method just takes the beanName (as defined in the faces xml). And creates a new instance (which means empty) of this bean and set it back to the application context.
The “clearSubmittedValues” method search for all input fields in the view that are associated with the given bean and set them to rerender in the response phase.

Thats all the magic. The “clearSubmittedValues” method can be optimised. The search for the solution took me some time, so I hope it will help others to move on faster.

The following code is a template for easy Enum mapping.

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;

public class EnumType<E extends Enum<E>> implements UserType {

 private static final int[] SQL_TYPES = {Types.VARCHAR};
 private Class<E> clazz = null;

 protected EnumType(Class<E> clazz) {
 this.clazz = clazz;
 }

 public int[] sqlTypes() {
 return SQL_TYPES;
 }

 public Class<E> returnedClass() {
 return clazz;
 }

 public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) throws HibernateException, SQLException {
 String name = resultSet.getString(names[0]);
 E result = null;
 if (!resultSet.wasNull()) {
 result = Enum.valueOf(clazz, name);
 }
 return result;
 }

 public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index) throws HibernateException, SQLException {
 if (null == value) {
 preparedStatement.setNull(index, Types.VARCHAR);
 }
 else {
 preparedStatement.setString(index, ((Enum)value).name());
 }
 }

 public Object deepCopy(Object value) throws HibernateException{
 return value;
 }

 public boolean isMutable() {
 return false;
 }

 public Object assemble(Serializable cached, Object owner) throws HibernateException {
 return cached;
 }

 public Serializable disassemble(Object value) throws HibernateException {
 return (Serializable)value;
 }

 public Object replace(Object original, Object target, Object owner) throws HibernateException {
 return original;
 }

 public int hashCode(Object x) throws HibernateException {
 return x.hashCode();
 }

 public boolean equals(Object x, Object y) throws HibernateException {
 if (x == y) {
 return true;
 }

 if (null == x || null == y) {
 return false;
 }

 return x.equals(y);
 }
}

Here is an example Enum:

public ExampleEnum {
 ENUM_A,
 ENUM_B;
}

Now we just need to create the following custom mapping type:

public class ExampleEnumType extends EnumType<ExampleEnum> {

public ExampleEnumType() {
 super(ExampleEnum.class);
 }
}

Finally, add it to your mapping file:

<hibernate-mapping>
[...]
 <property name="sample" type="mypackage.MyEnumUserType" not-null="true"/>
[...]

Or add it via Annotation:

@Entity
@TypeDef(name = "exampleEnumTypeDef", typeClass = ExampleEnumType.class)
public class Test {
 private ExampleEnum exampleEnum;
 [...]

@Type(type = "exampleEnumTypeDef")
@Column(name = "example")
public ExampleEnum getExample() {
 return exampleEnum;
 }

public void setExample(ExampleEnum exampleEnum) {
 this.exampleEnum = exampleEnum;
 }
}

I helps me very well and I hope you too.

Here is a very small and simple code to remove superfluous whitespaces (leading, in between but leave at least one and at the end).

 

String test = ” Hello   World  here I    am.  “;

test = test.replaceAll(“\\s+”, ” “).trim();

Result is: “Hello World here I am.”;

 

I have seen a lot of other implementations that will also work. But they often use the regex package, which produces too much overhead and is not needed for such small issue.

Sometimes it could be a little bit strange if you try to drop a foreign key on a MySQL table. You get for example error messages like this one:

  • Error on rename of ‘.\database\mytable’ to ‘.\database\#sql2-6ec-11′ (errno: 152)
  • Error on rename of ‘.\database\#sql-6ec_13′ to ‘.\database\mytable’ (errno: 150)

Often times this is because adding foreign keys also  adds an index key to the table (on top of the reference key).

To drop it you need to execute these two statements:

  • ALTER TABLE <table> DROP FOREIGN KEY `<foreign key name>`;
  • DROP INDEX <fk name or index name> ON <table>;

Here is another example (slight different):

CREATE TABLE `table_name`:
| table_name | CREATE TABLE `table_name` (
`id` int(20) unsigned NOT NULL auto_increment,
`key_column` smallint(5) unsigned default ’1′,
KEY `key_column` (`key_column`),
CONSTRAINT `table_name_ibfk_1` FOREIGN KEY (`key_column`) REFERENCES
`second_table` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |

So, first you remove the key:

ALTER TABLE table_name DROP KEY `key_column`;

then the foreign key:

ALTER TABLE table_name DROP FOREIGN KEY `table_name_ibfk_1`;

The error:

Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Long field fo.bar.ClassName to java.lang.Long

The solution:

The problem is that the field of the object which is used is an object itself and I did not specifiy the field of the object. Therefore we need to specifiy the field of the object.

Description:

This section in the SQL (excerpt):

pricedata.product IN ( ? , ? , ? ) AND ( pricedata.product_unit IN ( ? , ? , ? )

need to be look like this:

pricedata.product.id IN ( ? , ? , ? ) AND ( pricedata.product_unit.id IN ( ? , ? , ? )

Another example:
Pricedata has a many to one relationshipt to product (snippet from pricedata object):

@ManyToOne
@JoinColumn(“product”)
private Product product;

Wrong sql statement:
Select pd from priceData pd where pd.product in (100, 200);

Right sql statment:
Select pd from priceData pd where pd.product.id in (100, 200);

Problem

Normally you set the CATALINA_OPTS with the system properties. But this means you need to change the start script to the server.

SET CATALINA_OPTS=-Djava.security.auth.login.config=C:/programs/Tomcat-6.0.16/webapps/MyApp/WEB-INF/myapp.login -Djava.security.auth.policy=D:/programs/Tomcat-6.0.16/webapps/MyApp/WEB-INF/myapp.policy

Solution:

ServletContext servletContext =  (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();

System.setProperty(“java.security.auth.login.config”, servletContext.getRealPath(“/WEB-INF/myapp.login”));

System.setProperty(“java.security.auth.policy”, servletContext.getRealPath(“/WEB-INF/myapp.policy”));

Beware:

The getRealPath method returns NULL if the servlet container cannot translate the virtual path to a real path for any reason (such as when the content is being made available from a .war archive).

Business plan contest

Last year in December I found out that there was a business plan contest in my city. The contest was announced nationwide. Closing date was in the first January week of 2009. So I wrote my business plan in only one month. Not quite a good idea but I had nothing to lose. The business plan is checked by bankers, entrepreneurs, venture capitalists and people of the ministry of economics. Now I now that I have not made it into the second round. But now I look forward to see what the jurors have to say about my business plan. Because for every business plan that was submitted to the contest a review is written.

Oh, and I also look forward to the awards show. To see what other projects have ben submitted and to socialise with other founders.

Welcome to my blog!

I welcome you to my blog. This is my first post and I hope a thousand more will follow. For now my blog consists of four main topics:

  • Software Development contains Patterns, Examples, Solutions and Tutorials which I think can help any developer.
  • Founder contains information about my way to become a successful entrepreneur.
  • Urban living contains humorously and pondering posts about my thoughts  and occurrences I see during my day.
  • Miscellaneous contains post that does not fit into the other topics. Just like this one ;-)

I hope you enjoy it,

with kind regards

Nalfein

Follow

Get every new post delivered to your Inbox.