From 86043fd87e14690e48fca25d53cfb8be652d009c Mon Sep 17 00:00:00 2001 From: frsyuki Date: Fri, 22 Oct 2010 08:31:03 +0900 Subject: [PATCH] java: adds OptionalTemplate --- java/pom.xml | 2 +- .../msgpack/template/OptionalTemplate.java | 52 +++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 java/src/main/java/org/msgpack/template/OptionalTemplate.java diff --git a/java/pom.xml b/java/pom.xml index beec5034..aa3e3ce7 100755 --- a/java/pom.xml +++ b/java/pom.xml @@ -3,7 +3,7 @@ 4.0.0 org.msgpack msgpack - 0.4 + 0.4.0-devel MessagePack for Java MessagePack for Java diff --git a/java/src/main/java/org/msgpack/template/OptionalTemplate.java b/java/src/main/java/org/msgpack/template/OptionalTemplate.java new file mode 100644 index 00000000..6be16c1a --- /dev/null +++ b/java/src/main/java/org/msgpack/template/OptionalTemplate.java @@ -0,0 +1,52 @@ +// +// MessagePack for Java +// +// Copyright (C) 2009-2010 FURUHASHI Sadayuki +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +package org.msgpack.template; + +import java.util.List; +import java.util.ArrayList; +import java.io.IOException; +import org.msgpack.*; + +public class OptionalTemplate implements Template { + private Template elementTemplate; + private Object defaultObject; + + public OptionalTemplate(Template elementTemplate) { + this(elementTemplate, null); + } + + public OptionalTemplate(Template elementTemplate, Object defaultObject) { + this.elementTemplate = elementTemplate; + this.defaultObject = defaultObject; + } + + public Object unpack(Unpacker pac) throws IOException, MessageTypeException { + if(pac.tryUnpackNull()) { + return defaultObject; + } + return elementTemplate.unpack(pac); + } + + public Object convert(MessagePackObject from) throws MessageTypeException { + if(from.isNil()) { + return defaultObject; + } + return elementTemplate.convert(from); + } +} +