2 * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.Maps;
14 import java.util.Date;
16 import javax.management.openmbean.SimpleType;
17 import org.opendaylight.controller.config.facade.xml.util.Util;
19 public class SimpleAttributeMappingStrategy extends AbstractAttributeMappingStrategy<String, SimpleType<?>> {
21 public SimpleAttributeMappingStrategy(final SimpleType<?> openType) {
26 public Optional<String> mapAttribute(final Object value) {
28 return Optional.absent();
31 String expectedClass = getOpenType().getClassName();
32 String realClass = value.getClass().getName();
33 Preconditions.checkArgument(realClass.equals(expectedClass),
34 "Type mismatch, expected " + expectedClass + " but was " + realClass);
36 WriterPlugin prefferedPlugin = WRITER_PLUGINS.get(value.getClass().getCanonicalName());
37 prefferedPlugin = prefferedPlugin == null ? WRITER_PLUGINS.get(DEFAULT_WRITER_PLUGIN) : prefferedPlugin;
38 return Optional.of(prefferedPlugin.writeObject(value));
41 private static final String DEFAULT_WRITER_PLUGIN = "default";
42 private static final Map<String, WriterPlugin> WRITER_PLUGINS = Maps.newHashMap();
45 WRITER_PLUGINS.put(DEFAULT_WRITER_PLUGIN, new DefaultWriterPlugin());
46 WRITER_PLUGINS.put(Date.class.getCanonicalName(), new DatePlugin());
50 * Custom writer plugins must implement this interface.
52 interface WriterPlugin {
53 String writeObject(Object value);
56 static class DefaultWriterPlugin implements WriterPlugin {
59 public String writeObject(final Object value) {
60 return value.toString();
64 static class DatePlugin implements WriterPlugin {
67 public String writeObject(final Object value) {
68 Preconditions.checkArgument(value instanceof Date, "Attribute must be Date");
69 return Util.writeDate((Date) value);