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.NameExpr;
020import japa.parser.ast.expr.QualifiedNameExpr;
021import japa.parser.ast.expr.SingleMemberAnnotationExpr;
022import japa.parser.ast.expr.StringLiteralExpr;
023import org.apache.ojb.broker.metadata.CollectionDescriptor;
024import org.apache.ojb.broker.metadata.DescriptorRepository;
025import org.apache.ojb.broker.metadata.FieldHelper;
026import org.kuali.rice.devtools.jpa.eclipselink.conv.ojb.OjbUtil;
027import org.kuali.rice.devtools.jpa.eclipselink.conv.parser.helper.NodeData;
028
029import java.util.Collection;
030
031public class OrderByResolver extends AbstractMappedFieldResolver {
032
033    public static final String PACKAGE = "javax.persistence";
034    public static final String SIMPLE_NAME = "OrderBy";
035
036    public OrderByResolver(Collection<DescriptorRepository> descriptorRepositories) {
037        super(descriptorRepositories);
038    }
039    @Override
040    public String getFullyQualifiedName() {
041        return PACKAGE + "." + SIMPLE_NAME;
042    }
043
044    /** gets the annotation but also adds an import in the process if a Convert annotation is required. */
045    @Override
046    protected NodeData getAnnotationNodes(String enclosingClass, String fieldName, String mappedClass) {
047        final CollectionDescriptor cld = OjbUtil.findCollectionDescriptor(mappedClass, fieldName, descriptorRepositories);
048        if (cld != null) {
049            Collection<FieldHelper> orderBy = cld.getOrderBy();
050            if (orderBy != null && !orderBy.isEmpty()) {
051                String orderByStr = "";
052                for (FieldHelper fh : orderBy) {
053                    orderByStr += fh.name + (fh.isAscending ? "" : " DESC") + ", ";
054                }
055                orderByStr = orderByStr.replaceAll(", $", "");
056                return new NodeData(new SingleMemberAnnotationExpr(new NameExpr(SIMPLE_NAME), new StringLiteralExpr(orderByStr)),
057                        new ImportDeclaration(new QualifiedNameExpr(new NameExpr(PACKAGE), SIMPLE_NAME), false, false));
058            }
059        }
060        return null;
061    }
062}