update copyright
[fedora-idea.git] / xml / dom-openapi / src / com / intellij / util / xml / WrappingConverter.java
blob56214eb4dc730a6254a28ff0e6603e416ecc4e8d
1 /*
2 * Copyright 2000-2009 JetBrains s.r.o.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.intellij.util.xml;
19 import org.jetbrains.annotations.NonNls;
20 import org.jetbrains.annotations.NotNull;
21 import org.jetbrains.annotations.Nullable;
23 import java.util.List;
24 import java.util.Collections;
26 /**
27 * @author Gregory.Shrago
29 public abstract class WrappingConverter extends Converter<Object> {
31 public Object fromString(@Nullable @NonNls String s, final ConvertContext context) {
32 final List<Converter> converters = getConverters((GenericDomValue)context.getInvocationElement());
33 if (converters.isEmpty()) return s;
34 for (Converter converter : converters) {
35 final Object o = converter.fromString(s, context);
36 if (o != null) {
37 return o;
40 return null;
43 public String toString(@Nullable Object t, final ConvertContext context) {
44 final List<Converter> converters = getConverters((GenericDomValue)context.getInvocationElement());
45 if (converters.isEmpty()) return String.valueOf(t);
46 for (Converter converter : converters) {
47 final String s = converter.toString(t, context);
48 if (s != null) {
49 return s;
52 return null;
55 @NotNull
56 public List<Converter> getConverters(@NotNull final GenericDomValue domElement) {
57 final Converter converter = getConverter(domElement);
58 return converter == null ? Collections.<Converter>emptyList() : Collections.singletonList(converter);
61 @Nullable
62 public abstract Converter getConverter(@NotNull final GenericDomValue domElement);
64 public static Converter getDeepestConverter(final Converter converter, final GenericDomValue domValue) {
65 Converter cur = converter;
66 Converter next;
67 int guard = 0;
68 while (cur instanceof WrappingConverter) {
69 next = ((WrappingConverter)cur).getConverter(domValue);
70 if (next == null) break;
71 cur = next;
72 if (guard++ > 10) {
73 throw new RuntimeException("Too deep wrapping for " + converter);
76 return cur;