Example usage for java.util HashSet isEmpty

List of usage examples for java.util HashSet isEmpty

Introduction

In this page you can find the example usage for java.util HashSet isEmpty.

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if this set contains no elements.

Usage

From source file:structuredPredictionNLG.SFX.java

/**
 *
 * @param predicate//from   ww w . j  a  v a  2  s.com
 * @param currentAttrValue
 * @param costs
 * @param generatedAttributes
 * @param previousGeneratedWords
 * @param nextGeneratedAttributes
 * @param attrValuesAlreadyMentioned
 * @param attrValuesThatFollow
 * @param wasValueMentioned
 * @param availableWordActions
 * @return
 */
@Override
public Instance createWordInstanceWithCosts(String predicate, String currentAttrValue,
        TObjectDoubleHashMap<String> costs, ArrayList<String> generatedAttributes,
        ArrayList<Action> previousGeneratedWords, ArrayList<String> nextGeneratedAttributes,
        HashSet<String> attrValuesAlreadyMentioned, HashSet<String> attrValuesThatFollow,
        boolean wasValueMentioned, HashMap<String, HashSet<Action>> availableWordActions) {
    String currentAttr = currentAttrValue;
    String currentValue = "";
    if (currentAttr.contains("=")) {
        currentAttr = currentAttrValue.substring(0, currentAttrValue.indexOf('='));
        currentValue = currentAttrValue.substring(currentAttrValue.indexOf('=') + 1);
    }
    if (currentValue.contains(":")) {
        currentValue = currentAttrValue.substring(currentAttrValue.indexOf(':') + 1);
    }
    if (currentValue.isEmpty()) {
        //System.exit(0);
    }

    TObjectDoubleHashMap<String> generalFeatures = new TObjectDoubleHashMap<>();
    HashMap<String, TObjectDoubleHashMap<String>> valueSpecificFeatures = new HashMap<>();
    for (Action action : availableWordActions.get(currentAttr)) {
        valueSpecificFeatures.put(action.getAction(), new TObjectDoubleHashMap<String>());
    }

    /*if (gWords.get(wIndex).getWord().equals(Action.TOKEN_END)) {
    System.out.println("!!! "+ gWords.subList(0, wIndex + 1));
    }*/
    ArrayList<Action> generatedWords = new ArrayList<>();
    ArrayList<Action> generatedWordsInSameAttrValue = new ArrayList<>();
    ArrayList<String> generatedPhrase = new ArrayList<>();
    for (int i = 0; i < previousGeneratedWords.size(); i++) {
        Action a = previousGeneratedWords.get(i);
        if (!a.getWord().equals(Action.TOKEN_START) && !a.getWord().equals(Action.TOKEN_END)) {
            generatedWords.add(a);
            generatedPhrase.add(a.getWord());
            if (a.getAttribute().equals(currentAttrValue)) {
                generatedWordsInSameAttrValue.add(a);
            }
        }
    }

    //Previous word features
    for (int j = 1; j <= 1; j++) {
        String previousWord = "@@";
        if (generatedWords.size() - j >= 0) {
            previousWord = generatedWords.get(generatedWords.size() - j).getWord().trim();
        }
        generalFeatures.put("feature_word_" + j + "_" + previousWord.toLowerCase(), 1.0);
    }
    String prevWord = "@@";
    if (generatedWords.size() - 1 >= 0) {
        prevWord = generatedWords.get(generatedWords.size() - 1).getWord().trim();
    }
    String prev2Word = "@@";
    if (generatedWords.size() - 2 >= 0) {
        prev2Word = generatedWords.get(generatedWords.size() - 2).getWord().trim();
    }
    String prev3Word = "@@";
    if (generatedWords.size() - 3 >= 0) {
        prev3Word = generatedWords.get(generatedWords.size() - 3).getWord().trim();
    }
    String prev4Word = "@@";
    if (generatedWords.size() - 4 >= 0) {
        prev4Word = generatedWords.get(generatedWords.size() - 4).getWord().trim();
    }
    String prev5Word = "@@";
    if (generatedWords.size() - 5 >= 0) {
        prev5Word = generatedWords.get(generatedWords.size() - 5).getWord().trim();
    }

    String prevBigram = prev2Word + "|" + prevWord;
    String prevTrigram = prev3Word + "|" + prev2Word + "|" + prevWord;
    String prev4gram = prev4Word + "|" + prev3Word + "|" + prev2Word + "|" + prevWord;
    String prev5gram = prev5Word + "|" + prev4Word + "|" + prev3Word + "|" + prev2Word + "|" + prevWord;

    generalFeatures.put("feature_word_bigram_" + prevBigram.toLowerCase(), 1.0);
    generalFeatures.put("feature_word_trigram_" + prevTrigram.toLowerCase(), 1.0);
    generalFeatures.put("feature_word_4gram_" + prev4gram.toLowerCase(), 1.0);
    generalFeatures.put("feature_word_5gram_" + prev5gram.toLowerCase(), 1.0);

    /*String bigramWord54 = prev5Word + "|" + prev4Word;
    String bigramWord43 = prev4Word + "|" + prev3Word;
    String bigramWord32 = prev3Word + "|" + prev2Word;
    generalFeatures.put("feature_word_bigramWord54_" + bigramWord54, 1.0);
    generalFeatures.put("feature_word_bigramWord43_" + bigramWord43, 1.0);
    generalFeatures.put("feature_word_bigramWord32_" + bigramWord32, 1.0);
            
    String bigramWordSkip53 = prev5Word + "|" + prev3Word;
    String bigramWordSkip42 = prev4Word + "|" + prev2Word;
    String bigramWordSkip31 = prev3Word + "|" + prevWord;
    generalFeatures.put("feature_word_bigramWordSkip53_" + bigramWordSkip53, 1.0);
    generalFeatures.put("feature_word_bigramWordSkip42_" + bigramWordSkip42, 1.0);
    generalFeatures.put("feature_word_bigramWordSkip31_" + bigramWordSkip31, 1.0);
            
    String trigramWord543 = prev5Word + "|" + prev4Word + "|" + prev3Word;
    String trigramWord432 = prev4Word + "|" + prev3Word + "|" + prev2Word;
    generalFeatures.put("feature_word_trigramWord543_" + trigramWord543, 1.0);
    generalFeatures.put("feature_word_trigramWord432_" + trigramWord432, 1.0);
            
    String trigramWordSkip542 = prev5Word + "|" + prev4Word + "|" + prev2Word;
    String trigramWordSkip532 = prev5Word + "|" + prev3Word + "|" + prev2Word;
    String trigramWordSkip431 = prev4Word + "|" + prev3Word + "|" + prevWord;
    String trigramWordSkip421 = prev4Word + "|" + prev2Word + "|" + prevWord;
    generalFeatures.put("feature_word_trigramWordSkip542_" + trigramWordSkip542, 1.0);
    generalFeatures.put("feature_word_trigramWordSkip532_" + trigramWordSkip532, 1.0);
    generalFeatures.put("feature_word_trigramWordSkip431_" + trigramWordSkip431, 1.0);
    generalFeatures.put("feature_word_trigramWordSkip421_" + trigramWordSkip421, 1.0);*/
    //Previous words in same as current attrValue features
    /*if (generatedWordsInSameAttrValue.isEmpty()) {
    generalFeatures.put("feature_currentAttrValueWord_isEmpty", 1.0);
    }
            
    for (int j = 1; j <= 1; j++) {
    String previousCurrentAttrValueWord = "@@";
    if (generatedWordsInSameAttrValue.size() - j >= 0) {
        previousCurrentAttrValueWord = generatedWordsInSameAttrValue.get(generatedWordsInSameAttrValue.size() - j).getWord().trim();
    }
    generalFeatures.put("feature_currentAttrValueWord_" + j + "_" + previousCurrentAttrValueWord.toLowerCase(), 1.0);
    }
    String prevCurrentAttrValueWord = "@@";
    if (generatedWordsInSameAttrValue.size() - 1 >= 0) {
    prevCurrentAttrValueWord = generatedWordsInSameAttrValue.get(generatedWordsInSameAttrValue.size() - 1).getWord().trim();
    }
    String prev2CurrentAttrValueWord = "@@";
    if (generatedWordsInSameAttrValue.size() - 2 >= 0) {
    prev2CurrentAttrValueWord = generatedWordsInSameAttrValue.get(generatedWordsInSameAttrValue.size() - 2).getWord().trim();
    }
    String prev3CurrentAttrValueWord = "@@";
    if (generatedWordsInSameAttrValue.size() - 3 >= 0) {
    prev3CurrentAttrValueWord = generatedWordsInSameAttrValue.get(generatedWordsInSameAttrValue.size() - 3).getWord().trim();
    }
    String prev4CurrentAttrValueWord = "@@";
    if (generatedWordsInSameAttrValue.size() - 4 >= 0) {
    prev4CurrentAttrValueWord = generatedWordsInSameAttrValue.get(generatedWordsInSameAttrValue.size() - 4).getWord().trim();
    }
    String prev5CurrentAttrValueWord = "@@";
    if (generatedWordsInSameAttrValue.size() - 5 >= 0) {
    prev5CurrentAttrValueWord = generatedWordsInSameAttrValue.get(generatedWordsInSameAttrValue.size() - 5).getWord().trim();
    }
            
    String prevCurrentAttrValueBigram = prev2CurrentAttrValueWord + "|" + prevCurrentAttrValueWord;
    String prevCurrentAttrValueTrigram = prev3CurrentAttrValueWord + "|" + prev2CurrentAttrValueWord + "|" + prevCurrentAttrValueWord;
    String prevCurrentAttrValue4gram = prev4CurrentAttrValueWord + "|" + prev3CurrentAttrValueWord + "|" + prev2CurrentAttrValueWord + "|" + prevCurrentAttrValueWord;
    String prevCurrentAttrValue5gram = prev5CurrentAttrValueWord + "|" + prev4CurrentAttrValueWord + "|" + prev3CurrentAttrValueWord + "|" + prev2CurrentAttrValueWord + "|" + prevCurrentAttrValueWord;
            
    generalFeatures.put("feature_currentAttrValueWord_bigram_" + prevCurrentAttrValueBigram.toLowerCase(), 1.0);
    generalFeatures.put("feature_currentAttrValueWord_trigram_" + prevCurrentAttrValueTrigram.toLowerCase(), 1.0);
    generalFeatures.put("feature_currentAttrValueWord_4gram_" + prevCurrentAttrValue4gram.toLowerCase(), 1.0);
    generalFeatures.put("feature_currentAttrValueWord_5gram_" + prevCurrentAttrValue5gram.toLowerCase(), 1.0);*/

    /*String bigramCurrentAttrValueWord54 = prev5CurrentAttrValueWord + "|" + prev4CurrentAttrValueWord;
           String bigramCurrentAttrValueWord43 = prev4CurrentAttrValueWord + "|" + prev3CurrentAttrValueWord;
           String bigramCurrentAttrValueWord32 = prev3CurrentAttrValueWord + "|" + prev2CurrentAttrValueWord;
           generalFeatures.put("feature_currentAttrValueWord_bigramCurrentAttrValueWord54_" + bigramCurrentAttrValueWord54, 1.0);
           generalFeatures.put("feature_currentAttrValueWord_bigramCurrentAttrValueWord43_" + bigramCurrentAttrValueWord43, 1.0);
           generalFeatures.put("feature_currentAttrValueWord_bigramCurrentAttrValueWord32_" + bigramCurrentAttrValueWord32, 1.0);
                   
           String bigramCurrentAttrValueWordSkip53 = prev5CurrentAttrValueWord + "|" + prev3CurrentAttrValueWord;
           String bigramCurrentAttrValueWordSkip42 = prev4CurrentAttrValueWord + "|" + prev2CurrentAttrValueWord;
           String bigramCurrentAttrValueWordSkip31 = prev3CurrentAttrValueWord + "|" + prevCurrentAttrValueWord;
           generalFeatures.put("feature_currentAttrValueWord_bigramCurrentAttrValueWordSkip53_" + bigramCurrentAttrValueWordSkip53, 1.0);
           generalFeatures.put("feature_currentAttrValueWord_bigramCurrentAttrValueWordSkip42_" + bigramCurrentAttrValueWordSkip42, 1.0);
           generalFeatures.put("feature_currentAttrValueWord_bigramCurrentAttrValueWordSkip31_" + bigramCurrentAttrValueWordSkip31, 1.0);
                   
           String trigramCurrentAttrValueWord543 = prev5CurrentAttrValueWord + "|" + prev4CurrentAttrValueWord + "|" + prev3CurrentAttrValueWord;
           String trigramCurrentAttrValueWord432 = prev4CurrentAttrValueWord + "|" + prev3CurrentAttrValueWord + "|" + prev2CurrentAttrValueWord;
           generalFeatures.put("feature_currentAttrValueWord_trigramCurrentAttrValueWord543_" + trigramCurrentAttrValueWord543, 1.0);
           generalFeatures.put("feature_currentAttrValueWord_trigramCurrentAttrValueWord432_" + trigramCurrentAttrValueWord432, 1.0);
                   
           String trigramCurrentAttrValueWordSkip542 = prev5CurrentAttrValueWord + "|" + prev4CurrentAttrValueWord + "|" + prev2CurrentAttrValueWord;
           String trigramCurrentAttrValueWordSkip532 = prev5CurrentAttrValueWord + "|" + prev3CurrentAttrValueWord + "|" + prev2CurrentAttrValueWord;
           String trigramCurrentAttrValueWordSkip431 = prev4CurrentAttrValueWord + "|" + prev3CurrentAttrValueWord + "|" + prevCurrentAttrValueWord;
           String trigramCurrentAttrValueWordSkip421 = prev4CurrentAttrValueWord + "|" + prev2CurrentAttrValueWord + "|" + prevCurrentAttrValueWord;
           generalFeatures.put("feature_currentAttrValueWord_trigramCurrentAttrValueWordSkip542_" + trigramCurrentAttrValueWordSkip542, 1.0);
           generalFeatures.put("feature_currentAttrValueWord_trigramCurrentAttrValueWordSkip532_" + trigramCurrentAttrValueWordSkip532, 1.0);
           generalFeatures.put("feature_currentAttrValueWord_trigramCurrentAttrValueWordSkip431_" + trigramCurrentAttrValueWordSkip431, 1.0);
           generalFeatures.put("feature_currentAttrValueWord_trigramCurrentAttrValueWordSkip421_" + trigramCurrentAttrValueWordSkip421, 1.0);*/
    //Previous Attr|Word features
    for (int j = 1; j <= 1; j++) {
        String previousAttrWord = "@@";
        if (generatedWords.size() - j >= 0) {
            if (generatedWords.get(generatedWords.size() - j).getAttribute().contains("=")) {
                previousAttrWord = generatedWords.get(generatedWords.size() - j).getAttribute().trim()
                        .substring(0, generatedWords.get(generatedWords.size() - j).getAttribute().indexOf('='))
                        + "|" + generatedWords.get(generatedWords.size() - j).getWord().trim();
            } else {
                previousAttrWord = generatedWords.get(generatedWords.size() - j).getAttribute().trim() + "|"
                        + generatedWords.get(generatedWords.size() - j).getWord().trim();
            }
        }
        generalFeatures.put("feature_attrWord_" + j + "_" + previousAttrWord.toLowerCase(), 1.0);
    }
    String prevAttrWord = "@@";
    if (generatedWords.size() - 1 >= 0) {
        if (generatedWords.get(generatedWords.size() - 1).getAttribute().contains("=")) {
            prevAttrWord = generatedWords.get(generatedWords.size() - 1).getAttribute().trim().substring(0,
                    generatedWords.get(generatedWords.size() - 1).getAttribute().indexOf('=')) + ":"
                    + generatedWords.get(generatedWords.size() - 1).getWord().trim();
        } else {
            prevAttrWord = generatedWords.get(generatedWords.size() - 1).getAttribute().trim() + ":"
                    + generatedWords.get(generatedWords.size() - 1).getWord().trim();

        }
    }
    String prev2AttrWord = "@@";
    if (generatedWords.size() - 2 >= 0) {
        if (generatedWords.get(generatedWords.size() - 2).getAttribute().contains("=")) {
            prev2AttrWord = generatedWords.get(generatedWords.size() - 2).getAttribute().trim().substring(0,
                    generatedWords.get(generatedWords.size() - 2).getAttribute().indexOf('=')) + ":"
                    + generatedWords.get(generatedWords.size() - 2).getWord().trim();
        } else {
            prev2AttrWord = generatedWords.get(generatedWords.size() - 2).getAttribute().trim() + ":"
                    + generatedWords.get(generatedWords.size() - 2).getWord().trim();
        }
    }
    String prev3AttrWord = "@@";
    if (generatedWords.size() - 3 >= 0) {
        if (generatedWords.get(generatedWords.size() - 3).getAttribute().contains("=")) {
            prev3AttrWord = generatedWords.get(generatedWords.size() - 3).getAttribute().trim().substring(0,
                    generatedWords.get(generatedWords.size() - 3).getAttribute().indexOf('=')) + ":"
                    + generatedWords.get(generatedWords.size() - 3).getWord().trim();
        } else {
            prev3AttrWord = generatedWords.get(generatedWords.size() - 3).getAttribute().trim() + ":"
                    + generatedWords.get(generatedWords.size() - 3).getWord().trim();
        }
    }
    String prev4AttrWord = "@@";
    if (generatedWords.size() - 4 >= 0) {
        if (generatedWords.get(generatedWords.size() - 4).getAttribute().contains("=")) {
            prev4AttrWord = generatedWords.get(generatedWords.size() - 4).getAttribute().trim().substring(0,
                    generatedWords.get(generatedWords.size() - 4).getAttribute().indexOf('=')) + ":"
                    + generatedWords.get(generatedWords.size() - 4).getWord().trim();
        } else {
            prev4AttrWord = generatedWords.get(generatedWords.size() - 4).getAttribute().trim() + ":"
                    + generatedWords.get(generatedWords.size() - 4).getWord().trim();
        }
    }
    String prev5AttrWord = "@@";
    if (generatedWords.size() - 5 >= 0) {
        if (generatedWords.get(generatedWords.size() - 5).getAttribute().contains("=")) {
            prev5AttrWord = generatedWords.get(generatedWords.size() - 5).getAttribute().trim().substring(0,
                    generatedWords.get(generatedWords.size() - 5).getAttribute().indexOf('=')) + ":"
                    + generatedWords.get(generatedWords.size() - 5).getWord().trim();
        } else {
            prev5AttrWord = generatedWords.get(generatedWords.size() - 5).getAttribute().trim() + ":"
                    + generatedWords.get(generatedWords.size() - 5).getWord().trim();
        }
    }

    String prevAttrWordBigram = prev2AttrWord + "|" + prevAttrWord;
    String prevAttrWordTrigram = prev3AttrWord + "|" + prev2AttrWord + "|" + prevAttrWord;
    String prevAttrWord4gram = prev4AttrWord + "|" + prev3AttrWord + "|" + prev2AttrWord + "|" + prevAttrWord;
    String prevAttrWord5gram = prev5AttrWord + "|" + prev4AttrWord + "|" + prev3AttrWord + "|" + prev2AttrWord
            + "|" + prevAttrWord;

    generalFeatures.put("feature_attrWord_bigram_" + prevAttrWordBigram.toLowerCase(), 1.0);
    generalFeatures.put("feature_attrWord_trigram_" + prevAttrWordTrigram.toLowerCase(), 1.0);
    generalFeatures.put("feature_attrWord_4gram_" + prevAttrWord4gram.toLowerCase(), 1.0);
    generalFeatures.put("feature_attrWord_5gram_" + prevAttrWord5gram.toLowerCase(), 1.0);

    /*String bigramAttrWord54 = prev5AttrWord + "|" + prev4AttrWord;
    String bigramAttrWord43 = prev4AttrWord + "|" + prev3AttrWord;
    String bigramAttrWord32 = prev3AttrWord + "|" + prev2AttrWord;
    generalFeatures.put("feature_attrWord_bigramAttrWord54_" + bigramAttrWord54, 1.0);
    generalFeatures.put("feature_attrWord_bigramAttrWord43_" + bigramAttrWord43, 1.0);
    generalFeatures.put("feature_attrWord_bigramAttrWord32_" + bigramAttrWord32, 1.0);
            
    String bigramAttrWordSkip53 = prev5AttrWord + "|" + prev3AttrWord;
    String bigramAttrWordSkip42 = prev4AttrWord + "|" + prev2AttrWord;
    String bigramAttrWordSkip31 = prev3AttrWord + "|" + prevAttrWord;
    generalFeatures.put("feature_attrWord_bigramAttrWordSkip53_" + bigramAttrWordSkip53, 1.0);
    generalFeatures.put("feature_attrWord_bigramAttrWordSkip42_" + bigramAttrWordSkip42, 1.0);
    generalFeatures.put("feature_attrWord_bigramAttrWordSkip31_" + bigramAttrWordSkip31, 1.0);
            
    String trigramAttrWord543 = prev5AttrWord + "|" + prev4AttrWord + "|" + prev3AttrWord;
    String trigramAttrWord432 = prev4AttrWord + "|" + prev3AttrWord + "|" + prev2AttrWord;
    generalFeatures.put("feature_attrWord_trigramAttrWord543_" + trigramAttrWord543, 1.0);
    generalFeatures.put("feature_attrWord_trigramAttrWord432_" + trigramAttrWord432, 1.0);
            
    String trigramAttrWordSkip542 = prev5AttrWord + "|" + prev4AttrWord + "|" + prev2AttrWord;
    String trigramAttrWordSkip532 = prev5AttrWord + "|" + prev3AttrWord + "|" + prev2AttrWord;
    String trigramAttrWordSkip431 = prev4AttrWord + "|" + prev3AttrWord + "|" + prevAttrWord;
    String trigramAttrWordSkip421 = prev4AttrWord + "|" + prev2AttrWord + "|" + prevAttrWord;
    generalFeatures.put("feature_attrWord_trigramAttrWordSkip542_" + trigramAttrWordSkip542, 1.0);
    generalFeatures.put("feature_attrWord_trigramAttrWordSkip532_" + trigramAttrWordSkip532, 1.0);
    generalFeatures.put("feature_attrWord_trigramAttrWordSkip431_" + trigramAttrWordSkip431, 1.0);
    generalFeatures.put("feature_attrWord_trigramAttrWordSkip421_" + trigramAttrWordSkip421, 1.0);*/
    //Previous AttrValue|Word features
    for (int j = 1; j <= 1; j++) {
        String previousAttrWord = "@@";
        if (generatedWords.size() - j >= 0) {
            previousAttrWord = generatedWords.get(generatedWords.size() - j).getAttribute().trim() + "|"
                    + generatedWords.get(generatedWords.size() - j).getWord().trim();
        }
        generalFeatures.put("feature_attrValueWord_" + j + "_" + previousAttrWord.toLowerCase(), 1.0);
    }
    String prevAttrValueWord = "@@";
    if (generatedWords.size() - 1 >= 0) {
        prevAttrValueWord = generatedWords.get(generatedWords.size() - 1).getAttribute().trim() + ":"
                + generatedWords.get(generatedWords.size() - 1).getWord().trim();
    }
    String prev2AttrValueWord = "@@";
    if (generatedWords.size() - 2 >= 0) {
        prev2AttrValueWord = generatedWords.get(generatedWords.size() - 2).getAttribute().trim() + ":"
                + generatedWords.get(generatedWords.size() - 2).getWord().trim();
    }
    String prev3AttrValueWord = "@@";
    if (generatedWords.size() - 3 >= 0) {
        prev3AttrValueWord = generatedWords.get(generatedWords.size() - 3).getAttribute().trim() + ":"
                + generatedWords.get(generatedWords.size() - 3).getWord().trim();
    }
    String prev4AttrValueWord = "@@";
    if (generatedWords.size() - 4 >= 0) {
        prev4AttrValueWord = generatedWords.get(generatedWords.size() - 4).getAttribute().trim() + ":"
                + generatedWords.get(generatedWords.size() - 4).getWord().trim();
    }
    String prev5AttrValueWord = "@@";
    if (generatedWords.size() - 5 >= 0) {
        prev5AttrValueWord = generatedWords.get(generatedWords.size() - 5).getAttribute().trim() + ":"
                + generatedWords.get(generatedWords.size() - 5).getWord().trim();
    }

    String prevAttrValueWordBigram = prev2AttrValueWord + "|" + prevAttrValueWord;
    String prevAttrValueWordTrigram = prev3AttrValueWord + "|" + prev2AttrValueWord + "|" + prevAttrValueWord;
    String prevAttrValueWord4gram = prev4AttrValueWord + "|" + prev3AttrValueWord + "|" + prev2AttrValueWord
            + "|" + prevAttrValueWord;
    String prevAttrValueWord5gram = prev5AttrValueWord + "|" + prev4AttrValueWord + "|" + prev3AttrValueWord
            + "|" + prev2AttrValueWord + "|" + prevAttrValueWord;

    generalFeatures.put("feature_attrValueWord_bigram_" + prevAttrValueWordBigram.toLowerCase(), 1.0);
    generalFeatures.put("feature_attrValueWord_trigram_" + prevAttrValueWordTrigram.toLowerCase(), 1.0);
    generalFeatures.put("feature_attrValueWord_4gram_" + prevAttrValueWord4gram.toLowerCase(), 1.0);
    generalFeatures.put("feature_attrValueWord_5gram_" + prevAttrValueWord5gram.toLowerCase(), 1.0);

    /*String bigramAttrValueWord54 = prev5AttrValueWord + "|" + prev4AttrValueWord;
    String bigramAttrValueWord43 = prev4AttrValueWord + "|" + prev3AttrValueWord;
    String bigramAttrValueWord32 = prev3AttrValueWord + "|" + prev2AttrValueWord;
    generalFeatures.put("feature_attrValueWord_bigramAttrValueWord54_" + bigramAttrValueWord54, 1.0);
    generalFeatures.put("feature_attrValueWord_bigramAttrValueWord43_" + bigramAttrValueWord43, 1.0);
    generalFeatures.put("feature_attrValueWord_bigramAttrValueWord32_" + bigramAttrValueWord32, 1.0);
            
    String bigramAttrValueWordSkip53 = prev5AttrValueWord + "|" + prev3AttrValueWord;
    String bigramAttrValueWordSkip42 = prev4AttrValueWord + "|" + prev2AttrValueWord;
    String bigramAttrValueWordSkip31 = prev3AttrValueWord + "|" + prevAttrValueWord;
    generalFeatures.put("feature_attrValueWord_bigramAttrValueWordSkip53_" + bigramAttrValueWordSkip53, 1.0);
    generalFeatures.put("feature_attrValueWord_bigramAttrValueWordSkip42_" + bigramAttrValueWordSkip42, 1.0);
    generalFeatures.put("feature_attrValueWord_bigramAttrValueWordSkip31_" + bigramAttrValueWordSkip31, 1.0);
            
    String trigramAttrValueWord543 = prev5AttrValueWord + "|" + prev4AttrValueWord + "|" + prev3AttrValueWord;
    String trigramAttrValueWord432 = prev4AttrValueWord + "|" + prev3AttrValueWord + "|" + prev2AttrValueWord;
    generalFeatures.put("feature_attrValueWord_trigramAttrValueWord543_" + trigramAttrValueWord543, 1.0);
    generalFeatures.put("feature_attrValueWord_trigramAttrValueWord432_" + trigramAttrValueWord432, 1.0);
            
    String trigramAttrValueWordSkip542 = prev5AttrValueWord + "|" + prev4AttrValueWord + "|" + prev2AttrValueWord;
    String trigramAttrValueWordSkip532 = prev5AttrValueWord + "|" + prev3AttrValueWord + "|" + prev2AttrValueWord;
    String trigramAttrValueWordSkip431 = prev4AttrValueWord + "|" + prev3AttrValueWord + "|" + prevAttrValueWord;
    String trigramAttrValueWordSkip421 = prev4AttrValueWord + "|" + prev2AttrValueWord + "|" + prevAttrValueWord;
    generalFeatures.put("feature_attrValueWord_trigramAttrValueWordSkip542_" + trigramAttrValueWordSkip542, 1.0);
    generalFeatures.put("feature_attrValueWord_trigramAttrValueWordSkip532_" + trigramAttrValueWordSkip532, 1.0);
    generalFeatures.put("feature_attrValueWord_trigramAttrValueWordSkip431_" + trigramAttrValueWordSkip431, 1.0);
    generalFeatures.put("feature_attrValueWord_trigramAttrValueWordSkip421_" + trigramAttrValueWordSkip421, 1.0);*/
    //Previous attrValue features
    int attributeSize = generatedAttributes.size();
    for (int j = 1; j <= 1; j++) {
        String previousAttrValue = "@@";
        if (attributeSize - j >= 0) {
            previousAttrValue = generatedAttributes.get(attributeSize - j).trim();
        }
        generalFeatures.put("feature_attrValue_" + j + "_" + previousAttrValue, 1.0);
    }
    String prevAttrValue = "@@";
    if (attributeSize - 1 >= 0) {
        prevAttrValue = generatedAttributes.get(attributeSize - 1).trim();
    }
    String prev2AttrValue = "@@";
    if (attributeSize - 2 >= 0) {
        prev2AttrValue = generatedAttributes.get(attributeSize - 2).trim();
    }
    String prev3AttrValue = "@@";
    if (attributeSize - 3 >= 0) {
        prev3AttrValue = generatedAttributes.get(attributeSize - 3).trim();
    }
    String prev4AttrValue = "@@";
    if (attributeSize - 4 >= 0) {
        prev4AttrValue = generatedAttributes.get(attributeSize - 4).trim();
    }
    String prev5AttrValue = "@@";
    if (attributeSize - 5 >= 0) {
        prev5AttrValue = generatedAttributes.get(attributeSize - 5).trim();
    }

    String prevAttrBigramValue = prev2AttrValue + "|" + prevAttrValue;
    String prevAttrTrigramValue = prev3AttrValue + "|" + prev2AttrValue + "|" + prevAttrValue;
    String prevAttr4gramValue = prev4AttrValue + "|" + prev3AttrValue + "|" + prev2AttrValue + "|"
            + prevAttrValue;
    String prevAttr5gramValue = prev5AttrValue + "|" + prev4AttrValue + "|" + prev3AttrValue + "|"
            + prev2AttrValue + "|" + prevAttrValue;

    generalFeatures.put("feature_attrValue_bigram_" + prevAttrBigramValue.toLowerCase(), 1.0);
    generalFeatures.put("feature_attrValue_trigram_" + prevAttrTrigramValue.toLowerCase(), 1.0);
    generalFeatures.put("feature_attrValue_4gram_" + prevAttr4gramValue.toLowerCase(), 1.0);
    generalFeatures.put("feature_attrValue_5gram_" + prevAttr5gramValue.toLowerCase(), 1.0);

    /*String bigramAttrValue54 = prev5AttrValue + "|" + prev4AttrValue;
    String bigramAttrValue43 = prev4AttrValue + "|" + prev3AttrValue;
    String bigramAttrValue32 = prev3AttrValue + "|" + prev2AttrValue;
    generalFeatures.put("feature_attrValue_bigramAttrValue54_" + bigramAttrValue54, 1.0);
    generalFeatures.put("feature_attrValue_bigramAttrValue43_" + bigramAttrValue43, 1.0);
    generalFeatures.put("feature_attrValue_bigramAttrValue32_" + bigramAttrValue32, 1.0);
            
    String bigramAttrValueSkip53 = prev5AttrValue + "|" + prev3AttrValue;
    String bigramAttrValueSkip42 = prev4AttrValue + "|" + prev2AttrValue;
    String bigramAttrValueSkip31 = prev3AttrValue + "|" + prevAttrValue;
    generalFeatures.put("feature_attrValue_bigramAttrValueSkip53_" + bigramAttrValueSkip53, 1.0);
    generalFeatures.put("feature_attrValue_bigramAttrValueSkip42_" + bigramAttrValueSkip42, 1.0);
    generalFeatures.put("feature_attrValue_bigramAttrValueSkip31_" + bigramAttrValueSkip31, 1.0);
            
    String trigramAttrValue543 = prev5AttrValue + "|" + prev4AttrValue + "|" + prev3AttrValue;
    String trigramAttrValue432 = prev4AttrValue + "|" + prev3AttrValue + "|" + prev2AttrValue;
    generalFeatures.put("feature_attrValue_trigramAttrValue543_" + trigramAttrValue543, 1.0);
    generalFeatures.put("feature_attrValue_trigramAttrValue432_" + trigramAttrValue432, 1.0);
            
    String trigramAttrValueSkip542 = prev5AttrValue + "|" + prev4AttrValue + "|" + prev2AttrValue;
    String trigramAttrValueSkip532 = prev5AttrValue + "|" + prev3AttrValue + "|" + prev2AttrValue;
    String trigramAttrValueSkip431 = prev4AttrValue + "|" + prev3AttrValue + "|" + prevAttrValue;
    String trigramAttrValueSkip421 = prev4AttrValue + "|" + prev2AttrValue + "|" + prevAttrValue;
    generalFeatures.put("feature_attrValue_trigramAttrValueSkip542_" + trigramAttrValueSkip542, 1.0);
    generalFeatures.put("feature_attrValue_trigramAttrValueSkip532_" + trigramAttrValueSkip532, 1.0);
    generalFeatures.put("feature_attrValue_trigramAttrValueSkip431_" + trigramAttrValueSkip431, 1.0);
    generalFeatures.put("feature_attrValue_trigramAttrValueSkip421_" + trigramAttrValueSkip421, 1.0);*/
    //Previous attr features
    for (int j = 1; j <= 1; j++) {
        String previousAttr = "@@";
        if (attributeSize - j >= 0) {
            if (generatedAttributes.get(attributeSize - j).contains("=")) {
                previousAttr = generatedAttributes.get(attributeSize - j).trim().substring(0,
                        generatedAttributes.get(attributeSize - j).indexOf('='));
            } else {
                previousAttr = generatedAttributes.get(attributeSize - j).trim();
            }
        }
        generalFeatures.put("feature_attr_" + j + "_" + previousAttr, 1.0);
    }
    String prevAttr = "@@";
    if (attributeSize - 1 >= 0) {
        if (generatedAttributes.get(attributeSize - 1).contains("=")) {
            prevAttr = generatedAttributes.get(attributeSize - 1).trim().substring(0,
                    generatedAttributes.get(attributeSize - 1).indexOf('='));
        } else {
            prevAttr = generatedAttributes.get(attributeSize - 1).trim();
        }
    }
    String prev2Attr = "@@";
    if (attributeSize - 2 >= 0) {
        if (generatedAttributes.get(attributeSize - 2).contains("=")) {
            prev2Attr = generatedAttributes.get(attributeSize - 2).trim().substring(0,
                    generatedAttributes.get(attributeSize - 2).indexOf('='));
        } else {
            prev2Attr = generatedAttributes.get(attributeSize - 2).trim();
        }
    }
    String prev3Attr = "@@";
    if (attributeSize - 3 >= 0) {
        if (generatedAttributes.get(attributeSize - 3).contains("=")) {
            prev3Attr = generatedAttributes.get(attributeSize - 3).trim().substring(0,
                    generatedAttributes.get(attributeSize - 3).indexOf('='));
        } else {
            prev3Attr = generatedAttributes.get(attributeSize - 3).trim();
        }
    }
    String prev4Attr = "@@";
    if (attributeSize - 4 >= 0) {
        if (generatedAttributes.get(attributeSize - 4).contains("=")) {
            prev4Attr = generatedAttributes.get(attributeSize - 4).trim().substring(0,
                    generatedAttributes.get(attributeSize - 4).indexOf('='));
        } else {
            prev4Attr = generatedAttributes.get(attributeSize - 4).trim();
        }
    }
    String prev5Attr = "@@";
    if (attributeSize - 5 >= 0) {
        if (generatedAttributes.get(attributeSize - 5).contains("=")) {
            prev5Attr = generatedAttributes.get(attributeSize - 5).trim().substring(0,
                    generatedAttributes.get(attributeSize - 5).indexOf('='));
        } else {
            prev5Attr = generatedAttributes.get(attributeSize - 5).trim();
        }
    }

    String prevAttrBigram = prev2Attr + "|" + prevAttr;
    String prevAttrTrigram = prev3Attr + "|" + prev2Attr + "|" + prevAttr;
    String prevAttr4gram = prev4Attr + "|" + prev3Attr + "|" + prev2Attr + "|" + prevAttr;
    String prevAttr5gram = prev5Attr + "|" + prev4Attr + "|" + prev3Attr + "|" + prev2Attr + "|" + prevAttr;

    generalFeatures.put("feature_attr_bigram_" + prevAttrBigram.toLowerCase(), 1.0);
    generalFeatures.put("feature_attr_trigram_" + prevAttrTrigram.toLowerCase(), 1.0);
    generalFeatures.put("feature_attr_4gram_" + prevAttr4gram.toLowerCase(), 1.0);
    generalFeatures.put("feature_attr_5gram_" + prevAttr5gram.toLowerCase(), 1.0);

    /*String bigramAttr54 = prev5Attr + "|" + prev4Attr;
    String bigramAttr43 = prev4Attr + "|" + prev3Attr;
    String bigramAttr32 = prev3Attr + "|" + prev2Attr;
    generalFeatures.put("feature_attr_bigramAttr54_" + bigramAttr54, 1.0);
    generalFeatures.put("feature_attr_bigramAttr43_" + bigramAttr43, 1.0);
    generalFeatures.put("feature_attr_bigramAttr32_" + bigramAttr32, 1.0);
            
    String bigramAttrSkip53 = prev5Attr + "|" + prev3Attr;
    String bigramAttrSkip42 = prev4Attr + "|" + prev2Attr;
    String bigramAttrSkip31 = prev3Attr + "|" + prevAttr;
    generalFeatures.put("feature_attr_bigramAttrSkip53_" + bigramAttrSkip53, 1.0);
    generalFeatures.put("feature_attr_bigramAttrSkip42_" + bigramAttrSkip42, 1.0);
    generalFeatures.put("feature_attr_bigramAttrSkip31_" + bigramAttrSkip31, 1.0);
            
    String trigramAttr543 = prev5Attr + "|" + prev4Attr + "|" + prev3Attr;
    String trigramAttr432 = prev4Attr + "|" + prev3Attr + "|" + prev2Attr;
    generalFeatures.put("feature_attr_trigramAttr543_" + trigramAttr543, 1.0);
    generalFeatures.put("feature_attr_trigramAttr432_" + trigramAttr432, 1.0);
            
    String trigramAttrSkip542 = prev5Attr + "|" + prev4Attr + "|" + prev2Attr;
    String trigramAttrSkip532 = prev5Attr + "|" + prev3Attr + "|" + prev2Attr;
    String trigramAttrSkip431 = prev4Attr + "|" + prev3Attr + "|" + prevAttr;
    String trigramAttrSkip421 = prev4Attr + "|" + prev2Attr + "|" + prevAttr;
    generalFeatures.put("feature_attr_trigramAttrSkip542_" + trigramAttrSkip542, 1.0);
    generalFeatures.put("feature_attr_trigramAttrSkip532_" + trigramAttrSkip532, 1.0);
    generalFeatures.put("feature_attr_trigramAttrSkip431_" + trigramAttrSkip431, 1.0);
    generalFeatures.put("feature_attr_trigramAttrSkip421_" + trigramAttrSkip421, 1.0);*/
    //Next attr features
    for (int j = 0; j < 1; j++) {
        String nextAttr = "@@";
        if (j < nextGeneratedAttributes.size()) {
            if (nextGeneratedAttributes.get(j).contains("=")) {
                nextAttr = nextGeneratedAttributes.get(j).trim().substring(0,
                        nextGeneratedAttributes.get(j).indexOf('='));
            } else {
                nextAttr = nextGeneratedAttributes.get(j).trim();
            }
        }
        generalFeatures.put("feature_nextAttr_" + j + "_" + nextAttr, 1.0);
    }
    String nextAttr = "@@";
    if (0 < nextGeneratedAttributes.size()) {
        if (nextGeneratedAttributes.get(0).contains("=")) {
            nextAttr = nextGeneratedAttributes.get(0).trim().substring(0,
                    nextGeneratedAttributes.get(0).indexOf('='));
        } else {
            nextAttr = nextGeneratedAttributes.get(0).trim();
        }
    }
    String next2Attr = "@@";
    if (1 < nextGeneratedAttributes.size()) {
        if (nextGeneratedAttributes.get(1).contains("=")) {
            next2Attr = nextGeneratedAttributes.get(1).trim().substring(0,
                    nextGeneratedAttributes.get(1).indexOf('='));
        } else {
            next2Attr = nextGeneratedAttributes.get(1).trim();
        }
    }
    String next3Attr = "@@";
    if (2 < nextGeneratedAttributes.size()) {
        if (nextGeneratedAttributes.get(2).contains("=")) {
            next3Attr = nextGeneratedAttributes.get(2).trim().substring(0,
                    nextGeneratedAttributes.get(2).indexOf('='));
        } else {
            next3Attr = nextGeneratedAttributes.get(2).trim();
        }
    }
    String next4Attr = "@@";
    if (3 < nextGeneratedAttributes.size()) {
        if (nextGeneratedAttributes.get(3).contains("=")) {
            next4Attr = nextGeneratedAttributes.get(3).trim().substring(0,
                    nextGeneratedAttributes.get(3).indexOf('='));
        } else {
            next4Attr = nextGeneratedAttributes.get(3).trim();
        }
    }
    String next5Attr = "@@";
    if (4 < nextGeneratedAttributes.size()) {
        if (nextGeneratedAttributes.get(4).contains("=")) {
            next5Attr = nextGeneratedAttributes.get(4).trim().substring(0,
                    nextGeneratedAttributes.get(4).indexOf('='));
        } else {
            next5Attr = nextGeneratedAttributes.get(4).trim();
        }
    }

    String nextAttrBigram = nextAttr + "|" + next2Attr;
    String nextAttrTrigram = nextAttr + "|" + next2Attr + "|" + next3Attr;
    String nextAttr4gram = nextAttr + "|" + next2Attr + "|" + next3Attr + "|" + next4Attr;
    String nextAttr5gram = nextAttr + "|" + next2Attr + "|" + next3Attr + "|" + next4Attr + "|" + next5Attr;

    generalFeatures.put("feature_nextAttr_bigram_" + nextAttrBigram.toLowerCase(), 1.0);
    generalFeatures.put("feature_nextAttr_trigram_" + nextAttrTrigram.toLowerCase(), 1.0);
    generalFeatures.put("feature_nextAttr_4gram_" + nextAttr4gram.toLowerCase(), 1.0);
    generalFeatures.put("feature_nextAttr_5gram_" + nextAttr5gram.toLowerCase(), 1.0);

    //Next attrValue features
    for (int j = 0; j < 1; j++) {
        String nextAttrValue = "@@";
        if (j < nextGeneratedAttributes.size()) {
            nextAttrValue = nextGeneratedAttributes.get(j).trim();
        }
        generalFeatures.put("feature_nextAttrValue_" + j + "_" + nextAttrValue, 1.0);
    }
    String nextAttrValue = "@@";
    if (0 < nextGeneratedAttributes.size()) {
        nextAttrValue = nextGeneratedAttributes.get(0).trim();
    }
    String next2AttrValue = "@@";
    if (1 < nextGeneratedAttributes.size()) {
        next2AttrValue = nextGeneratedAttributes.get(1).trim();
    }
    String next3AttrValue = "@@";
    if (2 < nextGeneratedAttributes.size()) {
        next3AttrValue = nextGeneratedAttributes.get(2).trim();
    }
    String next4AttrValue = "@@";
    if (3 < nextGeneratedAttributes.size()) {
        next4AttrValue = nextGeneratedAttributes.get(3).trim();
    }
    String next5AttrValue = "@@";
    if (4 < nextGeneratedAttributes.size()) {
        next5AttrValue = nextGeneratedAttributes.get(4).trim();
    }

    String nextAttrValueBigram = nextAttrValue + "|" + next2AttrValue;
    String nextAttrValueTrigram = nextAttrValue + "|" + next2AttrValue + "|" + next3AttrValue;
    String nextAttrValue4gram = nextAttrValue + "|" + next2AttrValue + "|" + next3AttrValue + "|"
            + next4AttrValue;
    String nextAttrValue5gram = nextAttrValue + "|" + next2AttrValue + "|" + next3AttrValue + "|"
            + next4AttrValue + "|" + next5AttrValue;

    generalFeatures.put("feature_nextAttrValue_bigram_" + nextAttrValueBigram.toLowerCase(), 1.0);
    generalFeatures.put("feature_nextAttrValue_trigram_" + nextAttrValueTrigram.toLowerCase(), 1.0);
    generalFeatures.put("feature_nextAttrValue_4gram_" + nextAttrValue4gram.toLowerCase(), 1.0);
    generalFeatures.put("feature_nextAttrValue_5gram_" + nextAttrValue5gram.toLowerCase(), 1.0);

    //If values have already been generated or not
    generalFeatures.put("feature_valueToBeMentioned_" + currentValue.toLowerCase(), 1.0);
    if (wasValueMentioned) {
        generalFeatures.put("feature_wasValueMentioned_true", 1.0);
    } else {
        //generalFeatures.put("feature_wasValueMentioned_false", 1.0);
    }
    HashSet<String> valuesThatFollow = new HashSet<>();
    attrValuesThatFollow.stream().map((attrValue) -> {
        generalFeatures.put("feature_attrValuesThatFollow_" + attrValue.toLowerCase(), 1.0);
        return attrValue;
    }).forEachOrdered((attrValue) -> {
        if (attrValue.contains("=")) {
            String v = attrValue.substring(attrValue.indexOf('=') + 1);
            if (v.matches("[xX][0-9]+")) {
                String attr = attrValue.substring(0, attrValue.indexOf('='));
                valuesThatFollow.add(Action.TOKEN_X + attr + "_" + v.substring(1));
            } else {
                valuesThatFollow.add(v);
            }
            generalFeatures.put(
                    "feature_attrsThatFollow_" + attrValue.substring(0, attrValue.indexOf('=')).toLowerCase(),
                    1.0);
        } else {
            generalFeatures.put("feature_attrsThatFollow_" + attrValue.toLowerCase(), 1.0);
        }
    });
    if (valuesThatFollow.isEmpty()) {
        generalFeatures.put("feature_noAttrsFollow", 1.0);
    } else {
        generalFeatures.put("feature_noAttrsFollow", 0.0);
    }
    HashSet<String> mentionedValues = new HashSet<>();
    attrValuesAlreadyMentioned.stream().map((attrValue) -> {
        generalFeatures.put("feature_attrValuesAlreadyMentioned_" + attrValue.toLowerCase(), 1.0);
        return attrValue;
    }).forEachOrdered((attrValue) -> {
        if (attrValue.contains("=")) {
            generalFeatures.put("feature_attrsAlreadyMentioned_"
                    + attrValue.substring(0, attrValue.indexOf('=')).toLowerCase(), 1.0);
            String v = attrValue.substring(attrValue.indexOf('=') + 1);
            if (v.matches("[xX][0-9]+")) {
                String attr = attrValue.substring(0, attrValue.indexOf('='));
                mentionedValues.add(Action.TOKEN_X + attr + "_" + v.substring(1));
            } else {
                mentionedValues.add(v);
            }
        } else {
            generalFeatures.put("feature_attrsAlreadyMentioned_" + attrValue.toLowerCase(), 1.0);
        }
    });

    /*System.out.println("currentAttrValue: " + currentAttrValue);
    System.out.println("5W: " + prev5gram);
    System.out.println("5AW: " + prevAttrWord5gram);
    System.out.println("5A: " + prevAttr5gram);
    System.out.println("VM: " + wasValueMentioned);
    System.out.println("A_TF: " + attrValuesThatFollow);
    System.out.println("==============================");*/
    if (currentValue.equals("no") || currentValue.equals("yes") || currentValue.equals("yes or no")
            || currentValue.equals("none") || currentValue.equals("empty") //|| currentValue.equals("dont_care")
    ) {
        generalFeatures.put("feature_emptyValue", 1.0);
    }

    //Word specific features (and also global features)
    for (Action action : availableWordActions.get(currentAttr)) {
        //Is word same as previous word
        if (prevWord.equals(action.getWord())) {
            //valueSpecificFeatures.get(action.getAction()).put("feature_specific_sameAsPreviousWord", 1.0);
            valueSpecificFeatures.get(action.getAction()).put("global_feature_specific_sameAsPreviousWord",
                    1.0);
        } else {
            //valueSpecificFeatures.get(action.getAction()).put("feature_specific_notSameAsPreviousWord", 1.0);
            valueSpecificFeatures.get(action.getAction()).put("global_feature_specific_notSameAsPreviousWord",
                    1.0);
        }
        //Has word appeared in the same attrValue before
        generatedWords.forEach((previousAction) -> {
            if (previousAction.getWord().equals(action.getWord())
                    && previousAction.getAttribute().equals(currentAttrValue)) {
                //valueSpecificFeatures.get(action.getAction()).put("feature_specific_appearedInSameAttrValue", 1.0);
                valueSpecificFeatures.get(action.getAction())
                        .put("global_feature_specific_appearedInSameAttrValue", 1.0);
            } else {
                //valueSpecificFeatures.get(action.getAction()).put("feature_specific_notAppearedInSameAttrValue", 1.0);
                //valueSpecificFeatures.get(action.getAction()).put("global_feature_specific_notAppearedInSameAttrValue", 1.0);
            }
        });
        //Has word appeared before
        generatedWords.forEach((previousAction) -> {
            if (previousAction.getWord().equals(action.getWord())) {
                //valueSpecificFeatures.get(action.getAction()).put("feature_specific_appeared", 1.0);
                valueSpecificFeatures.get(action.getAction()).put("global_feature_specific_appeared", 1.0);
            } else {
                //valueSpecificFeatures.get(action.getAction()).put("feature_specific_notAppeared", 1.0);
                //valueSpecificFeatures.get(action.getAction()).put("global_feature_specific_notAppeared", 1.0);
            }
        });
        if (currentValue.equals("no") || currentValue.equals("yes") || currentValue.equals("yes or no")
                || currentValue.equals("none") || currentValue.equals("empty") //|| currentValue.equals("dont_care")
        ) {
            //valueSpecificFeatures.get(action.getAction()).put("feature_specific_emptyValue", 1.0);
            valueSpecificFeatures.get(action.getAction()).put("global_feature_specific_emptyValue", 1.0);
        } else {
            //valueSpecificFeatures.get(action.getAction()).put("feature_specific_notEmptyValue", 1.0);
            //valueSpecificFeatures.get(action.getAction()).put("global_feature_specific_notEmptyValue", 1.0);
        }

        HashSet<String> keys = new HashSet<>(valueSpecificFeatures.get(action.getAction()).keySet());
        keys.forEach((feature1) -> {
            keys.stream()
                    .filter((feature2) -> (valueSpecificFeatures.get(action.getAction()).get(feature1) == 1.0
                            && valueSpecificFeatures.get(action.getAction()).get(feature2) == 1.0
                            && feature1.compareTo(feature2) < 0))
                    .forEachOrdered((feature2) -> {
                        valueSpecificFeatures.get(action.getAction()).put(feature1 + "&&" + feature2, 1.0);
                    });
        });

        if (!action.getWord().startsWith(Action.TOKEN_X) && !currentValue.equals("no")
                && !currentValue.equals("yes") && !currentValue.equals("yes or no")
                && !currentValue.equals("none") && !currentValue.equals("empty") //&& !currentValue.equals("dont_care")
        ) {
            for (String value : getValueAlignments().keySet()) {
                for (ArrayList<String> alignedStr : getValueAlignments().get(value).keySet()) {
                    if (alignedStr.get(0).equals(action.getWord())) {
                        if (mentionedValues.contains(value)) {
                            //valueSpecificFeatures.get(action.getAction()).put("feature_specific_beginsValue_alreadyMentioned", 1.0);
                            valueSpecificFeatures.get(action.getAction())
                                    .put("global_feature_specific_beginsValue_alreadyMentioned", 1.0);

                        } else if (currentValue.equals(value)) {
                            //valueSpecificFeatures.get(action.getAction()).put("feature_specific_beginsValue_current", 1.0);
                            valueSpecificFeatures.get(action.getAction())
                                    .put("global_feature_specific_beginsValue_current", 1.0);

                        } else if (valuesThatFollow.contains(value)) {
                            //valueSpecificFeatures.get(action.getAction()).put("feature_specific_beginsValue_thatFollows", 1.0);
                            valueSpecificFeatures.get(action.getAction())
                                    .put("global_feature_specific_beginsValue_thatFollows", 1.0);

                        } else {
                            //valueSpecificFeatures.get(action.getAction()).put("feature_specific_beginsValue_notInMR", 1.0);
                            valueSpecificFeatures.get(action.getAction())
                                    .put("global_feature_specific_beginsValue_notInMR", 1.0);

                        }
                    } else {
                        for (int i = 1; i < alignedStr.size(); i++) {
                            if (alignedStr.get(i).equals(action.getWord())) {
                                if (endsWith(generatedPhrase,
                                        new ArrayList<String>(alignedStr.subList(0, i + 1)))) {
                                    if (mentionedValues.contains(value)) {
                                        //valueSpecificFeatures.get(action.getAction()).put("feature_specific_inValue_alreadyMentioned", 1.0);
                                        valueSpecificFeatures.get(action.getAction())
                                                .put("global_feature_specific_inValue_alreadyMentioned", 1.0);

                                    } else if (currentValue.equals(value)) {
                                        //valueSpecificFeatures.get(action.getAction()).put("feature_specific_inValue_current", 1.0);
                                        valueSpecificFeatures.get(action.getAction())
                                                .put("global_feature_specific_inValue_current", 1.0);

                                    } else if (valuesThatFollow.contains(value)) {
                                        //valueSpecificFeatures.get(action.getAction()).put("feature_specific_inValue_thatFollows", 1.0);
                                        valueSpecificFeatures.get(action.getAction())
                                                .put("global_feature_specific_inValue_thatFollows", 1.0);

                                    } else {
                                        //valueSpecificFeatures.get(action.getAction()).put("feature_specific_inValue_notInMR", 1.0);
                                        valueSpecificFeatures.get(action.getAction())
                                                .put("global_feature_specific_inValue_notInMR", 1.0);

                                    }
                                } else {
                                    /*if (mentionedValues.contains(value)) {
                                    valueSpecificFeatures.get(action.getAction()).put("feature_specific_outOfValue_alreadyMentioned", 1.0);
                                    } else if (currentValue.equals(value)) {
                                    valueSpecificFeatures.get(action.getAction()).put("feature_specific_outOfValue_current", 1.0);
                                    } else if (valuesThatFollow.contains(value)) {
                                    valueSpecificFeatures.get(action.getAction()).put("feature_specific_outOfValue_thatFollows", 1.0);
                                    } else {
                                    valueSpecificFeatures.get(action.getAction()).put("feature_specific_outOfValue_notInMR", 1.0);
                                    }*/
                                    //valueSpecificFeatures.get(action.getAction()).put("feature_specific_outOfValue", 1.0);
                                    valueSpecificFeatures.get(action.getAction())
                                            .put("global_feature_specific_outOfValue", 1.0);
                                }
                            }
                        }
                    }
                }
            }
            if (action.getWord().equals(Action.TOKEN_END)) {
                if (generatedWordsInSameAttrValue.isEmpty()) {
                    //valueSpecificFeatures.get(action.getAction()).put("feature_specific_closingEmptyAttr", 1.0);
                    valueSpecificFeatures.get(action.getAction())
                            .put("global_feature_specific_closingEmptyAttr", 1.0);
                }
                if (!wasValueMentioned) {
                    //valueSpecificFeatures.get(action.getAction()).put("feature_specific_closingAttrWithValueNotMentioned", 1.0);
                    valueSpecificFeatures.get(action.getAction())
                            .put("global_feature_specific_closingAttrWithValueNotMentioned", 1.0);
                }

                // if (!prevCurrentAttrValueWord.equals("@@")) {
                if (!prevWord.equals("@@")) {
                    boolean alignmentIsOpen = false;
                    for (String value : getValueAlignments().keySet()) {
                        for (ArrayList<String> alignedStr : getValueAlignments().get(value).keySet()) {
                            for (int i = 0; i < alignedStr.size() - 1; i++) {
                                if (alignedStr.get(i).equals(prevWord) && endsWith(generatedPhrase,
                                        new ArrayList<>(alignedStr.subList(0, i + 1)))) {
                                    alignmentIsOpen = true;
                                }
                            }
                        }
                    }
                    if (alignmentIsOpen) {
                        // valueSpecificFeatures.get(action.getAction()).put("feature_specific_closingAttrWhileValueIsNotConcluded", 1.0);
                        valueSpecificFeatures.get(action.getAction())
                                .put("global_feature_specific_closingAttrWhileValueIsNotConcluded", 1.0);
                    }
                }
            }
        } else if (currentValue.equals("no") || currentValue.equals("yes") || currentValue.equals("yes or no")
                || currentValue.equals("none") || currentValue.equals("empty") //|| currentValue.equals("dont_care")
        ) {
            valueSpecificFeatures.get(action.getAction()).put("global_feature_specific_XValue_notInMR", 1.0);
        } else {
            String currentValueVariant = "";
            if (currentValue.matches("[xX][0-9]+")) {
                currentValueVariant = Action.TOKEN_X + currentAttr + "_" + currentValue.substring(1);
            }

            if (mentionedValues.contains(action.getWord())) {
                //valueSpecificFeatures.get(action.getAction()).put("feature_specific_XValue_alreadyMentioned", 1.0);
                valueSpecificFeatures.get(action.getAction())
                        .put("global_feature_specific_XValue_alreadyMentioned", 1.0);
            } else if (currentValueVariant.equals(action.getWord()) && !currentValueVariant.isEmpty()) {
                //valueSpecificFeatures.get(action.getAction()).put("feature_specific_XValue_current", 1.0);
                valueSpecificFeatures.get(action.getAction()).put("global_feature_specific_XValue_current",
                        1.0);

            } else if (valuesThatFollow.contains(action.getWord())) {
                //valueSpecificFeatures.get(action.getAction()).put("feature_specific_XValue_thatFollows", 1.0);
                valueSpecificFeatures.get(action.getAction()).put("global_feature_specific_XValue_thatFollows",
                        1.0);
            } else {
                //valueSpecificFeatures.get(action.getAction()).put("feature_specific_XValue_notInMR", 1.0);
                valueSpecificFeatures.get(action.getAction()).put("global_feature_specific_XValue_notInMR",
                        1.0);
            }
        }
        /*for (int i : nGrams.keySet()) {
        for (String nGram : nGrams.get(i)) {
        if (i == 2) {
        if (nGram.startsWith(prevWord + "|")
        && nGram.endsWith("|" + action.getAction())) {
        valueSpecificFeatures.get(action.getAction()).put("feature_specific_valuesFollowsPreviousWord", 1.0);
        }
        } else if (i == 3) {
        if (nGram.startsWith(prevBigram + "|")
        && nGram.endsWith("|" + action.getAction())) {
        valueSpecificFeatures.get(action.getAction()).put("feature_specific_valuesFollowsPreviousBigram", 1.0);
        }
        } else if (i == 4) {
        if (nGram.startsWith(prevTrigram + "|")
        && nGram.endsWith("|" + action.getAction())) {
        valueSpecificFeatures.get(action.getAction()).put("feature_specific_valuesFollowsPreviousTrigram", 1.0);
        }
        } else if (i == 5) {
        if (nGram.startsWith(prev4gram + "|")
        && nGram.endsWith("|" + action.getAction())) {
        valueSpecificFeatures.get(action.getAction()).put("feature_specific_valuesFollowsPrevious4gram", 1.0);
        }
        } else if (i == 6) {
        if (nGram.startsWith(prev5gram + "|")
        && nGram.endsWith("|" + action.getAction())) {
        valueSpecificFeatures.get(action.getAction()).put("feature_specific_valuesFollowsPrevious5gram", 1.0);
        }
        }
        }
        }*/

        //valueSpecificFeatures.get(action.getAction()).put("global_feature_abstractMR_" + mr.getAbstractMR(), 1.0);
        valueSpecificFeatures.get(action.getAction())
                .put("global_feature_currentValue_" + currentValue.toLowerCase(), 1.0);

        ArrayList<String> fullGramLM = new ArrayList<>();
        for (int i = 0; i < generatedWords.size(); i++) {
            fullGramLM.add(generatedWords.get(i).getWord());
        }

        ArrayList<String> prev5wordGramLM = new ArrayList<>();
        int j = 0;
        for (int i = generatedWords.size() - 1; (i >= 0 && j < 5); i--) {
            prev5wordGramLM.add(0, generatedWords.get(i).getWord());
            j++;
        }
        prev5wordGramLM.add(action.getWord());
        while (prev5wordGramLM.size() < 4) {
            prev5wordGramLM.add(0, "@@");
        }

        double afterLMScorePerPred5Gram = getWordLMsPerPredicate().get(predicate)
                .getProbability(prev5wordGramLM);
        valueSpecificFeatures.get(action.getAction()).put("global_feature_LMWord_perPredicate_5gram_score",
                afterLMScorePerPred5Gram);

        double afterLMScorePerPred = getWordLMsPerPredicate().get(predicate).getProbability(fullGramLM);
        valueSpecificFeatures.get(action.getAction()).put("global_feature_LMWord_perPredicate_score",
                afterLMScorePerPred);
    }

    /*HashSet<String> keys = new HashSet<>(generalFeatures.keySet());
    for (String feature1 : keys) {
    if (generalFeatures.get(feature1) == 1.0) {
        generalFeatures.put("global_feature_attr_" + currentValue.toLowerCase() + "&&" + feature1, 1.0);
    }
    }*/
    //generalFeatures.put("feature_abstractMR_" + mr.getAbstractMR(), 1.0);

    /*HashSet<String> keys = new HashSet<>(generalFeatures.keySet());
    for (String feature1 : keys) {
    for (String feature2 : keys) {
    if (generalFeatures.get(feature1) == 1.0
    && generalFeatures.get(feature2) == 1.0
    && feature1.compareTo(feature2) < 0) {
    generalFeatures.put(feature1 + "&&" + feature2, 1.0);
    }
    }
    }*/
    return new Instance(generalFeatures, valueSpecificFeatures, costs);
}

