001/*
002 * Copyright 2012 Atteo.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.atteo.evo.filtering;
017
018import java.util.List;
019
020import org.atteo.evo.filtering.Filtering.Token;
021
022import com.google.common.base.Splitter;
023
024public class OneOfPropertyResolver implements PrefixedPropertyResolver {
025    private static final String prefix = "oneof:";
026
027    @Override
028    public String getPrefix() {
029        return prefix;
030    }
031
032    @Override
033    public String resolveProperty(String name, PropertyResolver resolver) throws PropertyNotFoundException {
034        if (!name.startsWith(prefix)) {
035            return null;
036        }
037        name = name.substring(prefix.length());
038        List<Token> tokens = Filtering.splitIntoTokens(name);
039
040        StringBuilder result = new StringBuilder();
041        boolean skip = false;
042
043        for (Token token : tokens) {
044            if (token.isProperty()) {
045                if (!skip) {
046                    String value = Filtering.getProperty(token.getValue(), resolver);
047                    if (value == null) {
048                        skip = true;
049                    }
050                    result.append(value);
051                }
052            } else {
053                boolean first = true;
054                for (String p : Splitter.on(',').split(token.getValue())) {
055                    if (!first) {
056                        if (!skip) {
057                            return result.toString();
058                        } else {
059                            result = new StringBuilder();
060                            skip = false;
061                        }
062                    }
063                    if (!skip) {
064                        result.append(p);
065                    }
066                    if (first) {
067                        first = false;
068                    }
069                }
070            }
071        }
072        if (skip) {
073            return null;
074        }
075
076        return result.toString();
077    }
078}