    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.text.translate;
    018
    019import java.io.IOException;
    020import java.io.Writer;
    021import java.security.InvalidParameterException;
    022import java.util.BitSet;
    023import java.util.HashMap;
    024import java.util.Map;
    025
    026/**
    027 * Translates a value using a lookup table.
    028 *
    029 * @since 1.0
    030 */
    031public class LookupTranslator extends CharSequenceTranslator {
    032
    033    /** The mapping to be used in translation. */
    034    private final Map<String, String> lookupMap;
    035    /** The first character of each key in the lookupMap. */
    036    private final BitSet prefixSet;
    037    /** The length of the shortest key in the lookupMap. */
    038    private final int shortest;
    039    /** The length of the longest key in the lookupMap. */
    040    private final int longest;
    041
    042    /**
    043     * Define the lookup table to be used in translation
    044     *
    045     * Note that, as of Lang 3.1 (the origin of this code), the key to the lookup
    046     * table is converted to a java.lang.String. This is because we need the key
    047     * to support hashCode and equals(Object), allowing it to be the key for a
    048     * HashMap. See LANG-882.
    049     *
    050     * @param lookupMap Map&lt;CharSequence, CharSequence&gt; table of translator
    051     *                  mappings
    052     */
    053    public LookupTranslator(final Map<CharSequence, CharSequence> lookupMap) {
    054        if (lookupMap == null) {
    055            throw new InvalidParameterException("lookupMap cannot be null");
    056        }
    057        this.lookupMap = new HashMap<>();
    058        this.prefixSet = new BitSet();
    059        int currentShortest = Integer.MAX_VALUE;
    060        int currentLongest = 0;
    061
    062        for (final Map.Entry<CharSequence, CharSequence> pair : lookupMap.entrySet()) {
    063            this.lookupMap.put(pair.getKey().toString(), pair.getValue().toString());
    064            this.prefixSet.set(pair.getKey().charAt(0));
    065            final int sz = pair.getKey().length();
    066            if (sz < currentShortest) {
    067                currentShortest = sz;
    068            }
    069            if (sz > currentLongest) {
    070                currentLongest = sz;
    071            }
    072        }
    073        this.shortest = currentShortest;
    074        this.longest = currentLongest;
    075    }
    076
    077    /**
    078     * {@inheritDoc}
    079     */
    080    @Override
    081    public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
    082        // check if translation exists for the input at position index
    083        if (prefixSet.get(input.charAt(index))) {
    084            int max = longest;
    085            if (index + longest > input.length()) {
    086                max = input.length() - index;
    087            }
    088            // implement greedy algorithm by trying maximum match first
    089            for (int i = max; i >= shortest; i--) {
    090                final CharSequence subSeq = input.subSequence(index, index + i);
    091                final String result = lookupMap.get(subSeq.toString());
    092
    093                if (result != null) {
    094                    out.write(result);
    095                    return i;
    096                }
    097            }
    098        }
    099        return 0;
    100    }
    101}