From source file:com.ah.ui.actions.hiveap.HiveApUpdateAction.java

private String checkPortProfile(ConfigTemplate wlanPolicy, HiveAp oneHiveAp, HashSet<String> ssidNames) {
    // check the duplicate name for both Access and SSID
    if (null != wlanPolicy && null != wlanPolicy.getAccessProfiles()) {
        for (PortAccessProfile access : wlanPolicy.getAccessProfiles()) {
            if (null != access) {
                if (!ssidNames.isEmpty() && ssidNames.contains(access.getName())) {
                    return getText("error.config.networkPolicy.check.cannotsame",
                            new String[] { access.getName(), wlanPolicy.getConfigName() });
                }/* www . ja va  2  s . co m*/
            }
        }
    }
    //Port Template Profiles
    //validate only "Use external DHCP and DNS servers on the network" is supported on switch ports.
    if (null != wlanPolicy && null != wlanPolicy.getPortProfiles()) {
        Set<PortGroupProfile> pgps = wlanPolicy.getPortProfiles();
        for (PortGroupProfile pgp : pgps) {
            if (pgp.getDeviceType() != oneHiveAp.getDeviceType()) {
                continue;
            }
            String[] models = pgp.getDeviceModelStrs();
            if (models == null) {
                continue;
            }
            boolean continueOp = true;
            for (String key : models) {
                if (key.equals(String.valueOf(oneHiveAp.getHiveApModel()))) {
                    continueOp = false;
                }
            }
            if (continueOp) {
                continue;
            }

            if (isSwitchTypeForDevice(oneHiveAp)) {
                // init usb count
                int wanCount = 1;
                int mirrorCount = 0;
                if (oneHiveAp.isSwitch()) {
                    if (null != pgp.getBasicProfiles()) {
                        for (PortBasicProfile pbp : pgp.getBasicProfiles()) {
                            if (pbp.getAccessProfile().getPortType() == PortAccessProfile.PORT_TYPE_WAN) {
                                return getText("error.config.networkPolicy.check.connotConfig3Args",
                                        new String[] { "WAN type", "switch port", wlanPolicy.getConfigName() });
                            }
                            if (pbp.getAccessProfile().getPortType() == PortAccessProfile.PORT_TYPE_MONITOR) {
                                if (pbp.getSFPs() != null) {
                                    mirrorCount = mirrorCount + pbp.getSFPs().length;
                                }
                                if (pbp.getETHs() != null) {
                                    mirrorCount = mirrorCount + pbp.getETHs().length;
                                }
                            }
                        }
                    }
                    if (mirrorCount > 4) {
                        return getText("error.config.networkPolicy.check.moreport",
                                new String[] { "4", "mirror type", wlanPolicy.getConfigName() });
                    }
                } else {
                    if (null != pgp.getBasicProfiles()) {
                        for (PortBasicProfile pbp : pgp.getBasicProfiles()) {
                            if (pbp.getAccessProfile().getPortType() == PortAccessProfile.PORT_TYPE_WAN) {
                                //                             if (pbp.getSFPs()!=null && pbp.getSFPs().length>0) {
                                //                                return getText("error.config.networkPolicy.check.connotConfig",
                                //                                       new String[]{"WAN type","SFP port",
                                //                                       wlanPolicy.getConfigName()});
                                //                             }
                                if (pbp.getSFPs() != null) {
                                    wanCount = wanCount + pbp.getSFPs().length;
                                }
                                if (pbp.getETHs() != null) {
                                    wanCount = wanCount + pbp.getETHs().length;
                                }
                                //                             if (pbp.getUSBs()!=null) {
                                //                                wanCount = wanCount + pbp.getUSBs().length;
                                //                             } else {
                                //                                // USB will taken one wan port
                                //                                wanCount = wanCount + 1;
                                //                             }
                            } else {
                                if (pbp.getUSBs() != null && pbp.getUSBs().length > 0) {
                                    return getText("error.config.networkPolicy.check.mustConfig", new String[] {
                                            "USB port", "WAN type", wlanPolicy.getConfigName() });
                                }
                            }
                            if (pbp.getAccessProfile().getPortType() == PortAccessProfile.PORT_TYPE_MONITOR) {
                                if (pbp.getSFPs() != null) {
                                    mirrorCount = mirrorCount + pbp.getSFPs().length;
                                }
                                if (pbp.getETHs() != null) {
                                    mirrorCount = mirrorCount + pbp.getETHs().length;
                                }
                            }
                        }
                    }
                    if (wanCount > 3) {
                        return getText("error.config.networkPolicy.check.moreport",
                                new String[] { "3", "WAN type", wlanPolicy.getConfigName() });
                    }
                    if (mirrorCount > 4) {
                        return getText("error.config.networkPolicy.check.moreport",
                                new String[] { "4", "mirror type", wlanPolicy.getConfigName() });
                    }
                }
            } else if (oneHiveAp.isBranchRouter()) {
                int wanCount = 2;
                if (null != pgp.getBasicProfiles()) {
                    for (PortBasicProfile pbp : pgp.getBasicProfiles()) {
                        if (pbp.getAccessProfile().getPortType() == PortAccessProfile.PORT_TYPE_WAN) {
                            //wanCount = wanCount + 1;
                            if (pbp.getETHs() != null) {
                                wanCount = wanCount + pbp.getETHs().length;
                            }
                            //                         if (pbp.getUSBs()!=null) {
                            //                            wanCount = wanCount + pbp.getUSBs().length;
                            //                         } else {
                            //                            // USB will taken one wan port
                            //                            wanCount = wanCount + 1;
                            //                         }
                        } else {
                            if (pbp.getUSBs() != null && pbp.getUSBs().length > 0) {
                                return getText("error.config.networkPolicy.check.mustConfig",
                                        new String[] { "USB port", "WAN type", wlanPolicy.getConfigName() });
                            }
                        }
                    }
                }
                if (wanCount > 3) {
                    return getText("error.config.networkPolicy.check.moreport",
                            new String[] { "2", "WAN type", wlanPolicy.getConfigName() });
                }
            }

            if (null != pgp.getBasicProfiles()) {
                for (PortBasicProfile pbp : pgp.getBasicProfiles()) {
                    if (null != pbp.getAccessProfile()) {
                        if (pbp.getAccessProfile().getPortType() == PortAccessProfile.PORT_TYPE_MONITOR
                                || pbp.getAccessProfile().getPortType() == PortAccessProfile.PORT_TYPE_WAN) {
                            continue;
                        }
                        if (pbp.getAccessProfile().isEnabledCWP()) {
                            if (pbp.getAccessProfile().getCwp() == null) {
                                return getText("error.config.networkPolicy.check.mustConfig",
                                        new String[] { "CWP",
                                                "Port Type (" + pbp.getAccessProfile().getName() + ")",
                                                wlanPolicy.getConfigName() });
                            } else {
                                if (isSwitchTypeForDevice(oneHiveAp)) {
                                    if (pbp.getAccessProfile().isEnabledCWP()) {
                                        if (null != pbp.getAccessProfile().getCwp() && pbp.getAccessProfile()
                                                .getCwp().getServerType() != Cwp.CWP_EXTERNAL) {
                                            return getText("error.port.access.dhcp.server.type",
                                                    new String[] { "Port Type ("
                                                            + pbp.getAccessProfile().getName() + ")",
                                                            wlanPolicy.getConfigName() });
                                        }
                                    }
                                }
                            }
                        }

                        if (pbp.getAccessProfile().getPortType() == PortAccessProfile.PORT_TYPE_8021Q) {
                            if (pbp.getAccessProfile().getNativeVlan() == null) {
                                return getText("error.config.networkPolicy.check.mustConfig",
                                        new String[] { "Native VLAN",
                                                "Port Type (" + pbp.getAccessProfile().getName() + ")",
                                                wlanPolicy.getConfigName() });
                            }
                        } else {
                            if (pbp.getAccessProfile().isEnabled8021X() || pbp.getAccessProfile().isEnabledMAC()
                                    || (pbp.getAccessProfile().isEnabledCWP() && (pbp.getAccessProfile()
                                            .getCwp()
                                            .getRegistrationType() == Cwp.REGISTRATION_TYPE_AUTHENTICATED
                                            || pbp.getAccessProfile().getCwp()
                                                    .getRegistrationType() == Cwp.REGISTRATION_TYPE_BOTH
                                            || pbp.getAccessProfile().getCwp()
                                                    .getRegistrationType() == Cwp.REGISTRATION_TYPE_EXTERNAL))) {
                                if (pbp.getAccessProfile().getRadiusAssignment() == null
                                        && !pbp.getAccessProfile().isEnabledIDM()) {
                                    return getText("error.config.networkPolicy.check.mustConfig",
                                            new String[] { "RADIUS Server",
                                                    "Port Type (" + pbp.getAccessProfile().getName() + ")",
                                                    wlanPolicy.getConfigName() });
                                }
                                if (pbp.getAccessProfile().isEnableAssignUserProfile()) {
                                    if (pbp.getAccessProfile().getRadiusUserGroups() != null) {
                                        if (pbp.getAccessProfile().getRadiusUserGroups().isEmpty()) {
                                            return getText("error.config.networkPolicy.check.mustConfig",
                                                    new String[] {
                                                            "RADIUS User Groups", "Port Type ("
                                                                    + pbp.getAccessProfile().getName() + ")",
                                                            wlanPolicy.getConfigName() });
                                        }
                                    }
                                }
                            }

                            if (pbp.getAccessProfile().getRadiusAssignment() != null) {
                                if (pbp.getAccessProfile().getDefUserProfile() == null) {
                                    return getText("error.config.networkPolicy.check.mustConfig",
                                            new String[] { "default User Profile",
                                                    "Port Type (" + pbp.getAccessProfile().getName() + ")",
                                                    wlanPolicy.getConfigName() });
                                }
                                if (pbp.getAccessProfile().isEnabledCWP() && pbp.getAccessProfile().getCwp()
                                        .getRegistrationType() == Cwp.REGISTRATION_TYPE_BOTH) {
                                    if (pbp.getAccessProfile().getSelfRegUserProfile() == null) {
                                        return getText("error.config.networkPolicy.check.mustConfig",
                                                new String[] { "registration User Profile",
                                                        "Port Type (" + pbp.getAccessProfile().getName() + ")",
                                                        wlanPolicy.getConfigName() });
                                    }
                                }
                            } else {
                                if (pbp.getAccessProfile().isEnabledCWP() && pbp.getAccessProfile().getCwp()
                                        .getRegistrationType() == Cwp.REGISTRATION_TYPE_REGISTERED) {
                                    if (pbp.getAccessProfile().getSelfRegUserProfile() == null) {
                                        return getText("error.config.networkPolicy.check.mustConfig",
                                                new String[] { "registration User Profile",
                                                        "Port Type (" + pbp.getAccessProfile().getName() + ")",
                                                        wlanPolicy.getConfigName() });
                                    }
                                } else {
                                    if (pbp.getAccessProfile().getDefUserProfile() == null) {
                                        return getText("error.config.networkPolicy.check.mustConfig",
                                                new String[] { "default User Profile",
                                                        "Port Type (" + pbp.getAccessProfile().getName() + ")",
                                                        wlanPolicy.getConfigName() });
                                    }

                                    if (pbp.getAccessProfile()
                                            .getPortType() == PortAccessProfile.PORT_TYPE_PHONEDATA) {
                                        if (!pbp.getAccessProfile().isRadiusAuthEnable()) {
                                            if (pbp.getAccessProfile().getDataVlan() == null
                                                    && pbp.getAccessProfile().getVoiceVlan() == null) {
                                                return getText("error.config.networkPolicy.check.mustConfig",
                                                        new String[] { "Voice VLAN and Data VLAN", "Port Type ("
                                                                + pbp.getAccessProfile().getName() + ")",
                                                                wlanPolicy.getConfigName() });
                                            } else if (pbp.getAccessProfile().getDataVlan() == null) {
                                                return getText("error.config.networkPolicy.check.mustConfig",
                                                        new String[] { "Data VLAN", "Port Type ("
                                                                + pbp.getAccessProfile().getName() + ")",
                                                                wlanPolicy.getConfigName() });
                                            } else if (pbp.getAccessProfile().getVoiceVlan() == null) {
                                                return getText("error.config.networkPolicy.check.mustConfig",
                                                        new String[] { "Voice VLAN", "Port Type ("
                                                                + pbp.getAccessProfile().getName() + ")",
                                                                wlanPolicy.getConfigName() });
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return "";
}

From source file:edu.ucla.cs.scai.canali.core.index.utils.BiomedicalOntologyUtils.java

private void loadLabelsAndClasses() throws IOException {
    String regex = "(\\s|\\t)*<([^<>]*)>(\\s|\\t)*<([^<>]*)>(\\s|\\t)*(<|\")(.*)(>|\")";
    Pattern p = Pattern.compile(regex);
    for (String fileName : fileNames) {
        try (BufferedReader in = new BufferedReader(new FileReader(downloadedFilesPath + fileName))) {
            String l;//from  w ww . ja  va2  s .co  m
            while ((l = in.readLine()) != null) {
                Matcher m = p.matcher(l);
                if (m.find()) {
                    String a = m.group(4);
                    String s = m.group(2);
                    String v = m.group(7);
                    if (a.equals("http://www.w3.org/2000/01/rdf-schema#label")) {
                        if (classIds.get(s) != null) {
                            s = classById[equivalentClass[classIds.get(s)]];
                            HashSet<String> labels = classLabels.get(s);
                            if (labels == null) {
                                labels = new HashSet<>();
                                classLabels.put(s, labels);
                            }
                            labels.add(fromCamelCaseOrUnderscore(v));
                        } else if (propertyIds.get(s) != null) {
                            s = propertyById[equivalentProperty[propertyIds.get(s)]];
                            HashSet<String> labels = propertyLabels.get(s);
                            if (labels == null) {
                                labels = new HashSet<>();
                                propertyLabels.put(s, labels);
                            }
                            labels.add(fromCamelCaseOrUnderscore(v));
                        } else if (entityIds.get(s) != null) {
                            s = entityById[sameAs[entityIds.get(s)]];
                            HashSet<String> labels = entityLabels.get(s);
                            if (labels == null) {
                                labels = new HashSet<>();
                                entityLabels.put(s, labels);
                            }
                            labels.add(fromCamelCaseOrUnderscore(v));
                        } else {
                            System.out.println("Subject unknown in " + l);
                        }
                    } else if (a.equals("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")) {
                        if (entityIds.get(s) != null) {
                            s = entityById[sameAs[entityIds.get(s)]];
                            if (classIds.get(v) != null) {
                                HashSet<String> classes = entityClasses.get(s);
                                if (classes == null) {
                                    classes = new HashSet<>();
                                    entityClasses.put(s, classes);
                                }
                                v = classById[equivalentClass[classIds.get(v)]];
                                classes.add(v);
                            } else {
                                if (!v.equals("http://www.w3.org/1999/02/22-rdf-syntax-ns#Property")
                                        && !v.equals("http://www.w3.org/2000/01/rdf-schema#Class")) {
                                    System.out.println("Value unknown in " + l);
                                }
                            }
                        } else {
                            if (!v.equals("http://www.w3.org/1999/02/22-rdf-syntax-ns#Property")
                                    && !v.equals("http://www.w3.org/2000/01/rdf-schema#Class")) {
                                System.out.println("Subject unknown in " + l);
                            }
                        }
                    }

                    //System.out.println("Skipped " + l + " for invalid subject: " + s);
                    l = in.readLine();
                }
            }
        }
    }
    //now manually add some labels

    String[] additionalLabels = new String[] {
            "http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/targets\ttarget",
            "http://www4.wiwiss.fu-berlin.de/diseasome/resource/diseasome/genes\tgene",
            "http://www4.wiwiss.fu-berlin.de/sider/resource/sider/drugs\tdrug",
            //"http://www4.wiwiss.fu-berlin.de/drugbank/vocab/resource/class/Offer\toffer",
            "http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/references\treference",
            "http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/drugs\tdrug",
            "http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/drug_interactions\tdrug interaction",
            "http://www4.wiwiss.fu-berlin.de/sider/resource/sider/side_effects\tside effect",
            "http://www4.wiwiss.fu-berlin.de/diseasome/resource/diseasome/diseases\tdisease",
            "http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/enzymes\tenzyme" };

    for (String pair : additionalLabels) {
        String[] st = pair.split("\t");
        String s = classById[equivalentClass[classIds.get(st[0])]];
        HashSet<String> labels = classLabels.get(s);
        if (labels == null) {
            labels = new HashSet<>();
            classLabels.put(s, labels);
        }
        labels.add(st[1]);
    }

    //now process additional property labels file
    /*
     try (BufferedReader in = new BufferedReader(new FileReader(downloadedFilesPath + "additional_property_labels"))) {
     String l;
     while ((l = in.readLine()) != null) {
     StringTokenizer st = new StringTokenizer(l, " \t");
     String prop=st.nextToken();
     String lab=st.nextToken();
     String suffix="";
     if (prop.endsWith("Inv")) {
     prop=prop.substring(0, prop.length()-3);
     suffix="Inv";
     }
     prop = propertyById[equivalentProperty[propertyIds.get(prop)]]+suffix;
     HashSet<String> labels = propertyLabels.get(prop);
     if (labels == null) {
     labels = new HashSet<>();
     propertyLabels.put(prop, labels);
     }
     labels.add(fromCamelCaseOrUnderscore(lab));
     }
     } catch (Exception e) {
     e.printStackTrace();
     }
     */
    //now extract a label from the URI of properties
    for (int i = 1; i < propertyById.length; i++) {
        String s = propertyById[i];
        if (s.equals("http://www.w3.org/2000/01/rdf-schema#seeAlso")
                || s.equals("http://xmlns.com/foaf/0.1/page")) {
            continue;
        }
        String[] ss = s.split("\\/");
        String l = ss[ss.length - 1].replaceAll("\\_", " ");
        s = propertyById[equivalentProperty[propertyIds.get(s)]];
        HashSet<String> labels = propertyLabels.get(s);
        if (labels == null) {
            labels = new HashSet<>();
            propertyLabels.put(s, labels);
        }
        if (labels.isEmpty()) {
            l = fromCamelCaseOrUnderscore(l).toLowerCase();
            System.out.println("Artificial label " + l + " for property " + s);
            labels.add(l);
        }
    }

    //now extract a label from the URI of entities
    for (int i = 1; i < entityById.length; i++) {
        String s = entityById[i];
        String[] ss = s.split("\\/");
        String l = ss[ss.length - 1].replaceAll("\\_", " ");
        s = entityById[sameAs[entityIds.get(s)]];
        HashSet<String> labels = entityLabels.get(s);
        if (labels == null) {
            labels = new HashSet<>();
            entityLabels.put(s, labels);
        }
        if (labels.isEmpty()) {
            l = fromCamelCaseOrUnderscore(l).toLowerCase();
            System.out.println("Artificial label " + l + " for entity " + s);
            labels.add(l); //todo: handle camel case
        }
    }
}

From source file:structuredPredictionNLG.SFX.java

/**
 *
 * @param predicate//from   w w w . jav  a 2s .  c  o m
 * @param costs
 * @param previousGeneratedAttrs
 * @param attrValuesAlreadyMentioned
 * @param attrValuesToBeMentioned
 * @param availableAttributeActions
 * @param MR
 * @return
 */
@Override
public Instance createContentInstanceWithCosts(String predicate, TObjectDoubleHashMap<String> costs,
        ArrayList<String> previousGeneratedAttrs, HashSet<String> attrValuesAlreadyMentioned,
        HashSet<String> attrValuesToBeMentioned, HashMap<String, HashSet<String>> availableAttributeActions,
        MeaningRepresentation MR) {
    TObjectDoubleHashMap<String> generalFeatures = new TObjectDoubleHashMap<>();
    HashMap<String, TObjectDoubleHashMap<String>> valueSpecificFeatures = new HashMap<>();
    if (availableAttributeActions.containsKey(predicate)) {
        availableAttributeActions.get(predicate).forEach((action) -> {
            valueSpecificFeatures.put(action, new TObjectDoubleHashMap<String>());
        });
    }

    ArrayList<String> mentionedAttrValues = new ArrayList<>();
    previousGeneratedAttrs.stream().filter(
            (attrValue) -> (!attrValue.equals(Action.TOKEN_START) && !attrValue.equals(Action.TOKEN_END)))
            .forEachOrdered((attrValue) -> {
                mentionedAttrValues.add(attrValue);
            });

    for (int j = 1; j <= 1; j++) {
        String previousAttrValue = "@@";
        if (mentionedAttrValues.size() - j >= 0) {
            previousAttrValue = mentionedAttrValues.get(mentionedAttrValues.size() - j).trim();
        }
        generalFeatures.put("feature_attrValue_" + j + "_" + previousAttrValue, 1.0);
    }
    //Word N-Grams
    String prevAttrValue = "@@";
    if (mentionedAttrValues.size() - 1 >= 0) {
        prevAttrValue = mentionedAttrValues.get(mentionedAttrValues.size() - 1).trim();
    }
    String prev2AttrValue = "@@";
    if (mentionedAttrValues.size() - 2 >= 0) {
        prev2AttrValue = mentionedAttrValues.get(mentionedAttrValues.size() - 2).trim();
    }
    String prev3AttrValue = "@@";
    if (mentionedAttrValues.size() - 3 >= 0) {
        prev3AttrValue = mentionedAttrValues.get(mentionedAttrValues.size() - 3).trim();
    }
    String prev4AttrValue = "@@";
    if (mentionedAttrValues.size() - 4 >= 0) {
        prev4AttrValue = mentionedAttrValues.get(mentionedAttrValues.size() - 4).trim();
    }
    String prev5AttrValue = "@@";
    if (mentionedAttrValues.size() - 5 >= 0) {
        prev5AttrValue = mentionedAttrValues.get(mentionedAttrValues.size() - 5).trim();
    }

    String prevBigramAttrValue = prev2AttrValue + "|" + prevAttrValue;
    String prevTrigramAttrValue = prev3AttrValue + "|" + prev2AttrValue + "|" + prevAttrValue;
    String prev4gramAttrValue = prev4AttrValue + "|" + prev3AttrValue + "|" + prev2AttrValue + "|"
            + prevAttrValue;
    String prev5gramAttrValue = prev5AttrValue + "|" + prev4AttrValue + "|" + prev3AttrValue + "|"
            + prev2AttrValue + "|" + prevAttrValue;
    generalFeatures.put("feature_attrValue_bigram_" + prevBigramAttrValue, 1.0);
    generalFeatures.put("feature_attrValue_trigram_" + prevTrigramAttrValue, 1.0);
    generalFeatures.put("feature_attrValue_4gram_" + prev4gramAttrValue, 1.0);
    generalFeatures.put("feature_attrValue_5gram_" + prev5gramAttrValue, 1.0);

    //If arguments have been generated or not
    for (int i = 0; i < mentionedAttrValues.size(); i++) {
        generalFeatures.put("feature_attrValue_allreadyMentioned_" + mentionedAttrValues.get(i), 1.0);
    }
    //If arguments should still be generated or not
    attrValuesToBeMentioned.forEach((attrValue) -> {
        generalFeatures.put("feature_attrValue_toBeMentioned_" + attrValue, 1.0);
    }); //Which attrs are in the MR and which are not

    if (availableAttributeActions.containsKey(predicate)) {
        availableAttributeActions.get(predicate).forEach((attribute) -> {
            if (MR.getAttributeValues().keySet().contains(attribute)) {
                generalFeatures.put("feature_attr_inMR_" + attribute, 1.0);
            } else {
                generalFeatures.put("feature_attr_notInMR_" + attribute, 1.0);
            }
        });
    }

    ArrayList<String> mentionedAttrs = new ArrayList<>();
    for (int i = 0; i < mentionedAttrValues.size(); i++) {
        String attr = mentionedAttrValues.get(i);
        if (attr.contains("=")) {
            attr = mentionedAttrValues.get(i).substring(0, mentionedAttrValues.get(i).indexOf('='));
        }
        mentionedAttrs.add(attr);
    }
    HashSet<String> attrsToBeMentioned = new HashSet<>();
    attrValuesToBeMentioned.stream().map((attrValue) -> {
        String attr = attrValue;
        if (attr.contains("=")) {
            attr = attrValue.substring(0, attrValue.indexOf('='));
        }
        return attr;
    }).forEachOrdered((attr) -> {
        attrsToBeMentioned.add(attr);
    });

    for (int j = 1; j <= 1; j++) {
        String previousAttr = "";
        if (mentionedAttrs.size() - j >= 0) {
            previousAttr = mentionedAttrs.get(mentionedAttrs.size() - j).trim();
        }
        if (!previousAttr.isEmpty()) {
            generalFeatures.put("feature_attr_" + j + "_" + previousAttr, 1.0);
        } else {
            generalFeatures.put("feature_attr_" + j + "_@@", 1.0);
        }
    }
    //Word N-Grams
    String prevAttr = "@@";
    if (mentionedAttrs.size() - 1 >= 0) {
        prevAttr = mentionedAttrs.get(mentionedAttrs.size() - 1).trim();
    }
    String prev2Attr = "@@";
    if (mentionedAttrs.size() - 2 >= 0) {
        prev2Attr = mentionedAttrs.get(mentionedAttrs.size() - 2).trim();
    }
    String prev3Attr = "@@";
    if (mentionedAttrs.size() - 3 >= 0) {
        prev3Attr = mentionedAttrs.get(mentionedAttrs.size() - 3).trim();
    }
    String prev4Attr = "@@";
    if (mentionedAttrs.size() - 4 >= 0) {
        prev4Attr = mentionedAttrs.get(mentionedAttrs.size() - 4).trim();
    }
    String prev5Attr = "@@";
    if (mentionedAttrs.size() - 5 >= 0) {
        prev5Attr = mentionedAttrs.get(mentionedAttrs.size() - 5).trim();
    }

    String prevBigramAttr = prev2Attr + "|" + prevAttr;
    String prevTrigramAttr = prev3Attr + "|" + prev2Attr + "|" + prevAttr;
    String prev4gramAttr = prev4Attr + "|" + prev3Attr + "|" + prev2Attr + "|" + prevAttr;
    String prev5gramAttr = prev5Attr + "|" + prev4Attr + "|" + prev3Attr + "|" + prev2Attr + "|" + prevAttr;

    generalFeatures.put("feature_attr_bigram_" + prevBigramAttr, 1.0);
    generalFeatures.put("feature_attr_trigram_" + prevTrigramAttr, 1.0);
    generalFeatures.put("feature_attr_4gram_" + prev4gramAttr, 1.0);
    generalFeatures.put("feature_attr_5gram_" + prev5gramAttr, 1.0);

    //If arguments have been generated or not
    attrValuesAlreadyMentioned.forEach((attr) -> {
        generalFeatures.put("feature_attr_alreadyMentioned_" + attr, 1.0);
    });
    //If arguments should still be generated or not
    attrsToBeMentioned.forEach((attr) -> {
        generalFeatures.put("feature_attr_toBeMentioned_" + attr, 1.0);
    });

    //Attr specific features (and global features)
    if (availableAttributeActions.containsKey(predicate)) {
        for (String action : availableAttributeActions.get(predicate)) {
            if (action.equals(Action.TOKEN_END)) {
                if (attrsToBeMentioned.isEmpty()) {
                    valueSpecificFeatures.get(action).put("global_feature_specific_allAttrValuesMentioned",
                            1.0);
                } else {
                    valueSpecificFeatures.get(action).put("global_feature_specific_allAttrValuesNotMentioned",
                            1.0);
                }
            } else {
                //Is attr in MR?
                if (MR.getAttributeValues().get(action) != null) {
                    valueSpecificFeatures.get(action).put("global_feature_specific_isInMR", 1.0);
                } else {
                    valueSpecificFeatures.get(action).put("global_feature_specific_isNotInMR", 1.0);
                }
                //Is attr already mentioned right before
                if (prevAttr.equals(action)) {
                    valueSpecificFeatures.get(action).put("global_feature_specific_attrFollowingSameAttr", 1.0);
                } else {
                    valueSpecificFeatures.get(action).put("global_feature_specific_attrNotFollowingSameAttr",
                            1.0);
                }
                //Is attr already mentioned
                attrValuesAlreadyMentioned.stream().map((attrValue) -> {
                    if (attrValue.indexOf('=') == -1) {
                    }
                    return attrValue;
                }).filter((attrValue) -> (attrValue.substring(0, attrValue.indexOf('=')).equals(action)))
                        .forEachOrdered((_item) -> {
                            valueSpecificFeatures.get(action)
                                    .put("global_feature_specific_attrAlreadyMentioned", 1.0);
                        });
                //Is attr to be mentioned (has value to express)
                boolean toBeMentioned = false;
                for (String attrValue : attrValuesToBeMentioned) {
                    if (attrValue.substring(0, attrValue.indexOf('=')).equals(action)) {
                        toBeMentioned = true;
                        valueSpecificFeatures.get(action).put("global_feature_specific_attrToBeMentioned", 1.0);
                    }
                }
                if (!toBeMentioned) {
                    valueSpecificFeatures.get(action).put("global_feature_specific_attrNotToBeMentioned", 1.0);
                }
            }
            HashSet<String> keys = new HashSet<>(valueSpecificFeatures.get(action).keySet());
            keys.forEach((feature1) -> {
                keys.stream()
                        .filter((feature2) -> (valueSpecificFeatures.get(action).get(feature1) == 1.0
                                && valueSpecificFeatures.get(action).get(feature2) == 1.0
                                && feature1.compareTo(feature2) < 0))
                        .forEachOrdered((feature2) -> {
                            valueSpecificFeatures.get(action).put(feature1 + "&&" + feature2, 1.0);
                        });
            });

            String nextValue = chooseNextValue(action, attrValuesToBeMentioned);
            if (nextValue.isEmpty() && !action.equals(Action.TOKEN_END)) {
                valueSpecificFeatures.get(action).put("global_feature_LMAttr_score", 0.0);
            } else {
                ArrayList<String> fullGramLM = new ArrayList<>();
                for (int i = 0; i < mentionedAttrValues.size(); i++) {
                    fullGramLM.add(mentionedAttrValues.get(i));
                }
                ArrayList<String> prev5attrValueGramLM = new ArrayList<>();
                int j = 0;
                for (int i = mentionedAttrValues.size() - 1; (i >= 0 && j < 5); i--) {
                    prev5attrValueGramLM.add(0, mentionedAttrValues.get(i));
                    j++;
                }
                if (!action.equals(Action.TOKEN_END)) {
                    prev5attrValueGramLM.add(action + "=" + chooseNextValue(action, attrValuesToBeMentioned));
                } else {
                    prev5attrValueGramLM.add(action);
                }
                while (prev5attrValueGramLM.size() < 4) {
                    prev5attrValueGramLM.add(0, "@@");
                }

                double afterLMScore = getContentLMsPerPredicate().get(predicate)
                        .getProbability(prev5attrValueGramLM);
                valueSpecificFeatures.get(action).put("global_feature_LMAttr_score", afterLMScore);

                afterLMScore = getContentLMsPerPredicate().get(predicate).getProbability(fullGramLM);
                valueSpecificFeatures.get(action).put("global_feature_LMAttrFull_score", afterLMScore);
            }
        }
    }
    return new Instance(generalFeatures, valueSpecificFeatures, costs);
}

From source file:com.fairphone.fplauncher3.Workspace.java

private void updateShortcutsAndWidgetsPerUser(ArrayList<AppInfo> apps, final UserHandleCompat user) {
    // Create a map of the apps to test against
    final HashMap<ComponentName, AppInfo> appsMap = new HashMap<ComponentName, AppInfo>();
    final HashSet<String> pkgNames = new HashSet<String>();
    for (AppInfo ai : apps) {
        appsMap.put(ai.componentName, ai);
        pkgNames.add(ai.componentName.getPackageName());
    }// w w  w  .  j  a  va2  s. c  o  m
    final HashSet<ComponentName> iconsToRemove = new HashSet<ComponentName>();

    mapOverItems(MAP_RECURSE, new ItemOperator() {
        @Override
        public boolean evaluate(ItemInfo info, View v, View parent) {
            if (info instanceof ShortcutInfo && v instanceof BubbleTextView) {
                ShortcutInfo shortcutInfo = (ShortcutInfo) info;
                ComponentName cn = shortcutInfo.getTargetComponent();
                AppInfo appInfo = appsMap.get(cn);
                if (user.equals(shortcutInfo.user) && cn != null && LauncherModel.isShortcutInfoUpdateable(info)
                        && pkgNames.contains(cn.getPackageName())) {
                    boolean promiseStateChanged = false;
                    boolean infoUpdated = false;
                    if (shortcutInfo.isPromise()) {
                        if (shortcutInfo.hasStatusFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
                            // Auto install icon
                            PackageManager pm = getContext().getPackageManager();
                            ResolveInfo matched = pm
                                    .resolveActivity(
                                            new Intent(Intent.ACTION_MAIN).setComponent(cn)
                                                    .addCategory(Intent.CATEGORY_LAUNCHER),
                                            PackageManager.MATCH_DEFAULT_ONLY);
                            if (matched == null) {
                                // Try to find the best match activity.
                                Intent intent = pm.getLaunchIntentForPackage(cn.getPackageName());
                                if (intent != null) {
                                    cn = intent.getComponent();
                                    appInfo = appsMap.get(cn);
                                }

                                if ((intent == null) || (appsMap == null)) {
                                    // Could not find a default activity. Remove this item.
                                    iconsToRemove.add(shortcutInfo.getTargetComponent());

                                    // process next shortcut.
                                    return false;
                                }
                                shortcutInfo.promisedIntent = intent;
                            }
                        }

                        // Restore the shortcut.
                        shortcutInfo.intent = shortcutInfo.promisedIntent;
                        shortcutInfo.promisedIntent = null;
                        shortcutInfo.status &= ~ShortcutInfo.FLAG_RESTORED_ICON
                                & ~ShortcutInfo.FLAG_AUTOINTALL_ICON
                                & ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;

                        promiseStateChanged = true;
                        infoUpdated = true;
                        shortcutInfo.updateIcon(mIconCache);
                        LauncherModel.updateItemInDatabase(getContext(), shortcutInfo);
                    }

                    if (appInfo != null) {
                        shortcutInfo.updateIcon(mIconCache);
                        shortcutInfo.title = appInfo.title.toString();
                        shortcutInfo.contentDescription = appInfo.contentDescription;
                        infoUpdated = true;
                    }

                    if (infoUpdated) {
                        BubbleTextView shortcut = (BubbleTextView) v;
                        shortcut.applyFromShortcutInfo(shortcutInfo, mIconCache, true, promiseStateChanged);

                        if (parent != null) {
                            parent.invalidate();
                        }
                    }
                }
            }
            // process all the shortcuts
            return false;
        }
    });

    if (!iconsToRemove.isEmpty()) {
        removeItemsByComponentName(iconsToRemove, user);
    }
    if (user.equals(UserHandleCompat.myUserHandle())) {
        restorePendingWidgets(pkgNames);
    }
}

From source file:org.sakaiproject.evaluation.logic.EvalEvaluationSetupServiceImpl.java

/**
 * Special method which skips the evaluation state checks,
 * this is mostly needed to allow us to force an update at any time <br/>
 * Synchronizes all the user assignments with the assigned groups for this evaluation
 * <br/> Always run as an admin for permissions handling
 * /* w  w  w  . j  a  v  a 2 s  . c  o m*/
 * @param evaluation the evaluation to do assignment updates for
 * @param evalGroupId (OPTIONAL) the internal group id of an eval group,
 * this will cause the synchronize to only affect the assignments related to this group
 * @param removeAllowed if true then will remove assignments as well, otherwise only adds
 * @return the list of {@link EvalAssignUser} ids changed during the synchronization (created, updated, deleted),
 * NOTE: deleted {@link EvalAssignUser} will not be able to be retrieved
 */
public List<Long> synchronizeUserAssignmentsForced(EvalEvaluation evaluation, String evalGroupId,
        boolean removeAllowed) {
    Long evaluationId = evaluation.getId();
    String currentUserId = commonLogic.getCurrentUserId();
    if (currentUserId == null) {
        currentUserId = commonLogic.getAdminUserId();
    } else {
        // check anon and use admin instead
        EvalUser user = commonLogic.getEvalUserById(currentUserId);
        if (EvalUser.USER_TYPE_ANONYMOUS.equals(user.type) || EvalUser.USER_TYPE_INVALID.equals(user.type)
                || EvalUser.USER_TYPE_UNKNOWN.equals(user.type)) {
            currentUserId = commonLogic.getAdminUserId();
        }
    }
    ArrayList<Long> changedUserAssignments = new ArrayList<>();
    // now the syncing logic
    HashSet<Long> assignUserToRemove = new HashSet<>();
    HashSet<EvalAssignUser> assignUserToSave = new HashSet<>();
    // get all user assignments for this evaluation (and possibly limit by group)
    String[] limitGroupIds = null;
    if (evalGroupId != null) {
        limitGroupIds = new String[] { evalGroupId };
    }
    // all users assigned to this eval (and group if specified)
    List<EvalAssignUser> assignedUsers = evaluationService.getParticipantsForEval(evaluationId, null,
            limitGroupIds, null, EvalEvaluationService.STATUS_ANY, null, null);
    // keys of all assignments which are unlinked or removed
    HashSet<String> assignUserUnlinkedRemovedKeys = new HashSet<>();
    // all assignments which are linked (groupId => assignments)
    HashMap<String, List<EvalAssignUser>> groupIdLinkedAssignedUsersMap = new HashMap<>();
    for (EvalAssignUser evalAssignUser : assignedUsers) {
        if (EvalAssignUser.STATUS_UNLINKED.equals(evalAssignUser.getStatus())
                || EvalAssignUser.STATUS_REMOVED.equals(evalAssignUser.getStatus())) {
            String key = makeEvalAssignUserKey(evalAssignUser, false, false);
            assignUserUnlinkedRemovedKeys.add(key);
        }
        String egid = evalAssignUser.getEvalGroupId();
        if (egid != null) {
            if (EvalAssignUser.STATUS_LINKED.equals(evalAssignUser.getStatus())) {
                List<EvalAssignUser> l = groupIdLinkedAssignedUsersMap.get(egid);
                if (l == null) {
                    l = new ArrayList<>();
                    groupIdLinkedAssignedUsersMap.put(egid, l);
                }
                l.add(evalAssignUser);
            }
        }
    }
    List<EvalAssignGroup> assignedGroups;
    if (evalGroupId == null) {
        // get all the assigned groups for this evaluation
        Map<Long, List<EvalAssignGroup>> m = evaluationService
                .getAssignGroupsForEvals(new Long[] { evaluationId }, true, null);
        assignedGroups = m.get(evaluationId);
    } else {
        // only dealing with a single assign group (or possibly none if invalid)
        assignedGroups = new ArrayList<>();
        EvalAssignGroup assignGroup = evaluationService.getAssignGroupByEvalAndGroupId(evaluationId,
                evalGroupId);
        if (assignGroup != null) {
            assignedGroups.add(assignGroup);
        }
    }
    // iterate through all assigned groups (may have been limited to one only)
    Set<String> evalGroupIdsFromEvals = new HashSet<>(assignedGroups.size());
    for (EvalAssignGroup evalAssignGroup : assignedGroups) {
        Long assignGroupId = evalAssignGroup.getId();
        String egid = evalAssignGroup.getEvalGroupId();
        evalGroupIdsFromEvals.add(egid);
        // get all the users who currently have permission for this group
        Set<String> currentEvaluated = commonLogic.getUserIdsForEvalGroup(egid, EvalConstants.PERM_BE_EVALUATED,
                evaluation.getSectionAwareness());
        Set<String> currentAssistants = commonLogic.getUserIdsForEvalGroup(egid,
                EvalConstants.PERM_ASSISTANT_ROLE, evaluation.getSectionAwareness());
        Set<String> currentTakers = commonLogic.getUserIdsForEvalGroup(egid, EvalConstants.PERM_TAKE_EVALUATION,
                evaluation.getSectionAwareness());

        if (evaluation.getAllRolesParticipate()) {
            currentTakers.addAll(currentAssistants);
            currentTakers.addAll(currentEvaluated);
        }

        HashSet<String> currentAll = new HashSet<>();
        currentAll.addAll(currentEvaluated);
        currentAll.addAll(currentAssistants);
        currentAll.addAll(currentTakers);
        /* Resolve the current permissions against the existing assignments,
         * this should only change linked records but should respect unlinked and removed records by not
         * adding a record where one already exists for the given user/group combo,
         * any linked records which do not exist anymore should be trashed if the status is right,
         * any missing records should be added if the evaluation is still active or better
         */
        List<EvalAssignUser> linkedUserAssignsInThisGroup = groupIdLinkedAssignedUsersMap.get(egid);
        if (linkedUserAssignsInThisGroup == null) {
            // this group has not been assigned yet
            linkedUserAssignsInThisGroup = new ArrayList<>();
        }
        // filter out all linked user assignments which match exactly with the existing ones
        for (Iterator<EvalAssignUser> iterator = linkedUserAssignsInThisGroup.iterator(); iterator.hasNext();) {
            EvalAssignUser evalAssignUser = iterator.next();
            String type = evalAssignUser.getType();
            String userId = evalAssignUser.getUserId();
            if (EvalAssignUser.TYPE_EVALUATEE.equals(type)) {
                if (currentEvaluated.contains(userId)) {
                    currentEvaluated.remove(userId);
                    iterator.remove();
                }
            } else if (EvalAssignUser.TYPE_ASSISTANT.equals(type)) {
                if (currentAssistants.contains(userId)) {
                    currentAssistants.remove(userId);
                    iterator.remove();
                }
            } else if (EvalAssignUser.TYPE_EVALUATOR.equals(type)) {
                if (currentTakers.contains(userId)) {
                    currentTakers.remove(userId);
                    iterator.remove();
                }
            } else {
                throw new IllegalStateException("Do not recognize this user assignment type: " + type);
            }
        }
        // any remaining linked user assignments should be removed if not unlinked
        for (EvalAssignUser evalAssignUser : linkedUserAssignsInThisGroup) {
            if (evalAssignUser.getId() != null) {
                String key = makeEvalAssignUserKey(evalAssignUser, false, false);
                if (!assignUserUnlinkedRemovedKeys.contains(key)) {
                    assignUserToRemove.add(evalAssignUser.getId());
                }
            }
        }
        // any remaining current set items need to be added if they are not unlinked/removed
        assignUserToSave.addAll(makeUserAssignmentsFromUserIdSet(currentEvaluated, egid,
                EvalAssignUser.TYPE_EVALUATEE, assignGroupId, assignUserUnlinkedRemovedKeys));
        assignUserToSave.addAll(makeUserAssignmentsFromUserIdSet(currentAssistants, egid,
                EvalAssignUser.TYPE_ASSISTANT, assignGroupId, assignUserUnlinkedRemovedKeys));
        assignUserToSave.addAll(makeUserAssignmentsFromUserIdSet(currentTakers, egid,
                EvalAssignUser.TYPE_EVALUATOR, assignGroupId, assignUserUnlinkedRemovedKeys));
    }

    // now handle the actual persistent updates and log them
    String message = "Synchronized user assignments for eval (" + evaluationId + ") with "
            + assignedGroups.size() + " assigned groups";
    if (assignUserToRemove.isEmpty() && assignUserToSave.isEmpty()) {
        message += ": no changes to the user assignments (" + assignedUsers.size() + ")";
    } else {
        if (removeAllowed && !assignUserToRemove.isEmpty()) {
            Long[] assignUserToRemoveArray = assignUserToRemove.toArray(new Long[assignUserToRemove.size()]);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Deleting user eval assignment Ids: " + assignUserToRemove);
            }
            dao.deleteSet(EvalAssignUser.class, assignUserToRemoveArray);
            message += ": removed the following assignments: " + assignUserToRemove;
            changedUserAssignments.addAll(assignUserToRemove);
        }
        if (!assignUserToSave.isEmpty()) {
            for (EvalAssignUser evalAssignUser : assignUserToSave) {
                setAssignUserDefaults(evalAssignUser, evaluation, currentUserId);
            }
            // this is meant to force the assigned users set to be re-calculated
            assignUserToSave = new HashSet<>(assignUserToSave);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Saving user eval assignments: " + assignUserToSave);
            }
            dao.saveSet(assignUserToSave);
            message += ": created the following assignments: " + assignUserToSave;
            for (EvalAssignUser evalAssignUser : assignUserToSave) {
                changedUserAssignments.add(evalAssignUser.getId());
            }
        }
    }

    // one more specialty check to cleanup orphaned user assignments - EVALSYS-703
    Set<String> evalGroupIdsFromUsers = groupIdLinkedAssignedUsersMap.keySet();
    evalGroupIdsFromUsers.removeAll(evalGroupIdsFromEvals);
    if (!evalGroupIdsFromUsers.isEmpty()) {
        // there are users assigned to group ids in this eval which are not part of the assigned groups
        HashSet<Long> orphanedUserAssignments = new HashSet<>();
        for (EvalAssignUser evalAssignUser : assignedUsers) {
            String egid = evalAssignUser.getEvalGroupId();
            if (egid != null && evalGroupIdsFromUsers.contains(egid)) {
                if (EvalAssignUser.STATUS_LINKED.equals(evalAssignUser.getStatus())) {
                    orphanedUserAssignments.add(evalAssignUser.getId());
                }
            }
        }
        if (!orphanedUserAssignments.isEmpty()) {
            Long[] orphanedUserAssignmentsArray = orphanedUserAssignments
                    .toArray(new Long[orphanedUserAssignments.size()]);
            dao.deleteSet(EvalAssignUser.class, orphanedUserAssignmentsArray);
            message += ": removed the following orphaned user assignments: " + orphanedUserAssignments;
            changedUserAssignments.addAll(orphanedUserAssignments);
        }
    }

    LOG.info(message);
    return changedUserAssignments;
}

From source file:org.jsweet.transpiler.typescript.Java2TypeScriptTranslator.java

@Override
public void visitClassDef(JCClassDecl classdecl) {
    if (context.isIgnored(classdecl)) {
        return;/*  w w w . j  av a 2  s . c om*/
    }
    String name = classdecl.getSimpleName().toString();
    if (!scope.isEmpty() && getScope().anonymousClasses.contains(classdecl)) {
        name = getScope().name + ANONYMOUS_PREFIX + getScope().anonymousClasses.indexOf(classdecl);
    }

    JCTree testParent = getFirstParent(JCClassDecl.class, JCMethodDecl.class);
    if (testParent != null && testParent instanceof JCMethodDecl) {
        if (!isLocalClass()) {
            getScope().localClasses.add(classdecl);
            return;
        }
    }

    enterScope();
    getScope().name = name;

    JCClassDecl parent = getParent(JCClassDecl.class);
    List<TypeVariableSymbol> parentTypeVars = new ArrayList<>();
    if (parent != null) {
        getScope().innerClass = true;
        if (!classdecl.getModifiers().getFlags().contains(Modifier.STATIC)) {
            getScope().innerClassNotStatic = true;
            if (parent.getTypeParameters() != null) {
                parentTypeVars.addAll(parent.getTypeParameters().stream()
                        .map(t -> (TypeVariableSymbol) t.type.tsym).collect(Collectors.toList()));
                getAdapter().typeVariablesToErase.addAll(parentTypeVars);
            }
        }
    }
    getScope().declareClassScope = context.hasAnnotationType(classdecl.sym, JSweetConfig.ANNOTATION_AMBIENT)
            || isDefinitionScope;
    getScope().interfaceScope = false;
    getScope().removedSuperclass = false;
    getScope().enumScope = false;
    getScope().enumWrapperClassScope = false;

    HashSet<Entry<JCClassDecl, JCMethodDecl>> defaultMethods = null;
    boolean globals = JSweetConfig.GLOBALS_CLASS_NAME.equals(classdecl.name.toString());
    if (globals && classdecl.extending != null) {
        report(classdecl, JSweetProblem.GLOBALS_CLASS_CANNOT_HAVE_SUPERCLASS);
    }
    List<Type> implementedInterfaces = new ArrayList<>();

    if (!globals) {
        if (classdecl.extending != null && JSweetConfig.GLOBALS_CLASS_NAME
                .equals(classdecl.extending.type.tsym.getSimpleName().toString())) {
            report(classdecl, JSweetProblem.GLOBALS_CLASS_CANNOT_BE_SUBCLASSED);
            return;
        }
        printDocComment(classdecl, false);
        print(classdecl.mods);
        if (!globalModule || context.useModules || isAnonymousClass() || isInnerClass() || isLocalClass()) {
            print("export ");
        }
        if (context.isInterface(classdecl.sym)) {
            print("interface ");
            getScope().interfaceScope = true;
        } else {
            if (classdecl.getKind() == Kind.ENUM) {
                if (getScope().declareClassScope && !(getIndent() != 0 && isDefinitionScope)) {
                    print("declare ");
                }
                if (scope.size() > 1 && getScope(1).isComplexEnum) {
                    if (Util.hasAbstractMethod(classdecl.sym)) {
                        print("abstract ");
                    }
                    print("class ");
                    getScope().enumWrapperClassScope = true;
                } else {
                    print("enum ");
                    getScope().enumScope = true;
                }
            } else {
                if (getScope().declareClassScope && !(getIndent() != 0 && isDefinitionScope)) {
                    print("declare ");
                }
                defaultMethods = new HashSet<>();
                Util.findDefaultMethodsInType(defaultMethods, context, classdecl.sym);
                if (classdecl.getModifiers().getFlags().contains(Modifier.ABSTRACT)) {
                    print("abstract ");
                }
                print("class ");
            }
        }

        print(name + (getScope().enumWrapperClassScope ? ENUM_WRAPPER_CLASS_SUFFIX : ""));

        if (classdecl.typarams != null && classdecl.typarams.size() > 0) {
            print("<").printArgList(classdecl.typarams).print(">");
        } else if (isAnonymousClass() && classdecl.getModifiers().getFlags().contains(Modifier.STATIC)) {
            JCNewClass newClass = getScope(1).anonymousClassesConstructors
                    .get(getScope(1).anonymousClasses.indexOf(classdecl));
            printAnonymousClassTypeArgs(newClass);
        }
        String mixin = null;
        if (context.hasAnnotationType(classdecl.sym, JSweetConfig.ANNOTATION_MIXIN)) {
            mixin = context.getAnnotationValue(classdecl.sym, JSweetConfig.ANNOTATION_MIXIN, null);
        }

        boolean extendsInterface = false;
        if (classdecl.extending != null) {

            boolean removeIterable = false;
            if (context.hasAnnotationType(classdecl.sym, JSweetConfig.ANNOTATION_SYNTACTIC_ITERABLE)
                    && classdecl.extending.type.tsym.getQualifiedName().toString()
                            .equals(Iterable.class.getName())) {
                removeIterable = true;
            }

            if (!removeIterable && !JSweetConfig.isJDKReplacementMode()
                    && !(JSweetConfig.OBJECT_CLASSNAME.equals(classdecl.extending.type.toString())
                            || Object.class.getName().equals(classdecl.extending.type.toString()))
                    && !(mixin != null && mixin.equals(classdecl.extending.type.toString())) && !(getAdapter()
                            .eraseSuperClass(classdecl, (ClassSymbol) classdecl.extending.type.tsym))) {
                if (!getScope().interfaceScope && context.isInterface(classdecl.extending.type.tsym)) {
                    extendsInterface = true;
                    print(" implements ");
                    implementedInterfaces.add(classdecl.extending.type);
                } else {
                    print(" extends ");
                }
                if (getScope().enumWrapperClassScope && getScope(1).anonymousClasses.contains(classdecl)) {
                    print(classdecl.extending.toString() + ENUM_WRAPPER_CLASS_SUFFIX);
                } else {
                    getAdapter().disableTypeSubstitution = !getAdapter().isSubstituteSuperTypes();
                    getAdapter().substituteAndPrintType(classdecl.extending);
                    getAdapter().disableTypeSubstitution = false;
                }
                if (context.classesWithWrongConstructorOverload.contains(classdecl.sym)) {
                    getScope().hasConstructorOverloadWithSuperClass = true;
                }
            } else {
                getScope().removedSuperclass = true;
            }
        }

        if (classdecl.implementing != null && !classdecl.implementing.isEmpty()) {
            List<JCExpression> implementing = new ArrayList<>(classdecl.implementing);

            if (context.hasAnnotationType(classdecl.sym, JSweetConfig.ANNOTATION_SYNTACTIC_ITERABLE)) {
                for (JCExpression itf : classdecl.implementing) {
                    if (itf.type.tsym.getQualifiedName().toString().equals(Iterable.class.getName())) {
                        implementing.remove(itf);
                    }
                }
            }
            // erase Java interfaces
            for (JCExpression itf : classdecl.implementing) {
                if (getAdapter().eraseSuperInterface(classdecl, (ClassSymbol) itf.type.tsym)) {
                    implementing.remove(itf);
                }
            }

            if (!implementing.isEmpty()) {
                if (!extendsInterface) {
                    if (getScope().interfaceScope) {
                        print(" extends ");
                    } else {
                        print(" implements ");
                    }
                } else {
                    print(", ");
                }
                for (JCExpression itf : implementing) {
                    getAdapter().disableTypeSubstitution = !getAdapter().isSubstituteSuperTypes();
                    getAdapter().substituteAndPrintType(itf);
                    getAdapter().disableTypeSubstitution = false;
                    implementedInterfaces.add(itf.type);
                    print(", ");
                }
                removeLastChars(2);
            }
        }
        print(" {").println().startIndent();
    }

    if (getScope().innerClassNotStatic && !getScope().interfaceScope && !getScope().enumScope) {
        printIndent().print("public " + PARENT_CLASS_FIELD_NAME + ": any;").println();
    }

    if (defaultMethods != null && !defaultMethods.isEmpty()) {
        getScope().defaultMethodScope = true;
        for (Entry<JCClassDecl, JCMethodDecl> entry : defaultMethods) {
            MethodSymbol s = Util.findMethodDeclarationInType(context.types, classdecl.sym,
                    entry.getValue().getName().toString(), (MethodType) entry.getValue().type);
            if (s == null || s == entry.getValue().sym) {
                getAdapter().typeVariablesToErase
                        .addAll(((ClassSymbol) s.getEnclosingElement()).getTypeParameters());
                printIndent().print(entry.getValue()).println();
                getAdapter().typeVariablesToErase
                        .removeAll(((ClassSymbol) s.getEnclosingElement()).getTypeParameters());
            }
        }
        getScope().defaultMethodScope = false;
    }

    if (getScope().enumScope) {
        printIndent();
    }
    if (globals) {
        removeLastIndent();
    }

    if (!getScope().interfaceScope && classdecl.getModifiers().getFlags().contains(Modifier.ABSTRACT)) {
        List<MethodSymbol> methods = new ArrayList<>();
        for (Type t : implementedInterfaces) {
            context.grabMethodsToBeImplemented(methods, t.tsym);
        }
        Map<Name, String> signatures = new HashMap<>();
        for (MethodSymbol meth : methods) {
            if (meth.type instanceof MethodType) {
                MethodSymbol s = Util.findMethodDeclarationInType(getContext().types, classdecl.sym,
                        meth.getSimpleName().toString(), (MethodType) meth.type, true);
                boolean printDefaultImplementation = false;
                if (s != null) {
                    if (!s.getEnclosingElement().equals(classdecl.sym)) {
                        if (!(s.isDefault() || (!context.isInterface((TypeSymbol) s.getEnclosingElement())
                                && !s.getModifiers().contains(Modifier.ABSTRACT)))) {
                            printDefaultImplementation = true;
                        }
                    }
                }
                if (printDefaultImplementation) {
                    Overload o = context.getOverload(classdecl.sym, meth);
                    if (o != null && o.methods.size() > 1 && !o.isValid) {
                        if (!meth.type.equals(o.coreMethod.type)) {
                            printDefaultImplementation = false;
                        }
                    }
                }
                if (s == null || printDefaultImplementation) {
                    String signature = getContext().types.erasure(meth.type).toString();
                    if (!(signatures.containsKey(meth.name) && signatures.get(meth.name).equals(signature))) {
                        printDefaultImplementation(meth);
                        signatures.put(meth.name, signature);
                    }
                }
            }
        }
    }

    for (JCTree def : classdecl.defs) {
        if (def instanceof JCClassDecl) {
            getScope().hasInnerClass = true;
        }
        if (def instanceof JCVariableDecl) {
            JCVariableDecl var = (JCVariableDecl) def;
            if (!var.sym.isStatic() && var.init != null) {
                getScope().fieldsWithInitializers.add((JCVariableDecl) def);
            }
        }
    }

    if (!globals && !context.isInterface(classdecl.sym)
            && context.getStaticInitializerCount(classdecl.sym) > 0) {
        printIndent().print("static __static_initialized : boolean = false;").println();
        int liCount = context.getStaticInitializerCount(classdecl.sym);
        String prefix = classdecl.getSimpleName().toString() + ".";
        printIndent().print("static __static_initialize() { ");
        print("if(!" + prefix + "__static_initialized) { ");
        print(prefix + "__static_initialized = true; ");
        for (int i = 0; i < liCount; i++) {
            print(prefix + "__static_initializer_" + i + "(); ");
        }
        print("} }").println().println();
        String qualifiedClassName = getQualifiedTypeName(classdecl.sym, globals);
        context.addTopFooterStatement(
                (isBlank(qualifiedClassName) ? "" : qualifiedClassName + ".__static_initialize();"));
    }

    boolean hasUninitializedFields = false;

    for (JCTree def : classdecl.defs) {
        if (getScope().interfaceScope && ((def instanceof JCMethodDecl && ((JCMethodDecl) def).sym.isStatic())
                || (def instanceof JCVariableDecl && ((JCVariableDecl) def).sym.isStatic()))) {
            // static interface members are printed in a namespace
            continue;
        }
        if (def instanceof JCClassDecl) {
            // inner types are be printed in a namespace
            continue;
        }
        if (def instanceof JCVariableDecl) {
            if (getScope().enumScope && ((JCVariableDecl) def).type.tsym != classdecl.type.tsym) {
                getScope().isComplexEnum = true;
                continue;
            }
            if (!getAdapter().needsVariableDecl((JCVariableDecl) def, VariableKind.FIELD)) {
                continue;
            }
            if (!((JCVariableDecl) def).getModifiers().getFlags().contains(Modifier.STATIC)
                    && ((JCVariableDecl) def).init == null) {
                hasUninitializedFields = true;
            }
        }
        if (def instanceof JCBlock && !((JCBlock) def).isStatic()) {
            hasUninitializedFields = true;
        }
        if (!getScope().enumScope) {
            printIndent();
        }
        int pos = getCurrentPosition();
        print(def);
        if (getCurrentPosition() == pos) {
            if (!getScope().enumScope) {
                removeLastIndent();
            }
            continue;
        }
        if (def instanceof JCVariableDecl) {
            if (getScope().enumScope) {
                print(", ");
            } else {
                print(";").println().println();
            }
        } else {
            println().println();
        }
    }

    if (!getScope().hasDeclaredConstructor
            && !(getScope().interfaceScope || getScope().enumScope || getScope().declareClassScope)) {
        Set<String> interfaces = new HashSet<>();
        context.grabSupportedInterfaceNames(interfaces, classdecl.sym);
        if (!interfaces.isEmpty() || getScope().innerClassNotStatic || hasUninitializedFields) {
            printIndent().print("constructor(");
            boolean hasArgs = false;
            if (getScope().innerClassNotStatic) {
                print(PARENT_CLASS_FIELD_NAME + ": any");
                hasArgs = true;
            }
            int anonymousClassIndex = scope.size() > 1 ? getScope(1).anonymousClasses.indexOf(classdecl) : -1;
            if (anonymousClassIndex != -1) {
                for (int i = 0; i < getScope(1).anonymousClassesConstructors.get(anonymousClassIndex).args
                        .length(); i++) {
                    if (!hasArgs) {
                        hasArgs = true;
                    } else {
                        print(", ");
                    }
                    print("__arg" + i + ": any");
                }
                for (VarSymbol v : getScope(1).finalVariables.get(anonymousClassIndex)) {
                    if (!hasArgs) {
                        hasArgs = true;
                    } else {
                        print(", ");
                    }
                    print("private " + v.getSimpleName() + ": any");
                }
            }

            print(") {").startIndent().println();
            if (classdecl.extending != null && !getScope().removedSuperclass
                    && !context.isInterface(classdecl.extending.type.tsym)) {
                printIndent().print("super(");
                if (getScope().innerClassNotStatic) {
                    TypeSymbol s = classdecl.extending.type.tsym;
                    boolean hasArg = false;
                    if (s.getEnclosingElement() instanceof ClassSymbol && !s.isStatic()) {
                        print(PARENT_CLASS_FIELD_NAME);
                        hasArg = true;
                    }
                    if (anonymousClassIndex != -1) {
                        for (int i = 0; i < getScope(1).anonymousClassesConstructors
                                .get(anonymousClassIndex).args.length(); i++) {
                            if (hasArg) {
                                print(", ");
                            } else {
                                hasArg = true;
                            }
                            print("__arg" + i);
                        }
                    }
                }
                print(");").println();
            }
            printInstanceInitialization(classdecl, null);
            endIndent().printIndent().print("}").println().println();
        }
    }

    removeLastChar();

    if (getScope().enumWrapperClassScope && !getScope(1).anonymousClasses.contains(classdecl)) {
        printIndent().print("public name() : string { return this." + ENUM_WRAPPER_CLASS_NAME + "; }")
                .println();
        printIndent().print("public ordinal() : number { return this." + ENUM_WRAPPER_CLASS_ORDINAL + "; }")
                .println();
    }

    if (getScope().enumScope) {
        removeLastChar().println();
    }

    if (!globals) {
        endIndent().printIndent().print("}");
        if (getContext().options.isSupportGetClass() && !getScope().interfaceScope
                && !getScope().declareClassScope && !getScope().enumScope && !classdecl.sym.isAnonymous()) {
            println().printIndent().print(classdecl.sym.getSimpleName().toString())
                    .print("[\"" + CLASS_NAME_IN_CONSTRUCTOR + "\"] = ")
                    .print("\"" + context.getRootRelativeName(null, classdecl.sym) + "\";");

            Set<String> interfaces = new HashSet<>();
            context.grabSupportedInterfaceNames(interfaces, classdecl.sym);
            if (!interfaces.isEmpty()) {
                println().printIndent().print(classdecl.sym.getSimpleName().toString())
                        .print("[\"" + INTERFACES_FIELD_NAME + "\"] = ");
                print("[");
                for (String itf : interfaces) {
                    print("\"").print(itf).print("\",");
                }
                removeLastChar();
                print("];").println();
            }
            if (!getScope().enumWrapperClassScope) {
                println();
            }
        }
    }

    // enum class for complex enum
    if (getScope().isComplexEnum) {
        println().println().printIndent();
        visitClassDef(classdecl);
    }

    // inner, anonymous and local classes in a namespace
    // ======================
    // print valid inner classes
    boolean nameSpace = false;
    for (JCTree def : classdecl.defs) {
        if (def instanceof JCClassDecl) {
            JCClassDecl cdef = (JCClassDecl) def;
            if (context.isIgnored(cdef)) {
                continue;
            }
            if (!nameSpace) {
                nameSpace = true;
                println().println().printIndent();
                if (!globalModule || context.useModules) {
                    print("export ");
                } else {
                    if (isDefinitionScope) {
                        print("declare ");
                    }
                }
                print("namespace ").print(name).print(" {").startIndent();
            }
            getScope().isInnerClass = true;
            println().println().printIndent().print(cdef);
            getScope().isInnerClass = false;
        }
    }
    // print anonymous classes
    for (JCClassDecl cdef : getScope().anonymousClasses) {
        if (!nameSpace) {
            nameSpace = true;
            println().println().printIndent();
            if (!globalModule || context.useModules) {
                print("export ");
            }
            print("namespace ").print(name).print(" {").startIndent();
        }
        getScope().isAnonymousClass = true;
        println().println().printIndent().print(cdef);
        getScope().isAnonymousClass = false;
    }
    // print local classes
    for (JCClassDecl cdef : getScope().localClasses) {
        if (!nameSpace) {
            nameSpace = true;
            println().println().printIndent();
            if (!globalModule || context.useModules) {
                print("export ");
            }
            print("namespace ").print(name).print(" {").startIndent();
        }
        getScope().isLocalClass = true;
        println().println().printIndent().print(cdef);
        getScope().isLocalClass = false;
    }
    if (nameSpace) {
        println().endIndent().printIndent().print("}").println();
    }
    // end of namespace =================================================

    if (getScope().enumScope && getScope().isComplexEnum && !getScope().anonymousClasses.contains(classdecl)) {
        println().printIndent().print(classdecl.sym.getSimpleName().toString())
                .print("[\"" + ENUM_WRAPPER_CLASS_WRAPPERS + "\"] = [");
        int index = 0;
        for (JCTree tree : classdecl.defs) {
            if (tree instanceof JCVariableDecl && ((JCVariableDecl) tree).type.equals(classdecl.type)) {
                JCVariableDecl varDecl = (JCVariableDecl) tree;
                // enum fields are not part of the enum auxiliary class but
                // will initialize the enum values
                JCNewClass newClass = (JCNewClass) varDecl.init;
                JCClassDecl clazz = classdecl;
                try {
                    int anonymousClassIndex = getScope().anonymousClasses.indexOf(newClass.def);
                    if (anonymousClassIndex >= 0) {
                        print("new ")
                                .print(clazz.getSimpleName().toString() + "." + clazz.getSimpleName().toString()
                                        + ANONYMOUS_PREFIX + anonymousClassIndex + ENUM_WRAPPER_CLASS_SUFFIX)
                                .print("(");
                    } else {
                        print("new ").print(clazz.getSimpleName().toString() + ENUM_WRAPPER_CLASS_SUFFIX)
                                .print("(");
                    }
                    print("" + (index++) + ", ");
                    print("\"" + varDecl.sym.name.toString() + "\"");
                    if (!newClass.args.isEmpty()) {
                        print(", ");
                    }
                    printArgList(newClass.args).print(")");
                    print(", ");
                } catch (Exception e) {
                    System.out.println("");
                }
            }
        }
        removeLastChars(2);
        print("];").println();
    }

    if (getScope().interfaceScope) {
        // print static members of interfaces
        nameSpace = false;
        for (JCTree def : classdecl.defs) {
            if ((def instanceof JCMethodDecl && ((JCMethodDecl) def).sym.isStatic())
                    || (def instanceof JCVariableDecl && ((JCVariableDecl) def).sym.isStatic())) {
                if (def instanceof JCVariableDecl && context.hasAnnotationType(((JCVariableDecl) def).sym,
                        ANNOTATION_STRING_TYPE, JSweetConfig.ANNOTATION_ERASED)) {
                    continue;
                }
                if (!nameSpace) {
                    nameSpace = true;
                    println().println().printIndent()
                            .print(getIndent() == 0 && isDefinitionScope ? "declare " : "export ")
                            .print("namespace ").print(classdecl.getSimpleName().toString()).print(" {")
                            .startIndent();
                }
                println().println().printIndent().print(def);
                if (def instanceof JCVariableDecl) {
                    print(";");
                }
            }
        }
        if (nameSpace) {
            println().endIndent().printIndent().print("}").println();
        }
    }

    if (mainMethod != null && mainMethod.getParameters().size() < 2
            && mainMethod.sym.getEnclosingElement().equals(classdecl.sym)) {
        String mainClassName = getQualifiedTypeName(classdecl.sym, globals);
        String mainMethodQualifier = mainClassName;
        if (!isBlank(mainClassName)) {
            mainMethodQualifier = mainClassName + ".";
        }
        context.entryFiles.add(new File(compilationUnit.sourcefile.getName()));
        context.addFooterStatement(mainMethodQualifier + JSweetConfig.MAIN_FUNCTION_NAME + "("
                + (mainMethod.getParameters().isEmpty() ? "" : "null") + ");");
    }

    getAdapter().typeVariablesToErase.removeAll(parentTypeVars);
    exitScope();
}

From source file:com.zimbra.cs.account.ldap.LdapProvisioning.java

private void removeDynamicGroupMembers(LdapDynamicGroup group, String[] members, boolean externalOnly)
        throws ServiceException {
    if (group.isMembershipDefinedByCustomURL()) {
        throw ServiceException.INVALID_REQUEST(String.format(
                "cannot remove members from dynamic group '%s' with custom memberURL", group.getName()), null);
    }//from   w w w. j a v  a2s  . c  o m

    String groupId = group.getId();

    List<Account> accts = new ArrayList<Account>();
    List<String> externalAddrs = new ArrayList<String>();
    HashSet<String> failed = new HashSet<String>();

    // check for errors, and put valid accts to the queue
    for (String member : members) {
        String memberName = member.toLowerCase();

        boolean isBadAddr = false;
        try {
            memberName = IDNUtil.toAsciiEmail(memberName);
        } catch (ServiceException e) {
            // if the addr is not a valid email address, maybe they want to
            // remove a bogus addr that somehow got in, just let it through.
            memberName = member;
            isBadAddr = true;
        }

        // always add all addrs to "externalAddrs".
        externalAddrs.add(memberName);

        if (!externalOnly) {
            Account acct = isBadAddr ? null : get(AccountBy.name, member);
            if (acct != null) {
                Set<String> memberOf = acct.getMultiAttrSet(Provisioning.A_zimbraMemberOf);
                if (memberOf.contains(groupId)) {
                    accts.add(acct);
                } else {
                    // else the addr is not in the group, throw exception
                    failed.add(memberName);
                }
            }
        }
    }

    if (!failed.isEmpty()) {
        StringBuilder sb = new StringBuilder();
        Iterator<String> iter = failed.iterator();
        while (true) {
            sb.append(iter.next());
            if (!iter.hasNext())
                break;
            sb.append(",");
        }
        throw AccountServiceException.NO_SUCH_MEMBER(group.getName(), sb.toString());
    }

    ZLdapContext zlc = null;
    try {
        zlc = LdapClient.getContext(LdapServerType.MASTER, LdapUsage.REMOVE_GROUP_MEMBER);

        /*
         * remove internal members
         */
        for (Account acct : accts) {
            Map<String, Object> attrs = new HashMap<String, Object>();
            attrs.put("-" + Provisioning.A_zimbraMemberOf, groupId);
            modifyLdapAttrs(acct, zlc, attrs);
            clearUpwardMembershipCache(acct);
        }

        /*
         * remove external members on the static unit
         */
        LdapDynamicGroup.StaticUnit staticUnit = group.getStaticUnit();
        Set<String> existingAddrs = staticUnit.getMembersSet();
        List<String> addrsToRemove = Lists.newArrayList();
        for (String addr : externalAddrs) {
            if (existingAddrs.contains(addr)) {
                addrsToRemove.add(addr);
            }
        }

        if (!addrsToRemove.isEmpty()) {
            Map<String, String[]> attrs = new HashMap<String, String[]>();
            attrs.put("-" + LdapDynamicGroup.StaticUnit.MEMBER_ATTR,
                    addrsToRemove.toArray(new String[addrsToRemove.size()]));
            modifyLdapAttrs(staticUnit, zlc, attrs);
        }

    } finally {
        LdapClient.closeContext(zlc);
    }
    PermissionCache.invalidateCache();
    cleanGroupMembersCache(group);
}

From source file:org.jsweet.transpiler.Java2TypeScriptTranslator.java

@Override
public void visitClassDef(JCClassDecl classdecl) {
    if (context.isIgnored(classdecl)) {
        getAdapter().afterType(classdecl.sym);
        return;/*from  w ww . j av  a  2 s .  c om*/
    }
    String name = classdecl.getSimpleName().toString();
    if (!scope.isEmpty() && getScope().anonymousClasses.contains(classdecl)) {
        name = getScope().name + ANONYMOUS_PREFIX + getScope().anonymousClasses.indexOf(classdecl);
    }

    JCTree testParent = getFirstParent(JCClassDecl.class, JCMethodDecl.class);
    if (testParent != null && testParent instanceof JCMethodDecl) {
        if (!isLocalClass()) {
            getScope().localClasses.add(classdecl);
            return;
        }
    }

    enterScope();
    getScope().name = name;

    JCClassDecl parent = getParent(JCClassDecl.class);
    List<TypeVariableSymbol> parentTypeVars = new ArrayList<>();
    if (parent != null) {
        getScope().innerClass = true;
        if (!classdecl.getModifiers().getFlags().contains(Modifier.STATIC)) {
            getScope().innerClassNotStatic = true;
            if (parent.getTypeParameters() != null) {
                parentTypeVars.addAll(parent.getTypeParameters().stream()
                        .map(t -> (TypeVariableSymbol) t.type.tsym).collect(Collectors.toList()));
                getAdapter().typeVariablesToErase.addAll(parentTypeVars);
            }
        }
    }
    getScope().declareClassScope = context.hasAnnotationType(classdecl.sym, JSweetConfig.ANNOTATION_AMBIENT)
            || isDefinitionScope;
    getScope().interfaceScope = false;
    getScope().removedSuperclass = false;
    getScope().enumScope = false;
    getScope().enumWrapperClassScope = false;

    HashSet<Entry<JCClassDecl, JCMethodDecl>> defaultMethods = null;
    boolean globals = JSweetConfig.GLOBALS_CLASS_NAME.equals(classdecl.name.toString());
    if (globals && classdecl.extending != null) {
        report(classdecl, JSweetProblem.GLOBALS_CLASS_CANNOT_HAVE_SUPERCLASS);
    }
    List<Type> implementedInterfaces = new ArrayList<>();

    if (!globals) {
        if (classdecl.extending != null && JSweetConfig.GLOBALS_CLASS_NAME
                .equals(classdecl.extending.type.tsym.getSimpleName().toString())) {
            report(classdecl, JSweetProblem.GLOBALS_CLASS_CANNOT_BE_SUBCLASSED);
            return;
        }
        printDocComment(classdecl, false);
        print(classdecl.mods);
        if (!isTopLevelScope() || context.useModules || isAnonymousClass() || isInnerClass()
                || isLocalClass()) {
            print("export ");
        }
        if (context.isInterface(classdecl.sym)) {
            print("interface ");
            getScope().interfaceScope = true;
        } else {
            if (classdecl.getKind() == Kind.ENUM) {
                if (getScope().declareClassScope && !(getIndent() != 0 && isDefinitionScope)) {
                    print("declare ");
                }
                if (scope.size() > 1 && getScope(1).isComplexEnum) {
                    if (Util.hasAbstractMethod(classdecl.sym)) {
                        print("abstract ");
                    }
                    print("class ");
                    getScope().enumWrapperClassScope = true;
                } else {
                    print("enum ");
                    getScope().enumScope = true;
                }
            } else {
                if (getScope().declareClassScope && !(getIndent() != 0 && isDefinitionScope)) {
                    print("declare ");
                }
                defaultMethods = new HashSet<>();
                Util.findDefaultMethodsInType(defaultMethods, context, classdecl.sym);
                if (classdecl.getModifiers().getFlags().contains(Modifier.ABSTRACT)) {
                    print("abstract ");
                }
                print("class ");
            }
        }

        print(name + (getScope().enumWrapperClassScope ? ENUM_WRAPPER_CLASS_SUFFIX : ""));

        if (classdecl.typarams != null && classdecl.typarams.size() > 0) {
            print("<").printArgList(null, classdecl.typarams).print(">");
        } else if (isAnonymousClass() && classdecl.getModifiers().getFlags().contains(Modifier.STATIC)) {
            JCNewClass newClass = getScope(1).anonymousClassesConstructors
                    .get(getScope(1).anonymousClasses.indexOf(classdecl));
            printAnonymousClassTypeArgs(newClass);
        }
        String mixin = null;
        if (context.hasAnnotationType(classdecl.sym, JSweetConfig.ANNOTATION_MIXIN)) {
            mixin = context.getAnnotationValue(classdecl.sym, JSweetConfig.ANNOTATION_MIXIN, null);
        }

        boolean extendsInterface = false;
        if (classdecl.extending != null) {

            boolean removeIterable = false;
            if (context.hasAnnotationType(classdecl.sym, JSweetConfig.ANNOTATION_SYNTACTIC_ITERABLE)
                    && classdecl.extending.type.tsym.getQualifiedName().toString()
                            .equals(Iterable.class.getName())) {
                removeIterable = true;
            }

            if (!removeIterable && !JSweetConfig.isJDKReplacementMode()
                    && !(JSweetConfig.OBJECT_CLASSNAME.equals(classdecl.extending.type.toString())
                            || Object.class.getName().equals(classdecl.extending.type.toString()))
                    && !(mixin != null && mixin.equals(classdecl.extending.type.toString())) && !(getAdapter()
                            .eraseSuperClass(classdecl.sym, (ClassSymbol) classdecl.extending.type.tsym))) {
                if (!getScope().interfaceScope && context.isInterface(classdecl.extending.type.tsym)) {
                    extendsInterface = true;
                    print(" implements ");
                    implementedInterfaces.add(classdecl.extending.type);
                } else {
                    print(" extends ");
                }
                if (getScope().enumWrapperClassScope && getScope(1).anonymousClasses.contains(classdecl)) {
                    print(classdecl.extending.toString() + ENUM_WRAPPER_CLASS_SUFFIX);
                } else {
                    disableTypeSubstitution = !getAdapter().isSubstituteSuperTypes();
                    substituteAndPrintType(classdecl.extending);
                    disableTypeSubstitution = false;
                }
                if (context.classesWithWrongConstructorOverload.contains(classdecl.sym)) {
                    getScope().hasConstructorOverloadWithSuperClass = true;
                }
            } else {
                getScope().removedSuperclass = true;
            }
        }

        if (classdecl.implementing != null && !classdecl.implementing.isEmpty()) {
            List<JCExpression> implementing = new ArrayList<>(classdecl.implementing);

            if (context.hasAnnotationType(classdecl.sym, JSweetConfig.ANNOTATION_SYNTACTIC_ITERABLE)) {
                for (JCExpression itf : classdecl.implementing) {
                    if (itf.type.tsym.getQualifiedName().toString().equals(Iterable.class.getName())) {
                        implementing.remove(itf);
                    }
                }
            }
            // erase Java interfaces
            for (JCExpression itf : classdecl.implementing) {
                if (context.isFunctionalType(itf.type.tsym)
                        || getAdapter().eraseSuperInterface(classdecl.sym, (ClassSymbol) itf.type.tsym)) {
                    implementing.remove(itf);
                }
            }

            if (!implementing.isEmpty()) {
                if (!extendsInterface) {
                    if (getScope().interfaceScope) {
                        print(" extends ");
                    } else {
                        print(" implements ");
                    }
                } else {
                    print(", ");
                }
                for (JCExpression itf : implementing) {
                    disableTypeSubstitution = !getAdapter().isSubstituteSuperTypes();
                    substituteAndPrintType(itf);
                    disableTypeSubstitution = false;
                    implementedInterfaces.add(itf.type);
                    print(", ");
                }
                removeLastChars(2);
            }
        }
        print(" {").println().startIndent();
    }

    if (getScope().innerClassNotStatic && !getScope().interfaceScope && !getScope().enumScope) {
        printIndent().print("public " + PARENT_CLASS_FIELD_NAME + ": any;").println();
    }

    if (defaultMethods != null && !defaultMethods.isEmpty()) {
        getScope().defaultMethodScope = true;
        for (Entry<JCClassDecl, JCMethodDecl> entry : defaultMethods) {
            if (!(entry.getValue().type instanceof MethodType)) {
                continue;
            }
            MethodSymbol s = Util.findMethodDeclarationInType(context.types, classdecl.sym,
                    entry.getValue().getName().toString(), (MethodType) entry.getValue().type);
            if (s == null || s == entry.getValue().sym) {
                getAdapter().typeVariablesToErase
                        .addAll(((ClassSymbol) s.getEnclosingElement()).getTypeParameters());
                printIndent().print(entry.getValue()).println();
                getAdapter().typeVariablesToErase
                        .removeAll(((ClassSymbol) s.getEnclosingElement()).getTypeParameters());
            }
        }
        getScope().defaultMethodScope = false;
    }

    if (getScope().enumScope) {
        printIndent();
    }
    if (globals) {
        removeLastIndent();
    }

    if (!getScope().interfaceScope && classdecl.getModifiers().getFlags().contains(Modifier.ABSTRACT)) {
        List<MethodSymbol> methods = new ArrayList<>();
        for (Type t : implementedInterfaces) {
            context.grabMethodsToBeImplemented(methods, t.tsym);
        }
        Map<Name, String> signatures = new HashMap<>();
        for (MethodSymbol meth : methods) {
            if (meth.type instanceof MethodType) {
                MethodSymbol s = Util.findMethodDeclarationInType(getContext().types, classdecl.sym,
                        meth.getSimpleName().toString(), (MethodType) meth.type, true);
                boolean printDefaultImplementation = false;
                if (s != null) {
                    if (!s.getEnclosingElement().equals(classdecl.sym)) {
                        if (!(s.isDefault() || (!context.isInterface((TypeSymbol) s.getEnclosingElement())
                                && !s.getModifiers().contains(Modifier.ABSTRACT)))) {
                            printDefaultImplementation = true;
                        }
                    }
                }

                if (printDefaultImplementation) {
                    Overload o = context.getOverload(classdecl.sym, meth);
                    if (o != null && o.methods.size() > 1 && !o.isValid) {
                        if (!meth.type.equals(o.coreMethod.type)) {
                            printDefaultImplementation = false;
                        }
                    }
                }
                if (s == null || printDefaultImplementation) {
                    String signature = getContext().types.erasure(meth.type).toString();
                    if (!(signatures.containsKey(meth.name) && signatures.get(meth.name).equals(signature))) {
                        printDefaultImplementation(meth);
                        signatures.put(meth.name, signature);
                    }
                }
            }
        }
    }

    for (JCTree def : classdecl.defs) {
        if (def instanceof JCClassDecl) {
            getScope().hasInnerClass = true;
        }
        if (def instanceof JCVariableDecl) {
            JCVariableDecl var = (JCVariableDecl) def;
            if (!var.sym.isStatic() && var.init != null) {
                getScope().fieldsWithInitializers.add((JCVariableDecl) def);
            }
        }
    }

    if (!globals && !context.isInterface(classdecl.sym)
            && context.getStaticInitializerCount(classdecl.sym) > 0) {
        printIndent().print("static __static_initialized : boolean = false;").println();
        int liCount = context.getStaticInitializerCount(classdecl.sym);
        String prefix = classdecl.getSimpleName().toString() + ".";
        printIndent().print("static __static_initialize() { ");
        print("if(!" + prefix + "__static_initialized) { ");
        print(prefix + "__static_initialized = true; ");
        for (int i = 0; i < liCount; i++) {
            print(prefix + "__static_initializer_" + i + "(); ");
        }
        print("} }").println().println();
        String qualifiedClassName = getQualifiedTypeName(classdecl.sym, globals);
        context.addTopFooterStatement(
                (isBlank(qualifiedClassName) ? "" : qualifiedClassName + ".__static_initialize();"));
    }

    boolean hasUninitializedFields = false;

    for (JCTree def : classdecl.defs) {
        if (getScope().interfaceScope && ((def instanceof JCMethodDecl && ((JCMethodDecl) def).sym.isStatic())
                || (def instanceof JCVariableDecl && ((JCVariableDecl) def).sym.isStatic()))) {
            // static interface members are printed in a namespace
            continue;
        }
        if (def instanceof JCClassDecl) {
            // inner types are be printed in a namespace
            continue;
        }
        if (def instanceof JCVariableDecl) {
            if (getScope().enumScope && ((JCVariableDecl) def).type.tsym != classdecl.type.tsym) {
                getScope().isComplexEnum = true;
                continue;
            }
            if (!((JCVariableDecl) def).getModifiers().getFlags().contains(Modifier.STATIC)
                    && ((JCVariableDecl) def).init == null) {
                hasUninitializedFields = true;
            }
        }
        if (def instanceof JCBlock && !((JCBlock) def).isStatic()) {
            hasUninitializedFields = true;
        }
        if (!getScope().enumScope) {
            printIndent();
        }
        int pos = getCurrentPosition();
        print(def);
        if (getCurrentPosition() == pos) {
            if (!getScope().enumScope) {
                removeLastIndent();
            }
            continue;
        }
        if (def instanceof JCVariableDecl) {
            if (getScope().enumScope) {
                print(", ");
            } else {
                print(";").println().println();
            }
        } else {
            println().println();
        }
    }

    if (!getScope().hasDeclaredConstructor
            && !(getScope().interfaceScope || getScope().enumScope || getScope().declareClassScope)) {
        Set<String> interfaces = new HashSet<>();
        context.grabSupportedInterfaceNames(interfaces, classdecl.sym);
        if (!interfaces.isEmpty() || getScope().innerClassNotStatic || hasUninitializedFields) {
            printIndent().print("constructor(");
            boolean hasArgs = false;
            if (getScope().innerClassNotStatic) {
                print(PARENT_CLASS_FIELD_NAME + ": any");
                hasArgs = true;
            }
            int anonymousClassIndex = scope.size() > 1 ? getScope(1).anonymousClasses.indexOf(classdecl) : -1;
            if (anonymousClassIndex != -1) {
                for (int i = 0; i < getScope(1).anonymousClassesConstructors.get(anonymousClassIndex).args
                        .length(); i++) {
                    if (!hasArgs) {
                        hasArgs = true;
                    } else {
                        print(", ");
                    }
                    print("__arg" + i + ": any");
                }
                for (VarSymbol v : getScope(1).finalVariables.get(anonymousClassIndex)) {
                    if (!hasArgs) {
                        hasArgs = true;
                    } else {
                        print(", ");
                    }
                    print("private " + v.getSimpleName() + ": any");
                }
            }

            print(") {").startIndent().println();
            if (classdecl.extending != null && !getScope().removedSuperclass
                    && !context.isInterface(classdecl.extending.type.tsym)) {
                printIndent().print("super(");
                if (getScope().innerClassNotStatic) {
                    TypeSymbol s = classdecl.extending.type.tsym;
                    boolean hasArg = false;
                    if (s.getEnclosingElement() instanceof ClassSymbol && !s.isStatic()) {
                        print(PARENT_CLASS_FIELD_NAME);
                        hasArg = true;
                    }
                    if (anonymousClassIndex != -1) {
                        for (int i = 0; i < getScope(1).anonymousClassesConstructors
                                .get(anonymousClassIndex).args.length(); i++) {
                            if (hasArg) {
                                print(", ");
                            } else {
                                hasArg = true;
                            }
                            print("__arg" + i);
                        }
                    }
                }
                print(");").println();
            }
            printInstanceInitialization(classdecl, null);
            endIndent().printIndent().print("}").println().println();
        }
    }

    removeLastChar();

    if (getScope().enumWrapperClassScope && !getScope(1).anonymousClasses.contains(classdecl)) {
        printIndent().print("public name() : string { return this." + ENUM_WRAPPER_CLASS_NAME + "; }")
                .println();
        printIndent().print("public ordinal() : number { return this." + ENUM_WRAPPER_CLASS_ORDINAL + "; }")
                .println();
    }

    if (getScope().enumScope) {
        removeLastChar().println();
    }

    if (!globals) {
        endIndent().printIndent().print("}");
        if (getContext().options.isSupportGetClass() && !getScope().interfaceScope
                && !getScope().declareClassScope && !getScope().enumScope && !classdecl.sym.isAnonymous()) {
            println().printIndent().print(classdecl.sym.getSimpleName().toString())
                    .print("[\"" + CLASS_NAME_IN_CONSTRUCTOR + "\"] = ")
                    .print("\"" + context.getRootRelativeName(null, classdecl.sym) + "\";");

            Set<String> interfaces = new HashSet<>();
            context.grabSupportedInterfaceNames(interfaces, classdecl.sym);
            if (!interfaces.isEmpty()) {
                println().printIndent().print(classdecl.sym.getSimpleName().toString())
                        .print("[\"" + INTERFACES_FIELD_NAME + "\"] = ");
                print("[");
                for (String itf : interfaces) {
                    print("\"").print(itf).print("\",");
                }
                removeLastChar();
                print("];").println();
            }
            if (!getScope().enumWrapperClassScope) {
                println();
            }
        }
    }

    // enum class for complex enum
    if (getScope().isComplexEnum) {
        println().println().printIndent();
        visitClassDef(classdecl);
    }

    // inner, anonymous and local classes in a namespace
    // ======================
    // print valid inner classes
    boolean nameSpace = false;
    for (JCTree def : classdecl.defs) {
        if (def instanceof JCClassDecl) {
            JCClassDecl cdef = (JCClassDecl) def;
            if (context.isIgnored(cdef)) {
                continue;
            }
            if (!nameSpace) {
                nameSpace = true;
                println().println().printIndent();
                if (!isTopLevelScope() || context.useModules) {
                    print("export ");
                } else {
                    if (isDefinitionScope) {
                        print("declare ");
                    }
                }
                print("namespace ").print(name).print(" {").startIndent();
            }
            getScope().isInnerClass = true;
            println().println().printIndent().print(cdef);
            getScope().isInnerClass = false;
        }
    }
    // print anonymous classes
    for (JCClassDecl cdef : getScope().anonymousClasses) {
        if (!nameSpace) {
            nameSpace = true;
            println().println().printIndent();
            if (!isTopLevelScope() || context.useModules) {
                print("export ");
            }
            print("namespace ").print(name).print(" {").startIndent();
        }
        getScope().isAnonymousClass = true;
        println().println().printIndent().print(cdef);
        getScope().isAnonymousClass = false;
    }
    // print local classes
    for (JCClassDecl cdef : getScope().localClasses) {
        if (!nameSpace) {
            nameSpace = true;
            println().println().printIndent();
            if (!isTopLevelScope() || context.useModules) {
                print("export ");
            }
            print("namespace ").print(name).print(" {").startIndent();
        }
        getScope().isLocalClass = true;
        println().println().printIndent().print(cdef);
        getScope().isLocalClass = false;
    }
    if (nameSpace) {
        println().endIndent().printIndent().print("}").println();
    }
    // end of namespace =================================================

    if (getScope().enumScope && getScope().isComplexEnum && !getScope().anonymousClasses.contains(classdecl)) {
        println().printIndent().print(classdecl.sym.getSimpleName().toString())
                .print("[\"" + ENUM_WRAPPER_CLASS_WRAPPERS + "\"] = [");
        int index = 0;
        for (JCTree tree : classdecl.defs) {
            if (tree instanceof JCVariableDecl && ((JCVariableDecl) tree).type.equals(classdecl.type)) {
                JCVariableDecl varDecl = (JCVariableDecl) tree;
                // enum fields are not part of the enum auxiliary class but
                // will initialize the enum values
                JCNewClass newClass = (JCNewClass) varDecl.init;
                JCClassDecl clazz = classdecl;
                try {
                    int anonymousClassIndex = getScope().anonymousClasses.indexOf(newClass.def);
                    if (anonymousClassIndex >= 0) {
                        print("new ")
                                .print(clazz.getSimpleName().toString() + "." + clazz.getSimpleName().toString()
                                        + ANONYMOUS_PREFIX + anonymousClassIndex + ENUM_WRAPPER_CLASS_SUFFIX)
                                .print("(");
                    } else {
                        print("new ").print(clazz.getSimpleName().toString() + ENUM_WRAPPER_CLASS_SUFFIX)
                                .print("(");
                    }
                    print("" + (index++) + ", ");
                    print("\"" + varDecl.sym.name.toString() + "\"");
                    if (!newClass.args.isEmpty()) {
                        print(", ");
                    }
                    printArgList(null, newClass.args).print(")");
                    print(", ");
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
        removeLastChars(2);
        print("];").println();
    }

    if (getScope().interfaceScope) {
        // print static members of interfaces
        nameSpace = false;
        for (JCTree def : classdecl.defs) {
            if ((def instanceof JCMethodDecl && ((JCMethodDecl) def).sym.isStatic())
                    || (def instanceof JCVariableDecl && ((JCVariableDecl) def).sym.isStatic())) {
                if (def instanceof JCVariableDecl && context.hasAnnotationType(((JCVariableDecl) def).sym,
                        ANNOTATION_STRING_TYPE, JSweetConfig.ANNOTATION_ERASED)) {
                    continue;
                }
                if (!nameSpace) {
                    nameSpace = true;
                    println().println().printIndent();

                    if (getIndent() != 0 || context.useModules) {
                        print("export ");
                    } else {
                        if (isDefinitionScope) {
                            print("declare ");
                        }
                    }

                    print("namespace ").print(classdecl.getSimpleName().toString()).print(" {").startIndent();
                }
                println().println().printIndent().print(def);
                if (def instanceof JCVariableDecl) {
                    print(";");
                }
            }
        }
        if (nameSpace) {
            println().endIndent().printIndent().print("}").println();
        }
    }

    if (mainMethod != null && mainMethod.getParameters().size() < 2
            && mainMethod.sym.getEnclosingElement().equals(classdecl.sym)) {
        String mainClassName = getQualifiedTypeName(classdecl.sym, globals);
        String mainMethodQualifier = mainClassName;
        if (!isBlank(mainClassName)) {
            mainMethodQualifier = mainClassName + ".";
        }
        context.entryFiles.add(new File(compilationUnit.sourcefile.getName()));
        context.addFooterStatement(mainMethodQualifier + JSweetConfig.MAIN_FUNCTION_NAME + "("
                + (mainMethod.getParameters().isEmpty() ? "" : "null") + ");");
    }

    getAdapter().typeVariablesToErase.removeAll(parentTypeVars);
    exitScope();

    getAdapter().afterType(classdecl.sym);

}

From source file:com.l2jfree.gameserver.gameobjects.L2Player.java

/**
 * Manage the delete task of a L2Player (Leave Party, Unsummon pet, Save its inventory in the database, Remove it from the world...).<BR><BR>
 *
 * <B><U> Actions</U> :</B><BR><BR>
 * <li>If the L2Player is in observer mode, set its position to its position before entering in observer mode </li>
 * <li>Set the online Flag to True or False and update the characters table of the database with online status and lastAccess </li>
 * <li>Stop the HP/MP/CP Regeneration task </li>
 * <li>Cancel Crafting, Attak or Cast </li>
 * <li>Remove the L2Player from the world </li>
 * <li>Stop Party and Unsummon Pet </li>
 * <li>Update database with items in its inventory and remove them from the world </li>
 * <li>Remove all L2Object from _knownObjects and _knownPlayer of the L2Creature then cancel Attak or Cast and notify AI </li>
 * <li>Close the connection with the client </li><BR><BR>
 *
 *//*from   ww  w. j  a va 2  s.co m*/
public void deleteMe() {
    final HashSet<L2Zone> before = getZonesPlayerIn();

    if (getOnlineState() == ONLINE_STATE_DELETED)
        return;

    // Pause restrictions
    ObjectRestrictions.getInstance().pauseTasks(getObjectId());

    abortCast();
    abortAttack();

    try {
        if (isFlying())
            removeSkill(SkillTable.getInstance().getInfo(4289, 1));
    } catch (Exception e) {
        _log.fatal(e.getMessage(), e);
    }

    try {
        L2ItemInstance flag = getInventory().getItemByItemId(9819);
        if (flag != null) {
            Fort fort = FortManager.getInstance().getFort(this);
            if (fort != null)
                FortSiegeManager.getInstance().dropCombatFlag(this);
            else {
                int slot = flag.getItem().getBodyPart();
                getInventory().unEquipItemInBodySlotAndRecord(slot);
                destroyItem("CombatFlag", flag, null, true);
            }
        }
    } catch (Exception e) {
        _log.fatal(e.getMessage(), e);
    }

    // If the L2Player has Pet, unsummon it
    if (getPet() != null) {
        try {
            getPet().unSummon(this);
            // dead pet wasnt unsummoned, broadcast npcinfo changes (pet will be without owner name - means owner offline)
            if (getPet() != null)
                getPet().broadcastFullInfoImpl(0);
        } catch (Exception e) {
            _log.error(e.getMessage(), e);
        } // Return pet to the control item
    }

    // Cancel trade
    if (getActiveRequester() != null) {
        getActiveRequester().onTradeCancel(this);
        onTradeCancel(getActiveRequester());

        cancelActiveTrade();

        setActiveRequester(null);
    }

    // Check if the L2Player is in observer mode to set its position to its position before entering in observer mode
    if (inObserverMode())
        getPosition().setXYZ(_obsX, _obsY, _obsZ);
    else if (isInAirShip())
        getAirShip().oustPlayer(this);

    Castle castle = null;
    if (getClan() != null) {
        castle = CastleManager.getInstance().getCastleByOwner(getClan());
        if (castle != null)
            castle.destroyClanGate();
    }

    // Set the online Flag to True or False and update the characters table of the database with online status and lastAccess (called when login and logout)
    try {
        setOnlineStatus(false);
    } catch (Exception e) {
        _log.fatal(e.getMessage(), e);
    }

    // Stop the HP/MP/CP Regeneration task (scheduled tasks)
    try {
        stopAllTimers();
    } catch (Exception e) {
        _log.fatal(e.getMessage(), e);
    }

    GlobalRestrictions.playerDisconnected(this);

    try {
        setIsTeleporting(false);
    } catch (Exception e) {
        _log.fatal(e.getMessage(), e);
    }

    // Stop crafting, if in progress
    try {
        RecipeTable.getInstance().requestMakeItemAbort(this);
    } catch (Exception e) {
        _log.fatal(e.getMessage(), e);
    }

    try {
        setTarget(null);
    } catch (Exception e) {
        _log.fatal(e.getMessage(), e);
    }

    if (_throne != null)
        _throne.setOccupier(null);
    _throne = null;

    try {
        if (_fusionSkill != null) {
            abortCast();
        }
        for (L2Creature character : getKnownList().getKnownCharacters())
            if (character.getFusionSkill() != null && character.getFusionSkill().getTarget() == this)
                character.abortCast();
    } catch (Exception e) {
        _log.fatal(e.getMessage(), e);
    }

    getEffects().stopAllEffects(true);

    // Remove from world regions zones
    L2WorldRegion oldRegion = getWorldRegion();

    // Remove the L2Player from the world
    if (isVisible()) {
        try {
            decayMe();
        } catch (Exception e) {
            _log.fatal(e.getMessage(), e);
        }
    }

    if (oldRegion != null)
        oldRegion.removeFromZones(this);

    // If a Party is in progress, leave it (and festival party)
    if (isInParty()) {
        try {
            // If player is festival participant and it is in progress
            // notify party members that the player is not longer a participant.
            if (isFestivalParticipant() && SevenSignsFestival.getInstance().isFestivalInitialized()) {
                getParty().broadcastToPartyMembers(
                        SystemMessage.sendString(getName() + " has been removed from the upcoming festival."));
            }

            leaveParty();
        } catch (Exception e) {
            _log.fatal(e.getMessage(), e);
        }
    } else
    // if in party, already taken care of
    {
        L2PartyRoom room = getPartyRoom();
        if (room != null)
            room.removeMember(this, false);
    }
    PartyRoomManager.getInstance().removeFromWaitingList(this);

    if (getClanId() != 0 && getClan() != null) {
        // Set the status for pledge member list to OFFLINE
        try {
            L2ClanMember clanMember = getClan().getClanMember(getName());
            if (clanMember != null)
                clanMember.setPlayerInstance(null);
        } catch (Exception e) {
            _log.fatal(e.getMessage(), e);
        }
    }

    if (getActiveRequester() != null) {
        // Deals with sudden exit in the middle of transaction
        setActiveRequester(null);
    }

    // If the L2Player is a GM, remove it from the GM List
    if (isGM()) {
        try {
            GmListTable.deleteGm(this);
        } catch (Exception e) {
            _log.fatal(e.getMessage(), e);
        }
    }

    // remove player from instance and set spawn location if any
    try {
        if (isInInstance()) {
            final Instance inst = InstanceManager.getInstance().getInstance(getInstanceId());
            if (inst != null) {
                inst.removePlayer(getObjectId());
                final Location spawn = inst.getSpawnLoc();
                if (spawn != null) {
                    final int x = spawn.getX() + Rnd.get(-30, 30);
                    final int y = spawn.getY() + Rnd.get(-30, 30);
                    getPosition().setXYZ(x, y, spawn.getZ());
                    if (getPet() != null) // dead pet
                    {
                        getPet().teleToLocation(x, y, spawn.getZ());
                        // ??? unset pet's instance id, but not players
                        getPet().decayMe();
                        getPet().spawnMe();
                    }
                }
            }
        }
    } catch (Exception e) {
        _log.fatal(e.getMessage(), e);
    }

    // Update database with items in its inventory and remove them from the world
    try {
        getInventory().deleteMe();
    } catch (Exception e) {
        _log.fatal(e.getMessage(), e);
    }

    // Update database with items in its warehouse and remove them from the world
    try {
        clearWarehouse();
    } catch (Exception e) {
        _log.fatal(e.getMessage(), e);
    }

    if (Config.WAREHOUSE_CACHE)
        WarehouseCacheManager.getInstance().remove(this);

    // Update database with items in its freight and remove them from the world
    try {
        clearFreight();
    } catch (Exception e) {
        _log.fatal(e.getMessage(), e);
    }

    try {
        clearDepositedFreight();
    } catch (Exception e) {
        _log.fatal(e.getMessage(), e);
    }

    // Remove all L2Object from _knownObjects and _knownPlayer of the L2Creature then cancel Attak or Cast and notify AI
    try {
        getKnownList().removeAllKnownObjects();
    } catch (Exception e) {
        _log.fatal(e.getMessage(), e);
    }

    untransform();

    if (getClanId() > 0)
        getClan().broadcastToOtherOnlineMembers(new PledgeShowMemberListUpdate(this), this);

    if (_snoopedPlayers.length > 0) {
        for (L2Player snooped : _snoopedPlayers)
            snooped.removeSnooper(this);
        _snoopedPlayers = L2Player.EMPTY_ARRAY;
    }

    if (_snoopers.length > 0) {
        broadcastSnoop(SystemChatChannelId.Chat_Normal, "", "*** Player " + getName() + " logged off ***");
        for (L2Player snooper : _snoopers)
            snooper.removeSnooped(this);
        _snoopers = L2Player.EMPTY_ARRAY;
    }

    for (Integer objId : getFriendList().getFriendIds()) {
        L2Player friend = L2World.getInstance().findPlayer(objId);
        if (friend != null) {
            friend.sendPacket(new FriendList(friend));
            friend.sendMessage("Friend: " + getName() + " has logged off.");
        }
    }

    MovementController.getInstance().remove(this);

    // Remove L2Object object from _allObjects of L2World, if still in it
    L2World.getInstance().removeObject(this);

    try {
        // To delete the player from L2World on crit during teleport ;)
        setIsTeleporting(false);

        L2World.getInstance().removeOnlinePlayer(this);
    } catch (RuntimeException e) {
        _log.fatal("deleteMe()", e);
    }

    RegionBBSManager.changeCommunityBoard(this, PlayerStateOnCommunity.NONE);

    //getClearableReference().clear();
    LeakTaskManager.getInstance().add(this);

    SQLQueue.getInstance().run();

    final HashSet<L2Zone> after = getZonesPlayerIn();

    if (!after.isEmpty()) {
        _log.warn("Leaking zones before L2Player.deleteMe(): " + before.toString());
        _log.warn("Leaking zones after L2Player.deleteMe(): " + after.toString());
    }
}