1 /*
2  * JBoss, Home of Professional Open Source.
3  *
4  * Copyright 2011 Red Hat, Inc. and/or its affiliates, and individual
5  * contributors as indicated by the @author tags.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */

19
20 package org.xnio;
21
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.List;
25
26 import static org.xnio._private.Messages.msg;
27
28 /**
29  * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
30  */

31 final class SequenceOption<T> extends Option<Sequence<T>> {
32
33     private static final long serialVersionUID = -4328676629293125136L;
34
35     private final transient Class<T> elementType;
36     private final transient ValueParser<T> parser;
37
38     SequenceOption(final Class<?> declClass, final String name, final Class<T> elementType) {
39         super(declClass, name);
40         if (elementType == null) {
41             throw msg.nullParameter("elementType");
42         }
43         this.elementType = elementType;
44         parser = Option.getParser(elementType);
45     }
46
47     public Sequence<T> cast(final Object o) {
48         if (o == null) {
49             return null;
50         } else if (o instanceof Sequence) {
51             return ((Sequence<?>)o).cast(elementType);
52         } else if (o instanceof Object[]){
53             return Sequence.of((Object[])o).cast(elementType);
54         } else if (o instanceof Collection) {
55             return Sequence.of((Collection<?>)o).cast(elementType);
56         } else {
57             throw new ClassCastException("Not a sequence");
58         }
59     }
60
61     public Sequence<T> parseValue(final String string, final ClassLoader classLoader) throws IllegalArgumentException {
62         final List<T> list = new ArrayList<T>();
63         if (string.isEmpty()) {
64             return Sequence.empty();
65         }
66         for (String value : string.split(",")) {
67             list.add(parser.parseValue(value, classLoader));
68         }
69         return Sequence.of(list);
70     }
71 }
72