Java tutorial
/* Copyright 2009 - 2010 Under Dusken Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package no.dusken.barweb.admin.editor; import no.dusken.common.model.DuskenObject; import no.dusken.common.service.GenericService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Required; import java.beans.PropertyEditorSupport; public class GenericEditor<T extends DuskenObject> extends PropertyEditorSupport { protected final static Logger log = LoggerFactory.getLogger(GenericEditor.class); private GenericService<T> genericService; @Override public String getAsText() { if (log.isDebugEnabled()) log.debug(getValue().toString()); @SuppressWarnings({ "unchecked" }) T entity = (T) getValue(); if (entity == null) return " "; Long ID = entity.getId(); if (ID == null) return " "; if (log.isDebugEnabled()) log.debug(ID.toString()); return ID.toString(); } @Override public void setAsText(String string) throws IllegalArgumentException { if (string == null || string.equals("")) { setValue(null); return; } Long ID; try { ID = Long.parseLong(string); } catch (NumberFormatException e) { setValue(null); throw new IllegalArgumentException("Not a valid ID: " + string); } if (log.isDebugEnabled()) { log.debug("getting entity with ID: " + ID); T entity = genericService.findOne(ID); log.debug("got " + entity.getClass()); log.debug("got entity: " + entity); setValue(entity); return; } setValue(genericService.findOne(ID)); } @Required public void setGenericService(GenericService<T> genericService) { this.genericService = genericService; } }