/*
* Copyright 2012 Adaptrex, LLC
*
* 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 com.adaptrex.core.persistence.jpa;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.metamodel.PluralAttribute;
import org.apache.commons.lang3.StringUtils;
import com.adaptrex.core.ext.ExtTypeFormatter;
import com.adaptrex.core.ext.FieldDefinition;
import com.adaptrex.core.persistence.api.AdaptrexCollectionType;
import com.adaptrex.core.persistence.api.AdaptrexEntityType;
import com.adaptrex.core.security.SecureEntity;
import com.adaptrex.core.utilities.StringUtilities;
public class JPACollectionType extends AdaptrexCollectionType {
private Method getter;
private Method setter;
public JPACollectionType(PluralAttribute<?,?,?> collection, SecureEntity secureEntity) {
super(collection.getName(), collection.getJavaType(), collection.getElementType().getJavaType(), secureEntity);
String relName = StringUtilities.singularize(collection.getName());
this.idsFieldDefinition =
new FieldDefinition(
relName + StringUtils.capitalize(AdaptrexEntityType.COLLECTION_IDS_NAME),
ExtTypeFormatter.AUTO
);
String capName = StringUtilities.capitalize(getName());
Class<?> declaringClass = collection.getDeclaringType().getJavaType();
try {
getter = declaringClass.getMethod("get" + capName);
} catch (Exception e) {}
if (getter == null) return;
try {
setter = declaringClass.getMethod("set" + capName, getter.getReturnType());
} catch (Exception e) {}
}
@Override
public Object getCollectionFrom(Object entity) throws Exception {
return getter.invoke(entity);
}
@SuppressWarnings("unchecked")
public void setByIds(EntityManager em, Object entity, Object collectionIds) throws Exception {
List<Object> listItemIds = null;
if (collectionIds != null) {
if (collectionIds instanceof String) {
String stringVal = String.valueOf(collectionIds);
if (!stringVal.isEmpty())
listItemIds = (List<Object>) StringUtilities.fromJson(stringVal, List.class);
} else if (collectionIds instanceof List) {
listItemIds = (List<Object>) collectionIds;
}
}
List<Object> newCollection = new ArrayList<Object>();
for (Object listItemId : listItemIds) {
newCollection.add(em.find(this.getItemType(), listItemId));
}
setter.invoke(entity, newCollection);
}
}