001/* Copyright (C) 2014 konik.io
002 *
003 * This file is part of the Konik library.
004 *
005 * The Konik library is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Affero General Public License as
007 * published by the Free Software Foundation, either version 3 of the
008 * License, or (at your option) any later version.
009 *
010 * The Konik library is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013 * GNU Affero General Public License for more details.
014 *
015 * You should have received a copy of the GNU Affero General Public License
016 * along with the Konik library. If not, see <http://www.gnu.org/licenses/>.
017 */
018package io.konik.jaxb.adapter;
019
020import static java.util.logging.Level.WARNING;
021
022import java.util.logging.Logger;
023
024import javax.xml.bind.annotation.adapters.XmlAdapter;
025
026import io.konik.zugferd.entity.Parameter;
027import io.konik.zugferd.profile.ConformanceLevel;
028import io.konik.zugferd.profile.Profile;
029import io.konik.zugferd.profile.ProfileVersion;
030
031/**
032 * 
033 * JaxB Adapter for mapping Parameter to Profile Enum.
034 */
035public class ParameterProfileAdapter extends XmlAdapter<Parameter, Profile> {
036
037   private static final Logger LOG = Logger.getLogger(ParameterProfileAdapter.class.getName());
038   private static final String DELIMITER = ":";
039
040   @Override
041   public Profile unmarshal(Parameter p) throws Exception {
042      if (p == null) {
043         return null;
044      }
045      String fullName = p.getId();
046      try {
047         ProfileVersion version = ProfileVersion.extractVersion(fullName);
048         ConformanceLevel conformanceLevel = ConformanceLevel.extractConformanceLevel(fullName);
049         String ns = getNamespace(fullName);
050         return new Profile(ns, version, conformanceLevel);
051      } catch (RuntimeException e) {
052         LOG.log(WARNING, "Could not parse the profile. Fallback to BASIC latest version", e);
053         return new Profile(ConformanceLevel.BASIC);
054      }
055   }
056
057   private static String getNamespace(String fullName) {
058      String[] tokens = fullName.split(DELIMITER);
059      StringBuilder ns = new StringBuilder();
060      for (int i = 0; i < tokens.length - 2; i++) {
061         ns.append(tokens[i]).append(DELIMITER);
062      }
063      return ns.toString();
064   }
065
066   @Override
067   public Parameter marshal(Profile profile) throws Exception {
068      if (profile == null) {
069         return null;
070      }
071      return new Parameter(profile.fullName());
072   }
073}