001/**
002 * Copyright 2005-2015 The Kuali Foundation
003 *
004 * Licensed under the Educational Community License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.opensource.org/licenses/ecl2.php
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.kuali.rice.devtools.jpa.eclipselink.conv.parser.helper.resolver;
017
018import japa.parser.ast.ImportDeclaration;
019import japa.parser.ast.expr.MarkerAnnotationExpr;
020import japa.parser.ast.expr.NameExpr;
021import japa.parser.ast.expr.QualifiedNameExpr;
022import org.apache.ojb.broker.metadata.DescriptorRepository;
023import org.apache.ojb.broker.metadata.FieldDescriptor;
024import org.kuali.rice.devtools.jpa.eclipselink.conv.ojb.OjbUtil;
025import org.kuali.rice.devtools.jpa.eclipselink.conv.parser.helper.NodeData;
026
027import java.util.Collection;
028
029public class IdResolver extends AbstractMappedFieldResolver {
030
031    public static final String PACKAGE = "javax.persistence";
032    public static final String SIMPLE_NAME = "Id";
033
034    public IdResolver(Collection<DescriptorRepository> descriptorRepositories) {
035        super(descriptorRepositories);
036    }
037
038    @Override
039    public String getFullyQualifiedName() {
040        return PACKAGE + "." + SIMPLE_NAME;
041    }
042
043    @Override
044    protected NodeData getAnnotationNodes(String enclosingClass, String fieldName, String mappedClass) {
045        final boolean pk = isPrimaryKeyColumn(mappedClass, fieldName);
046        if (pk) {
047            return new NodeData(new MarkerAnnotationExpr(new NameExpr(SIMPLE_NAME)),
048                    new ImportDeclaration(new QualifiedNameExpr(new NameExpr(PACKAGE), SIMPLE_NAME), false, false));
049        }
050        return null;
051    }
052
053    private boolean isPrimaryKeyColumn(String clazz, String fieldName) {
054        final FieldDescriptor fd = OjbUtil.findFieldDescriptor(clazz, fieldName, descriptorRepositories);
055
056        if (fd != null) {
057            return fd.isPrimaryKey();
058        }
059        return false;
060    }
061}