All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.apicatalog.cborld.dictionary.CodeTermMap Maven / Gradle / Ivy

package com.apicatalog.cborld.dictionary;

import java.math.BigInteger;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.apicatalog.cborld.context.ContextError;
import com.apicatalog.jsonld.loader.DocumentLoader;

public class CodeTermMap implements Dictionary {

    final Map index;
    final Map reverse;

    int lastCustomIndex;

    protected CodeTermMap(Map index, int lastCustomIndex) {
        this.index = index;
        this.reverse = index
                .entrySet()
                       .stream()
                       .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
    
        this.lastCustomIndex = lastCustomIndex;
    }

    public static CodeTermMap from(Collection> contextKeys, DocumentLoader loader) throws ContextError {
    
        final CodeTermMap map = new CodeTermMap(
                                  new LinkedHashMap<>(KeywordDictionary.CODE_TO_TERM),
                                  KeywordDictionary.CUSTOM_OFFSET
                                  );
        contextKeys
            .stream()
            .map(c -> c.stream().sorted())
            .flatMap(Function.identity())
            .forEach(map::add);
            
            return map;
    }
    
    public static CodeTermMap create() {
        
        final CodeTermMap map = new CodeTermMap(
                new LinkedHashMap<>(KeywordDictionary.CODE_TO_TERM),
                KeywordDictionary.CUSTOM_OFFSET
                );
        
        return map;
    }
    
    public void add(Collection keys) {
        keys
        .stream()
        .sorted()
        .forEach(this::add);
    }
    
    public void add(String key) {
        if (!reverse.containsKey(key)) {
                index.put(lastCustomIndex, key);
                reverse.put(key,  lastCustomIndex);
                lastCustomIndex += 2;
        }
    }

    @Override
    public String getValue(BigInteger code) {
        return index.get(code.intValueExact());
    }

    @Override
    public BigInteger getCode(String term) {
        return reverse.containsKey(term) ? BigInteger.valueOf(reverse.get(term)) : null;
    }    
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy