001/**
002 * Copyright 2005-2016 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.kim.api.jaxb;
017
018import javax.xml.bind.MarshalException;
019import javax.xml.bind.UnmarshalException;
020import javax.xml.bind.annotation.adapters.NormalizedStringAdapter;
021import javax.xml.bind.annotation.adapters.XmlAdapter;
022
023import org.apache.commons.lang.StringUtils;
024import org.kuali.rice.core.util.jaxb.NameAndNamespacePair;
025import org.kuali.rice.kim.api.services.KimApiServiceLocator;
026import org.kuali.rice.kim.api.type.KimTypeContract;
027
028/**
029 * An XML adapter that converts between a NameAndNamespacePair and a KIM type ID.
030 * 
031 * @author Kuali Rice Team (rice.collab@kuali.org)
032 */
033public class NameAndNamespacePairToKimTypeIdAdapter extends XmlAdapter<NameAndNamespacePair,String> {
034
035    /**
036     * @see javax.xml.bind.annotation.adapters.XmlAdapter#unmarshal(java.lang.Object)
037     */
038    @Override
039    public String unmarshal(NameAndNamespacePair v) throws Exception {
040        if (v != null) {
041            KimTypeContract kimType = KimApiServiceLocator.getKimTypeInfoService().findKimTypeByNameAndNamespace(
042                    v.getNamespaceCode(), new NormalizedStringAdapter().unmarshal(v.getName()));
043            if (kimType == null) {
044                throw new UnmarshalException("Cannot find KIM Type with namespace \"" + v.getNamespaceCode() + "\" and name \"" + v.getName() + "\"");
045            }
046            return kimType.getId();
047        }
048        return null;
049    }
050
051    /**
052     * @see javax.xml.bind.annotation.adapters.XmlAdapter#marshal(java.lang.Object)
053     */
054    @Override
055    public NameAndNamespacePair marshal(String v) throws Exception {
056        if (v != null) {
057            KimTypeContract kimType = KimApiServiceLocator.getKimTypeInfoService().getKimType(StringUtils.trim(v));
058            if (kimType == null) {
059                throw new MarshalException("Cannot find KIM Type with ID \"" + v + "\"");
060            }
061            return new NameAndNamespacePair(kimType.getNamespaceCode(), kimType.getName());
062        }
063        return null;
064    }
065
066}