001/*
002 * Copyright 2011 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/ecl1.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.kuali.rice.core.util.jaxb.NameAndNamespacePair;
024import org.kuali.rice.kim.api.common.template.Template;
025import org.kuali.rice.kim.api.services.KimApiServiceLocator;
026
027/**
028 * An XML adapter that converts between a NameAndNamespacePair and a permission template ID.
029 * 
030 * @author Kuali Rice Team (rice.collab@kuali.org)
031 */
032public class NameAndNamespacePairToPermTemplateIdAdapter extends XmlAdapter<NameAndNamespacePair,String> {
033
034    /**
035     * @see javax.xml.bind.annotation.adapters.XmlAdapter#unmarshal(java.lang.Object)
036     */
037    @Override
038    public String unmarshal(NameAndNamespacePair v) throws Exception {
039        if (v != null) {
040            Template permissionTemplate = KimApiServiceLocator.getPermissionService().findPermTemplateByNamespaceCodeAndName(
041                    v.getNamespaceCode(), new NormalizedStringAdapter().unmarshal(v.getName()));
042            if (permissionTemplate == null) {
043                throw new UnmarshalException("Cannot find permission template with namespace \"" + v.getNamespaceCode() + "\" and name \"" + v.getName() + "\"");
044            }
045            return permissionTemplate.getId();
046        }
047        return null;
048    }
049
050    /**
051     * @see javax.xml.bind.annotation.adapters.XmlAdapter#marshal(java.lang.Object)
052     */
053    @Override
054    public NameAndNamespacePair marshal(String v) throws Exception {
055        if (v != null) {
056            Template permissionTemplate = KimApiServiceLocator.getPermissionService().getPermissionTemplate(v);
057            if (permissionTemplate == null) {
058                throw new MarshalException("Cannot find permission template with ID \"" + v + "\"");
059            }
060            return new NameAndNamespacePair(permissionTemplate.getNamespaceCode(), permissionTemplate.getName());
061        }
062        return null;
063    }
064
065}