/*
Copyright 2006 - 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.aranea.admin.editor;
import no.dusken.aranea.model.AraneaObject;
import no.dusken.common.service.GenericService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import java.util.Collection;
public class GenericCollectionEditor<T extends AraneaObject, U extends Collection>
extends CustomCollectionEditor {
protected final static Logger log = LoggerFactory.getLogger(GenericCollectionEditor.class);
private GenericService<T> genericService;
public GenericCollectionEditor(Class<U> collectionType) {
super(collectionType);
}
/**
* Hook to convert each encountered Collection/array element. The default
* implementation simply returns the passed-in element as-is.
* <p/>
* Can be overridden to perform conversion of certain elements, for example
* String to Integer if a String array comes in and should be converted to a
* Set of Integer objects.
* <p/>
* Only called if actually creating a new Collection! This is by default not
* the case if the type of the passed-in Collection already matches.
* Override {@link #alwaysCreateNewCollection()} to enforce creating a new
* Collection in every case.
*
* @param element the source element
* @return the element to be used in the target Collection
* @see #alwaysCreateNewCollection()
*/
protected Object convertElement(Object element) {
if (log.isDebugEnabled())
log.debug("Converting: {}", element);
if (element instanceof AraneaObject) {
if (log.isDebugEnabled())
log.debug("Element is an AraneaObject: {}", element);
return element;
}
String string = (String) element;
Long ID;
try {
ID = Long.parseLong(string);
} catch (NumberFormatException e) {
return null;
}
if (log.isDebugEnabled()) {
T entity = genericService.getEntity(ID);
log.debug("Got {}", entity.getClass());
log.debug("Got entity: {}", entity);
return entity;
}
return genericService.getEntity(ID);
}
public void setGenericService(GenericService<T> genericService) {
this.genericService = genericService;
}
}