001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.swaps;
018
019import static org.apache.juneau.common.utils.ThrowableUtils.*;
020
021import javax.xml.datatype.*;
022
023import org.apache.juneau.*;
024import org.apache.juneau.common.utils.*;
025import org.apache.juneau.swap.*;
026
027/**
028 * Transforms {@link XMLGregorianCalendar XMLGregorianCalendars} to ISO8601 date-time {@link String Strings}.
029 *
030 * <p>
031 * Objects are converted to strings using {@link XMLGregorianCalendar#toXMLFormat()}.
032 *
033 * <p>
034 * Strings are converted to objects using {@link DatatypeFactory#newXMLGregorianCalendar(String)}.
035 *
036 * <h5 class='section'>See Also:</h5><ul>
037 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/SwapBasics">Swap Basics</a>
038
039 * </ul>
040 */
041public class XMLGregorianCalendarSwap extends StringSwap<XMLGregorianCalendar> {
042
043   private DatatypeFactory dtf;
044
045   /**
046    * Constructor.
047    */
048   public XMLGregorianCalendarSwap() {
049      try {
050         this.dtf = DatatypeFactory.newInstance();
051      } catch (DatatypeConfigurationException e) {
052         throw asRuntimeException(e);
053      }
054   }
055
056   /**
057    * Converts the specified <c>XMLGregorianCalendar</c> to a {@link String}.
058    */
059   @Override /* ObjectSwap */
060   public String swap(BeanSession session, XMLGregorianCalendar b) throws Exception {
061      return b.toXMLFormat();
062   }
063
064   /**
065    * Converts the specified {@link String} to an <c>XMLGregorianCalendar</c>.
066    */
067   @Override /* ObjectSwap */
068   public XMLGregorianCalendar unswap(BeanSession session, String s, ClassMeta<?> hint) throws Exception {
069      if (Utils.isEmpty(s))
070         return null;
071      return dtf.newXMLGregorianCalendar(s);
072   }
073}