package net.programmierecke.radiodroid2.tests;

import android.content.Context;
import android.media.AudioManager;
import android.view.View;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.espresso.action.ViewActions;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.LargeTest;
import androidx.test.rule.ActivityTestRule;
import net.programmierecke.radiodroid2.ActivityMain;
import net.programmierecke.radiodroid2.R;
import net.programmierecke.radiodroid2.tests.utils.TestUtils;
import net.programmierecke.radiodroid2.tests.utils.conditionwatcher.ConditionWatcher;
import net.programmierecke.radiodroid2.tests.utils.conditionwatcher.IsMusicPlayingCondition;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.isDescendantOfA;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayingAtLeast;
import static androidx.test.espresso.matcher.ViewMatchers.withContentDescription;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static net.programmierecke.radiodroid2.tests.utils.RecyclerViewMatcher.withRecyclerView;
import static net.programmierecke.radiodroid2.tests.utils.conditionwatcher.ViewMatchWaiter.waitForView;
import static org.hamcrest.core.AllOf.allOf;

@LargeTest
@RunWith(AndroidJUnit4.class)
public class UISmallPlayerTest {

    @Rule
    public ActivityTestRule<ActivityMain> activityRule = new ActivityTestRule<>(ActivityMain.class);

    @Before
    public void setUp() {
        TestUtils.populateHistory(ApplicationProvider.getApplicationContext(), 1);
    }

    private Matcher<View> getPlayButton() {
        return allOf(withId(R.id.buttonPlay), isDisplayingAtLeast(80));
    }

    private boolean isMusicPlaying() {
        AudioManager manager = (AudioManager) ApplicationProvider.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
        return manager.isMusicActive();
    }

    @Test
    public void stationListItem_ShouldStartPlayBack_WhenClicked() {
        onView(allOf(withId(R.id.layoutMain), isDescendantOfA(withRecyclerView(R.id.recyclerViewStations).atPosition(0)))).perform(ViewActions.click());
        onView(getPlayButton()).check(matches(withContentDescription(R.string.detail_pause)));
        ConditionWatcher.waitForCondition(new IsMusicPlayingCondition(true), ConditionWatcher.SHORT_WAIT_POLICY);
    }

    @Test
    public void playBackState_ShouldBeCorrect_AfterRapidToggling() {
        // TODO: Make clicking more rapid. there is a visible delay as of now.
        Matcher<View> btnPlay = getPlayButton();

        waitForView(btnPlay).toMatch(withContentDescription(R.string.detail_pause));
        ConditionWatcher.waitForCondition(new IsMusicPlayingCondition(true), ConditionWatcher.SHORT_WAIT_POLICY);
        for (int i = 0; i < 7; i++) {
            onView(btnPlay).perform(ViewActions.click());
        }
        ConditionWatcher.waitForCondition(new IsMusicPlayingCondition(false), ConditionWatcher.SHORT_WAIT_POLICY);
    }
}


try {
                int resId = Integer.valueOf(uri.getPathSegments().get(0));
                return this.getContext().getResources().openRawResourceFd(resId);
            } catch (Throwable t) {
                return null;
            }

package x.x.x;

import java.io.FileNotFoundException;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;

/**
 * Created by Gustavo Claramunt.
 * User: adw
 * Date: 23/01/11
 * Time: 18:31
 */
public class DocksProvider extends ContentProvider {

    @Override
    public boolean onCreate() {
        return false;
    }

    @Override
    public Cursor query(Uri uri, String[] strings, String s, String[] strings1, String s1) {
        return null;
    }

    @Override
    public String getType(Uri uri) {
        return "image/*";
    }

    @Override
    public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
        if (uri.getPathSegments().size() > 0) {

        } else {
            return null;
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues contentValues) {
        return null;
    }

    @Override
    public int delete(Uri uri, String s, String[] strings) {
        return 0;
    }

    @Override
    public int update(Uri uri, ContentValues contentValues, String s, String[] strings) {
        return 0;
    }
}


String login(JwtAuthenticationRequest authenticationRequest) throws Exception;

package com.loop.demo.admin.service;

import com.loop.demo.admin.vo.user.JwtAuthenticationRequest;

public interface AuthService {

    /**
     * 登录验证 传入账号密码对象
     * @param authenticationRequest
     * @return
     * @throws Exception
     */

    String refresh(String oldToken) throws Exception;

    /**
     * 根据token得到用户的信息
     * @param token
     * @throws Exception
     */
    void validate(String token) throws Exception;
}


for (int i = 0; i < list.size() - 1; i++) {
            // the last element will be at its final place
            int index = i;
            for (int j = i + 1; j < list.size(); j++) {
                // find the index of the minimum
                if (comparator.compare(list.get(index), list.get(j)) > 0) {
                    // update the index of the min
                    index = j;
                }
            }
            Collections.swap(list, i, index);
        }

package interviews.sorts;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Selection sort.
 * Run in O(n^2).
 * @author Francois Rousseau
 */
public class SelectionSort {

    public static <E> void f(List<E> list, Comparator<E> comparator) {


public static WmiResult<IdentifierProperty> queryHwIdentifier(WmiQueryHandler h, String typeToQuery, String typeName) {
        StringBuilder sb = new StringBuilder(HARDWARE);
        sb.append(" WHERE ").append(typeToQuery).append("Type=\"").append(typeName).append('\"');
        WmiQuery<IdentifierProperty> cpuIdentifierQuery = new WmiQuery<>(WmiUtil.OHM_NAMESPACE, sb.toString(), IdentifierProperty.class);
        return h.queryWMI(cpuIdentifierQuery, false);
    }

package oshi.driver.windows.wmi;

// NOSONAR squid:S1191
import com.sun.jna.platform.win32.COM.WbemcliUtil.WmiQuery;
import com.sun.jna.platform.win32.COM.WbemcliUtil.WmiResult;
import oshi.annotation.concurrent.ThreadSafe;
import oshi.util.platform.windows.WmiQueryHandler;
import oshi.util.platform.windows.WmiUtil;

/**
 * Utility to query Open Hardware Monitor WMI data for Hardware
 */
@ThreadSafe
public final class OhmHardware {

    private static final String HARDWARE = "Hardware";

    /**
     * HW Identifier Property
     */
    public enum IdentifierProperty {

        IDENTIFIER
    }

    private OhmHardware() {
    }

    /**
     * Queries the hardware identifiers for a monitored type.
     *
     * @param h
     *            An instantiated {@link WmiQueryHandler}. User should have already
     *            initialized COM.
     * @param typeToQuery
     *            which type to filter based on
     * @param typeName
     *            the name of the type
     * @return The sensor value.
     */


public static String joinWithTabs(String[] ss) {
        return join(ss, "\t");
    }

package edu.jhu.jacana.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;

/**
 * A collection of utilities for string processing.
 *
 * @author Nico Schlaefer
 * @version 2007-05-05
 */
// TODO use Levenstein distance to identify similar tokens
public class StringUtils {

    /**
     * Fraction of words that must occur in both strings for
     * equalsIntersect() to be true.
     */
    private static final float INTERSECT_THRESH = 0.33f;

    /**
     * Checks if the first array of tokens is a subset if the second array.
     *
     * @param tokens1 token array 1
     * @param tokens2 token array 2
     *
     * @return true, iff ss1 is a subset of ss2
     */
    private static boolean isSubset(String[] tokens1, String[] tokens2) {
        boolean exists;
        for (String token1 : tokens1) {
            exists = false;
            for (String token2 : tokens2) if (token1.equals(token2)) {
                exists = true;
                break;
            }
            if (!exists)
                return false;
        }
        return true;
    }

    /**
     * Checks if the tokens in the first string form a subset of the tokens in
     * the second string.
     *
     * @param s1 string 1
     * @param s2 string 2
     * @return true, iff the tokens in s1 are a subset of the tokens in s2
     */
    public static boolean isSubset(String s1, String s2) {
        if (s1 == null)
            return true;
        if (s2 == null)
            return false;
        String[] tokens1 = s1.split(" ");
        String[] tokens2 = s2.split(" ");
        return isSubset(tokens1, tokens2);
    }

    /**
     * Concatenates an array of strings, using the given delimiter.
     *
     * @param ss array of strings
     * @param delim delimiter
     * @return concatenated string
     */
    public static String join(String[] ss, String delim) {
        StringBuilder sb = new StringBuilder();
        if (ss.length > 0)
            sb.append(ss[0]);
        for (int i = 1; i < ss.length; i++) sb.append(delim + ss[i]);
        return sb.toString();
    }

    public static String join(String[] ss, String delim, int start, int end) {
        StringBuilder sb = new StringBuilder();
        if (ss.length > start && end > start)
            sb.append(ss[start]);
        for (int i = start; i < Math.min(ss.length, end); i++) sb.append(delim + ss[i]);
        return sb.toString();
    }

    public static <T> String join(T[] ss, String delim) {
        StringBuilder sb = new StringBuilder();
        if (ss.length > 0)
            sb.append(ss[0]);
        for (int i = 1; i < ss.length; i++) sb.append(delim + ss[i]);
        return sb.toString();
    }

    public static String join(List<String> ss, String delim) {
        StringBuilder sb = new StringBuilder();
        if (ss.size() > 0)
            sb.append(ss.get(0));
        for (int i = 1; i < ss.size(); i++) sb.append(delim + ss.get(i));
        return sb.toString();
    }

    public static String join(List<String> ss, String delim, int start, int end) {
        StringBuilder sb = new StringBuilder();
        if (ss.size() > start && end > start)
            sb.append(ss.get(start));
        for (int i = start; i < Math.min(ss.size(), end); i++) sb.append(delim + ss.get(i));
        return sb.toString();
    }

    /**
     * Concatenates an array of strings, using whitespaces as delimiters.
     *
     * @param ss array of strings
     * @return concatenated string
     */
    public static String joinWithSpaces(String[] ss) {
        return join(ss, " ");
    }

    /**
     * Concatenates an array of strings, using tabs as delimiters.
     *
     * @param ss array of strings
     * @return concatenated string
     */

/**
     * Repeats string s n times.
     *
     * @param s a string
     * @param n number of repetitions
     */
    public static String repeat(String s, int n) {
        String repeated = "";
        for (int i = 0; i < n; i++) repeated += s;
        return repeated;
    }

    /**
     * Compares two strings. The strings are considered equal, iff one of the
     * strings is a subset of the other string, i.e. iff all the tokens in the
     * one string also occur in the other string.
     *
     * @param s1 string 1
     * @param s2 string 2
     * @return true, iff the strings are equal in the sense defined above
     */
    public static boolean equalsSubset(String s1, String s2) {
        return isSubset(s1, s2) || isSubset(s2, s1);
    }

    /**
     * Compares two strings. The strings are considered equal, iff the number of
     * words that occur in both strings over the total number of words is at
     * least INTERSECT_FRAC.
     *
     * @param s1 string 1
     * @param s2 string 2
     * @return true, iff the strings are equal in the sense defined above
     */
    public static boolean equalsIntersect(String s1, String s2) {
        // tokenize both strings
        String[] tokens1 = s1.split(" ");
        String[] tokens2 = s2.split(" ");
        // number of common tokens and total number of tokens
        // (note that duplicates are not handled properly)
        int commonTokens = 0;
        int totalTokens = tokens2.length;
        for (String token1 : tokens1) for (String token2 : tokens2) if (token1.equals(token2))
            commonTokens++;
        else
            totalTokens++;
        return ((float) commonTokens) / totalTokens >= INTERSECT_THRESH;
    }

    /**
     *
Sorts an array of strings by their length in ascending order.

     *
     *
This sort is guaranteed to be stable: strings of equal length are not
     * reordered.

     *
     * @param ss array of strings
     */
    public static void sortByLength(String[] ss) {
        Comparator<String> lengthC = new Comparator<String>() {

            public int compare(String s1, String s2) {
                return s1.length() - s2.length();
            }
        };
        Arrays.sort(ss, lengthC);
    }

    /**
     *
Sorts an array of strings by their length in descending order.

     *
     *
This sort is guaranteed to be stable: strings of equal length are not
     * reordered.

     *
     * @param ss array of strings
     */
    public static void sortByLengthDesc(String[] ss) {
        Comparator<String> lengthC = new Comparator<String>() {

            public int compare(String s1, String s2) {
                return s2.length() - s1.length();
            }
        };
        Arrays.sort(ss, lengthC);
    }

    /**
     * Capitalize the first letter of input and return the new string.
     */
    public static String capitalizeFirst(String input) {
        if (input == null)
            return null;
        return input.substring(0, 1).toUpperCase() + input.substring(1);
    }

    /**
     * Check whether all letters in a string are in upper case.
     */
    public static boolean isAllUppercase(String input) {
        if (input == null)
            return false;
        String cap = input.toUpperCase();
        if (cap.equals(input))
            return true;
        else
            return false;
    }

    /**
     * Make the first letter of input lower case and return the new string.
     */
    public static String lowercaseFirst(String input) {
        if (input == null)
            return null;
        return input.substring(0, 1).toLowerCase() + input.substring(1);
    }

    public static String replaceXMLspecials(String input) {
        if (input == null)
            return null;
        return input.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """).replaceAll("\'", "'");
    }
}


package edu.jhu.jacana.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;

/**
 * A collection of utilities for string processing.
 *
 * @author Nico Schlaefer
 * @version 2007-05-05
 */
// TODO use Levenstein distance to identify similar tokens
public class StringUtils {

    /**
     * Fraction of words that must occur in both strings for
     * equalsIntersect() to be true.
     */
    private static final float INTERSECT_THRESH = 0.33f;

    /**
     * Checks if the first array of tokens is a subset if the second array.
     *
     * @param tokens1 token array 1
     * @param tokens2 token array 2
     *
     * @return true, iff ss1 is a subset of ss2
     */
    private static boolean isSubset(String[] tokens1, String[] tokens2) {
        boolean exists;
        for (String token1 : tokens1) {
            exists = false;
            for (String token2 : tokens2) if (token1.equals(token2)) {
                exists = true;
                break;
            }
            if (!exists)
                return false;
        }
        return true;
    }

    /**
     * Checks if the tokens in the first string form a subset of the tokens in
     * the second string.
     *
     * @param s1 string 1
     * @param s2 string 2
     * @return true, iff the tokens in s1 are a subset of the tokens in s2
     */
    public static boolean isSubset(String s1, String s2) {
        if (s1 == null)
            return true;
        if (s2 == null)
            return false;
        String[] tokens1 = s1.split(" ");
        String[] tokens2 = s2.split(" ");
        return isSubset(tokens1, tokens2);
    }

    /**
     * Concatenates an array of strings, using the given delimiter.
     *
     * @param ss array of strings
     * @param delim delimiter
     * @return concatenated string
     */
    public static String join(String[] ss, String delim) {
        StringBuilder sb = new StringBuilder();
        if (ss.length > 0)
            sb.append(ss[0]);

return sb.toString();
    }

    public static String join(String[] ss, String delim, int start, int end) {
        StringBuilder sb = new StringBuilder();
        if (ss.length > start && end > start)
            sb.append(ss[start]);
        for (int i = start; i < Math.min(ss.length, end); i++) sb.append(delim + ss[i]);
        return sb.toString();
    }

    public static <T> String join(T[] ss, String delim) {
        StringBuilder sb = new StringBuilder();
        if (ss.length > 0)
            sb.append(ss[0]);
        for (int i = 1; i < ss.length; i++) sb.append(delim + ss[i]);
        return sb.toString();
    }

    public static String join(List<String> ss, String delim) {
        StringBuilder sb = new StringBuilder();
        if (ss.size() > 0)
            sb.append(ss.get(0));
        for (int i = 1; i < ss.size(); i++) sb.append(delim + ss.get(i));
        return sb.toString();
    }

    public static String join(List<String> ss, String delim, int start, int end) {
        StringBuilder sb = new StringBuilder();
        if (ss.size() > start && end > start)
            sb.append(ss.get(start));
        for (int i = start; i < Math.min(ss.size(), end); i++) sb.append(delim + ss.get(i));
        return sb.toString();
    }

    /**
     * Concatenates an array of strings, using whitespaces as delimiters.
     *
     * @param ss array of strings
     * @return concatenated string
     */
    public static String joinWithSpaces(String[] ss) {
        return join(ss, " ");
    }

    /**
     * Concatenates an array of strings, using tabs as delimiters.
     *
     * @param ss array of strings
     * @return concatenated string
     */
    public static String joinWithTabs(String[] ss) {
        return join(ss, "\t");
    }

    /**
     * Repeats string s n times.
     *
     * @param s a string
     * @param n number of repetitions
     */
    public static String repeat(String s, int n) {
        String repeated = "";
        for (int i = 0; i < n; i++) repeated += s;
        return repeated;
    }

    /**
     * Compares two strings. The strings are considered equal, iff one of the
     * strings is a subset of the other string, i.e. iff all the tokens in the
     * one string also occur in the other string.
     *
     * @param s1 string 1
     * @param s2 string 2
     * @return true, iff the strings are equal in the sense defined above
     */
    public static boolean equalsSubset(String s1, String s2) {
        return isSubset(s1, s2) || isSubset(s2, s1);
    }

    /**
     * Compares two strings. The strings are considered equal, iff the number of
     * words that occur in both strings over the total number of words is at
     * least INTERSECT_FRAC.
     *
     * @param s1 string 1
     * @param s2 string 2
     * @return true, iff the strings are equal in the sense defined above
     */
    public static boolean equalsIntersect(String s1, String s2) {
        // tokenize both strings
        String[] tokens1 = s1.split(" ");
        String[] tokens2 = s2.split(" ");
        // number of common tokens and total number of tokens
        // (note that duplicates are not handled properly)
        int commonTokens = 0;
        int totalTokens = tokens2.length;
        for (String token1 : tokens1) for (String token2 : tokens2) if (token1.equals(token2))
            commonTokens++;
        else
            totalTokens++;
        return ((float) commonTokens) / totalTokens >= INTERSECT_THRESH;
    }

    /**
     *
Sorts an array of strings by their length in ascending order.

     *
     *
This sort is guaranteed to be stable: strings of equal length are not
     * reordered.

     *
     * @param ss array of strings
     */
    public static void sortByLength(String[] ss) {
        Comparator<String> lengthC = new Comparator<String>() {

            public int compare(String s1, String s2) {
                return s1.length() - s2.length();
            }
        };
        Arrays.sort(ss, lengthC);
    }

    /**
     *
Sorts an array of strings by their length in descending order.

     *
     *
This sort is guaranteed to be stable: strings of equal length are not
     * reordered.

     *
     * @param ss array of strings
     */
    public static void sortByLengthDesc(String[] ss) {
        Comparator<String> lengthC = new Comparator<String>() {

            public int compare(String s1, String s2) {
                return s2.length() - s1.length();
            }
        };
        Arrays.sort(ss, lengthC);
    }

    /**
     * Capitalize the first letter of input and return the new string.
     */
    public static String capitalizeFirst(String input) {
        if (input == null)
            return null;
        return input.substring(0, 1).toUpperCase() + input.substring(1);
    }

    /**
     * Check whether all letters in a string are in upper case.
     */
    public static boolean isAllUppercase(String input) {
        if (input == null)
            return false;
        String cap = input.toUpperCase();
        if (cap.equals(input))
            return true;
        else
            return false;
    }

    /**
     * Make the first letter of input lower case and return the new string.
     */
    public static String lowercaseFirst(String input) {
        if (input == null)
            return null;
        return input.substring(0, 1).toLowerCase() + input.substring(1);
    }

    public static String replaceXMLspecials(String input) {
        if (input == null)
            return null;
        return input.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """).replaceAll("\'", "'");
    }
}


for (; numBuilders < builders.length; numBuilders++) {
                HugeWeightMapBuilder builder = builders[numBuilders];
                if (builder == null) {
                    break;
                }
            }

/*
 *
 * This file is part of Neo4j Graph Algorithms <http://example.com>.
 *
 */
package org.neo4j.graphalgo.core.huge.loader;

import org.neo4j.graphalgo.core.utils.paged.AllocationTracker;
import org.neo4j.internal.kernel.api.CursorFactory;
import org.neo4j.internal.kernel.api.Read;
import static org.neo4j.graphalgo.core.utils.paged.MemoryUsage.sizeOfObjectArray;

abstract class WeightBuilder {

    abstract boolean loadsWeights();

    abstract void addWeightImporter(int pageIndex);

    abstract void finish();

    // TODO: check thread safety
    abstract void addWeight(CursorFactory cursors, Read read, long relationshipReference, long propertiesReference, long sourceNodeId, long targetNodeId);

    static WeightBuilder of(HugeWeightMapBuilder weights, int numPages, int pageSize, long nodeCount, AllocationTracker tracker) {
        if (!weights.loadsWeights()) {
            return NoWeights.INSTANCE;
        }
        weights.prepare(numPages, pageSize);
        tracker.add(sizeOfObjectArray(numPages));
        HugeWeightMapBuilder[] builders = new HugeWeightMapBuilder[numPages];
        return new PagedWeights(weights, builders, nodeCount, pageSize);
    }

    static WeightBuilder noWeights() {
        return NoWeights.INSTANCE;
    }

    private static final class PagedWeights extends WeightBuilder {

        private final HugeWeightMapBuilder weights;

        private final HugeWeightMapBuilder[] builders;

        private final long nodeCount;

        private final int pageSize;

        private final int pageShift;

        private final long pageMask;

        private PagedWeights(HugeWeightMapBuilder weights, HugeWeightMapBuilder[] builders, long nodeCount, int pageSize) {
            this.weights = weights;
            this.builders = builders;
            this.nodeCount = nodeCount;
            this.pageSize = pageSize;
            this.pageShift = Integer.numberOfTrailingZeros(pageSize);
            this.pageMask = (long) (pageSize - 1);
        }

        @Override
        boolean loadsWeights() {
            return true;
        }

        void addWeightImporter(int pageIndex) {
            int pageSize = (int) Math.min((long) this.pageSize, nodeCount - (((long) pageIndex) << pageShift));
            if (pageSize > 0) {
                builders[pageIndex] = weights.threadLocalCopy(pageIndex, pageSize);
            }
        }

        @Override
        void finish() {
            int numBuilders = 0;

            weights.finish(numBuilders);
        }

        @Override
        void addWeight(final CursorFactory cursors, final Read read, final long relationshipReference, final long propertiesReference, final long sourceNodeId, final long targetNodeId) {
            int pageIdx = (int) (sourceNodeId >>> pageShift);
            int localId = (int) (sourceNodeId & pageMask);
            builders[pageIdx].load(relationshipReference, propertiesReference, targetNodeId, localId, cursors, read);
        }
    }

    private static final class NoWeights extends WeightBuilder {

        private static final WeightBuilder INSTANCE = new NoWeights();

        @Override
        boolean loadsWeights() {
            return false;
        }

        @Override
        void addWeightImporter(int pageIndex) {
        }

        @Override
        void finish() {
        }

        @Override
        void addWeight(final CursorFactory cursors, final Read read, final long relationshipReference, final long propertiesReference, final long sourceNodeId, final long targetNodeId) {
        }
    }
}


for (int j = 0; j < n; j++) {
            a[i][j] = sc.nextInt();
        }

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone {

    public static void main(String[] args) throws java.lang.Exception {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[][] a = new int[n + 1][n + 1];
        for (int i = 0; i < n; i++)

        int ans = 0;
        for (int i = 0; i < n; i++) for (int j = i + 1; j <= n; j++) {
            int cnt = 0;
            for (int k = 0; k < n; k++) if (a[i][k] == 1 && a[k][j] == 1)
                cnt++;
            ans += cnt * (cnt - 1) / 2;
        }
        System.out.println(ans / 2);
    }
}


public Multiset<N> adjacentNodesMultiset() {
        Multiset<N> multiset = (Multiset) getReference(this.adjacentNodesReference);
        if (multiset != null) {
            return multiset;
        }
        HashMultiset create = HashMultiset.create(this.incidentEdgeMap.values());
        this.adjacentNodesReference = new SoftReference(create);
        return create;
    }

package com.google.common.graph;

import com.google.common.base.Preconditions;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Multiset;
import com.google.errorprone.annotations.concurrent.LazyInit;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;

final class UndirectedMultiNetworkConnections<N, E> extends AbstractUndirectedNetworkConnections<N, E> {

    @LazyInit
    private transient Reference<Multiset<N>> adjacentNodesReference;

    private UndirectedMultiNetworkConnections(Map<E, N> map) {
        super(map);
    }

    static <N, E> UndirectedMultiNetworkConnections<N, E> of() {
        return new UndirectedMultiNetworkConnections<>(new HashMap(2, 1.0f));
    }

    static <N, E> UndirectedMultiNetworkConnections<N, E> ofImmutable(Map<E, N> map) {
        return new UndirectedMultiNetworkConnections<>(ImmutableMap.copyOf(map));
    }

    public Set<N> adjacentNodes() {
        return Collections.unmodifiableSet(adjacentNodesMultiset().elementSet());
    }

    /* access modifiers changed from: private */

    public Set<E> edgesConnecting(final N n) {
        return new MultiEdgesConnecting<E>(this.incidentEdgeMap, n) {

            public int size() {
                return UndirectedMultiNetworkConnections.this.adjacentNodesMultiset().count(n);
            }
        };
    }

    public N removeInEdge(E e, boolean z) {
        if (!z) {
            return removeOutEdge(e);
        }
        return null;
    }

    public N removeOutEdge(E e) {
        N removeOutEdge = super.removeOutEdge(e);
        Multiset multiset = (Multiset) getReference(this.adjacentNodesReference);
        if (multiset != null) {
            Preconditions.checkState(multiset.remove(removeOutEdge));
        }
        return removeOutEdge;
    }

    public void addInEdge(E e, N n, boolean z) {
        if (!z) {
            addOutEdge(e, n);
        }
    }

    public void addOutEdge(E e, N n) {
        super.addOutEdge(e, n);
        Multiset multiset = (Multiset) getReference(this.adjacentNodesReference);
        if (multiset != null) {
            Preconditions.checkState(multiset.add(n));
        }
    }

    @NullableDecl
    private static <T> T getReference(@NullableDecl Reference<T> reference) {
        if (reference == null) {
            return null;
        }
        return reference.get();
    }
}


try {
            context = new InitialContext();
            ds = (DataSource) context.lookup("java:comp/env/DataSource");
        } catch (NamingException e) {
            throw new EJBException("cant find datasource");
        }

package com.sun.s1asdev.jdbc.resenabledisable.ejb;

import jakarta.ejb.*;
import javax.naming.*;
import javax.sql.*;
import java.sql.*;

public class SimpleBMPBean implements SessionBean {

    protected DataSource ds;

    private transient jakarta.ejb.SessionContext m_ctx = null;

    public void setSessionContext(SessionContext context) {
        m_ctx = context;
    }

    public Integer ejbCreate() throws CreateException {
        return new Integer(1);
    }

    /* Get a single connection and close it */
    public boolean test1() {
        Connection conn = null;
        boolean passed = true;
        Context context = null;

        try {
            conn = ds.getConnection();
            insertEntry(conn);
            emptyTable(conn);
        } catch (Exception e) {
            System.out.println("Exception caught : " + e.getMessage());
            passed = false;
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception ex) {
                    System.out.println("Exception in closing connection");
                }
            }
        }
        return passed;
    }

    private void insertEntry(Connection conn) throws SQLException {
        Statement stmt = conn.createStatement();
        stmt.executeUpdate("INSERT into O_CUSTOMER" + "  values (1, 'abcd')");
        stmt.close();
    }

    private void emptyTable(Connection conn) throws SQLException {
        Statement stmt = conn.createStatement();
        stmt.executeUpdate("DELETE FROM O_CUSTOMER");
        stmt.close();
    }

    public void ejbLoad() {
    }

    public void ejbStore() {
    }

    public void ejbRemove() {
    }

    public void ejbActivate() {
    }

    public void ejbPassivate() {
    }

    public void unsetEntityContext() {
    }

    public void ejbPostCreate() {
    }
}


for (int i = 1; i < model.getColumnCount(); ++i) table.setColumnWidth(i, new WLength(120));

package eu.webtoolkit.jwt.examples.charts;

import eu.webtoolkit.jwt.AlignmentFlag;
import eu.webtoolkit.jwt.EditTrigger;
import eu.webtoolkit.jwt.SelectionMode;
import eu.webtoolkit.jwt.Side;
import eu.webtoolkit.jwt.WAbstractItemModel;
import eu.webtoolkit.jwt.WApplication;
import eu.webtoolkit.jwt.WColor;
import eu.webtoolkit.jwt.WContainerWidget;
import eu.webtoolkit.jwt.WLength;
import eu.webtoolkit.jwt.WShadow;
import eu.webtoolkit.jwt.WString;
import eu.webtoolkit.jwt.WTableView;
import eu.webtoolkit.jwt.WText;
import eu.webtoolkit.jwt.chart.Axis;
import eu.webtoolkit.jwt.chart.SeriesType;
import eu.webtoolkit.jwt.chart.WCartesianChart;
import eu.webtoolkit.jwt.chart.WDataSeries;
import eu.webtoolkit.jwt.examples.charts.csv.CsvUtil;

/**
 * A Widget that demonstrates a category chart
 */
public class CategoryExample extends WContainerWidget {

    /**
     * Creates the category chart example
     */
    public CategoryExample(WContainerWidget parent) {
        super(parent);
        new WText(WString.tr("category chart"), this);
        WAbstractItemModel model = CsvUtil.readCsvFile("category.csv", this);
        if (model == null)
            return;
        WContainerWidget w = new WContainerWidget(this);
        WTableView table = new WTableView(w);
        table.setMargin(new WLength(10), Side.Top, Side.Bottom);
        table.setMargin(WLength.Auto, Side.Left, Side.Right);
        table.setModel(model);
        table.setSortingEnabled(true);
        table.setColumnResizeEnabled(true);
        table.setSelectionMode(SelectionMode.None);
        table.setAlternatingRowColors(true);
        table.setColumnAlignment(0, AlignmentFlag.Center);
        table.setHeaderAlignment(0, AlignmentFlag.Center);
        table.setRowHeight(new WLength(22));
        // Editing does not really work without Ajax, it would require an
        // additional button somewhere to confirm the edited value.
        if (WApplication.getInstance().getEnvironment().hasAjax()) {
            table.resize(600, 20 + 5 * 22);
            table.setEditTriggers(EditTrigger.SingleClicked);
        } else {
            table.resize(new WLength(600), WLength.Auto);
            table.setEditTriggers(EditTrigger.None);
        }
        table.setColumnWidth(0, new WLength(80));

        /*
         * Create the category chart.
         */
        WCartesianChart chart = new WCartesianChart(this);
        // set the model
        chart.setModel(model);
        // set the column that holds the categories
        chart.setXSeriesColumn(0);
        // enable the legend
        chart.setLegendEnabled(true);
        chart.getAxis(Axis.Y).setLabelFormat("%.0f");
        chart.setAutoLayoutEnabled();
        /*
         * Add all (but first) column as bar series
         */
        for (int i = 1; i < model.getColumnCount(); ++i) {
            WDataSeries s = new WDataSeries(i, SeriesType.Bar);
            s.setShadow(new WShadow(3, 3, new WColor(0, 0, 0, 127), 3));
            chart.addSeries(s);
        }
        // WPaintedWidget must be given explicit size
        chart.resize(800, 400);
        // add margin vertically
        chart.setMargin(10, Side.Top, Side.Bottom);
        // center
        chart.setMargin(WLength.Auto, Side.Left, Side.Right);
        // horizontally
        new ChartConfig(chart, this);
    }
}


switch(rw) {
                    case 0:
                        value = getForUser(provider, 0, key);
                        break;
                    case 1:
                        putForUser(provider, 0, key, value);
                        break;
                    default:
                        Log.e(TAG, "Unspecified command");
                        break;
                }

package com.android.server.pm;

import android.app.ActivityManager;
import android.app.ActivityManagerNative;
import android.app.ContentProviderHolder;
import android.app.IActivityManager;
import android.content.Context;
import android.content.IContentProvider;
import android.content.Intent;
import android.content.pm.UserInfo;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.SystemProperties;
import android.util.Log;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public final class HwAdbManager {

    private static final String ADB_INSTALL_NEED_CONFIRM_KEY = "adb_install_need_confirm";

    private static final int SETTING_READ = 0;

    private static final int SETTING_WRITE = 1;

    private static final String TAG = "HwAdbManager";

    private static String sHdbKey = BackupManagerConstants.DEFAULT_BACKUP_FINISHED_NOTIFICATION_RECEIVERS;

    public static void setHdbKey(String key) {
        if (key == null) {
            Log.d(TAG, "set HDB KEY is null, return!");
        } else {
            sHdbKey = key;
        }
    }

    public static String getHdbKey() {
        return sHdbKey;
    }

    static boolean startHdbVerification(String[] args, int hdbArgIndex, String hdbEncode) {
        String randstr = getHdbKey();
        if (BackupManagerConstants.DEFAULT_BACKUP_FINISHED_NOTIFICATION_RECEIVERS.equals(randstr)) {
            Log.e(TAG, "startHdbVerification default empty hdb rand value");
            return false;
        }
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            digest.reset();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(randstr);
            stringBuilder.append("=");
            StringBuilder key = new StringBuilder(stringBuilder.toString());
            for (int i = hdbArgIndex; i < args.length - 1; i++) {
                key.append(args[i]);
                key.append(' ');
            }
            key.append(args[args.length - 1]);
            byte[] encodeArray = digest.digest(key.toString().getBytes());
            StringBuilder stringBuilder2 = new StringBuilder();
            stringBuilder2.append("%0");
            stringBuilder2.append(encodeArray.length << 1);
            stringBuilder2.append("x");
            return hdbEncode.equals(String.format(stringBuilder2.toString(), new Object[] { new BigInteger(1, encodeArray) }));
        } catch (NoSuchAlgorithmException e) {
            Log.e(TAG, "hdb verify, key check error!");
            return false;
        } catch (Exception e2) {
            Log.e(TAG, "hdb verify error!");
            return false;
        }
    }

    public static boolean startPackageInstallerForConfirm(Context context, int sessionId) {
        Intent intent = new Intent("android.content.pm.action.CONFIRM_PERMISSIONS");
        intent.setPackage("com.android.packageinstaller");
        intent.putExtra("android.content.pm.extra.SESSION_ID", sessionId);
        intent.putExtra("hw_adb_install", true);
        intent.setFlags(268468224);
        try {
            int j = ActivityManagerNative.getDefault().startActivity(0, "adb", intent, null, null, null, 0, 0, null, null);
            if (j == 0) {
                return true;
            }
            String str = TAG;
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("start PackageInstallerActivity failed [");
            stringBuilder.append(j);
            stringBuilder.append("]");
            Log.i(str, stringBuilder.toString());
            return false;
        } catch (RemoteException e) {
            Log.e(TAG, "Fail to PackageInstallerActivity, RemoteException!");
            return false;
        }
    }

    private static boolean isRepairMode() {
        IActivityManager am = ActivityManager.getService();
        boolean z = false;
        if (am != null) {
            try {
                UserInfo userInfo = am.getCurrentUser();
                if (userInfo != null && userInfo.isRepairMode()) {
                    z = true;
                }
                return z;
            } catch (RemoteException e) {
                String str = TAG;
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("check isRepairMode error:");
                stringBuilder.append(e.getMessage());
                Log.e(str, stringBuilder.toString());
            }
        }
        return false;
    }

    public static boolean autoPermitInstall() {
        String deviceRootValue = SystemProperties.get("ro.adb.secure");
        if (BackupManagerConstants.DEFAULT_BACKUP_FINISHED_NOTIFICATION_RECEIVERS.equals(deviceRootValue) || "0".equals(deviceRootValue)) {
            Log.v(TAG, "autoPermitInstall root device!");
            return true;
        } else if (isRepairMode()) {
            Log.v(TAG, "autoPermitInstall in repair mode!");
            return true;
        } else if (checkSwitchIsOpen()) {
            return false;
        } else {
            Log.v(TAG, "autoPermitInstall switch is open!");
            return true;
        }
    }

    private static boolean checkSwitchIsOpen() {
        String value = secureSettingRW(ADB_INSTALL_NEED_CONFIRM_KEY, null, 0);
        if (value == null || 1 == Integer.parseInt(value)) {
            return true;
        }
        return false;
    }

    private static String secureSettingRW(String key, String value, int rw) {
        IActivityManager activityManager;
        IBinder token;
        try {
            activityManager = ActivityManagerNative.getDefault();
            token = new Binder();
            ContentProviderHolder holder = activityManager.getContentProviderExternal("settings", 0, token);
            if (holder != null) {
                IContentProvider provider = holder.provider;

                if (provider != null) {
                    activityManager.removeContentProviderExternal("settings", token);
                }
                return value;
            }
            throw new IllegalStateException("Could not find settings provider");
        } catch (Exception e) {
            Log.e(TAG, "Error while accessing settings provider");
        } catch (Throwable th) {
            if (null != null) {
                activityManager.removeContentProviderExternal("settings", token);
            }
        }
    }

    private static String getForUser(IContentProvider provider, int userHandle, String key) {
        String result = null;
        try {
            Bundle arg = new Bundle();
            arg.putInt("_user", userHandle);
            Bundle b = provider.call(null, "GET_secure", key, arg);
            if (b != null) {
                return b.getPairValue();
            }
            return result;
        } catch (RemoteException e) {
            String str = TAG;
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("Can't read key ");
            stringBuilder.append(key);
            stringBuilder.append(" in secure for user ");
            stringBuilder.append(userHandle);
            Log.e(str, stringBuilder.toString());
            return result;
        }
    }

    private static void putForUser(IContentProvider provider, int userHandle, String key, String value) {
        try {
            Bundle arg = new Bundle();
            arg.putString("value", value);
            arg.putInt("_user", userHandle);
            provider.call(null, "PUT_secure", key, arg);
        } catch (RemoteException e) {
            String str = TAG;
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("Can't set key ");
            stringBuilder.append(key);
            stringBuilder.append(" in secure for user ");
            stringBuilder.append(userHandle);
            Log.e(str, stringBuilder.toString());
        }
    }
}


for (int i = hdbArgIndex; i < args.length - 1; i++) {
                key.append(args[i]);
                key.append(' ');
            }

package com.android.server.pm;

import android.app.ActivityManager;
import android.app.ActivityManagerNative;
import android.app.ContentProviderHolder;
import android.app.IActivityManager;
import android.content.Context;
import android.content.IContentProvider;
import android.content.Intent;
import android.content.pm.UserInfo;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.SystemProperties;
import android.util.Log;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public final class HwAdbManager {

    private static final String ADB_INSTALL_NEED_CONFIRM_KEY = "adb_install_need_confirm";

    private static final int SETTING_READ = 0;

    private static final int SETTING_WRITE = 1;

    private static final String TAG = "HwAdbManager";

    private static String sHdbKey = BackupManagerConstants.DEFAULT_BACKUP_FINISHED_NOTIFICATION_RECEIVERS;

    public static void setHdbKey(String key) {
        if (key == null) {
            Log.d(TAG, "set HDB KEY is null, return!");
        } else {
            sHdbKey = key;
        }
    }

    public static String getHdbKey() {
        return sHdbKey;
    }

    static boolean startHdbVerification(String[] args, int hdbArgIndex, String hdbEncode) {
        String randstr = getHdbKey();
        if (BackupManagerConstants.DEFAULT_BACKUP_FINISHED_NOTIFICATION_RECEIVERS.equals(randstr)) {
            Log.e(TAG, "startHdbVerification default empty hdb rand value");
            return false;
        }
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            digest.reset();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(randstr);
            stringBuilder.append("=");
            StringBuilder key = new StringBuilder(stringBuilder.toString());

            key.append(args[args.length - 1]);
            byte[] encodeArray = digest.digest(key.toString().getBytes());
            StringBuilder stringBuilder2 = new StringBuilder();
            stringBuilder2.append("%0");
            stringBuilder2.append(encodeArray.length << 1);
            stringBuilder2.append("x");
            return hdbEncode.equals(String.format(stringBuilder2.toString(), new Object[] { new BigInteger(1, encodeArray) }));
        } catch (NoSuchAlgorithmException e) {
            Log.e(TAG, "hdb verify, key check error!");
            return false;
        } catch (Exception e2) {
            Log.e(TAG, "hdb verify error!");
            return false;
        }
    }

    public static boolean startPackageInstallerForConfirm(Context context, int sessionId) {
        Intent intent = new Intent("android.content.pm.action.CONFIRM_PERMISSIONS");
        intent.setPackage("com.android.packageinstaller");
        intent.putExtra("android.content.pm.extra.SESSION_ID", sessionId);
        intent.putExtra("hw_adb_install", true);
        intent.setFlags(268468224);
        try {
            int j = ActivityManagerNative.getDefault().startActivity(0, "adb", intent, null, null, null, 0, 0, null, null);
            if (j == 0) {
                return true;
            }
            String str = TAG;
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("start PackageInstallerActivity failed [");
            stringBuilder.append(j);
            stringBuilder.append("]");
            Log.i(str, stringBuilder.toString());
            return false;
        } catch (RemoteException e) {
            Log.e(TAG, "Fail to PackageInstallerActivity, RemoteException!");
            return false;
        }
    }

    private static boolean isRepairMode() {
        IActivityManager am = ActivityManager.getService();
        boolean z = false;
        if (am != null) {
            try {
                UserInfo userInfo = am.getCurrentUser();
                if (userInfo != null && userInfo.isRepairMode()) {
                    z = true;
                }
                return z;
            } catch (RemoteException e) {
                String str = TAG;
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("check isRepairMode error:");
                stringBuilder.append(e.getMessage());
                Log.e(str, stringBuilder.toString());
            }
        }
        return false;
    }

    public static boolean autoPermitInstall() {
        String deviceRootValue = SystemProperties.get("ro.adb.secure");
        if (BackupManagerConstants.DEFAULT_BACKUP_FINISHED_NOTIFICATION_RECEIVERS.equals(deviceRootValue) || "0".equals(deviceRootValue)) {
            Log.v(TAG, "autoPermitInstall root device!");
            return true;
        } else if (isRepairMode()) {
            Log.v(TAG, "autoPermitInstall in repair mode!");
            return true;
        } else if (checkSwitchIsOpen()) {
            return false;
        } else {
            Log.v(TAG, "autoPermitInstall switch is open!");
            return true;
        }
    }

    private static boolean checkSwitchIsOpen() {
        String value = secureSettingRW(ADB_INSTALL_NEED_CONFIRM_KEY, null, 0);
        if (value == null || 1 == Integer.parseInt(value)) {
            return true;
        }
        return false;
    }

    private static String secureSettingRW(String key, String value, int rw) {
        IActivityManager activityManager;
        IBinder token;
        try {
            activityManager = ActivityManagerNative.getDefault();
            token = new Binder();
            ContentProviderHolder holder = activityManager.getContentProviderExternal("settings", 0, token);
            if (holder != null) {
                IContentProvider provider = holder.provider;
                switch(rw) {
                    case 0:
                        value = getForUser(provider, 0, key);
                        break;
                    case 1:
                        putForUser(provider, 0, key, value);
                        break;
                    default:
                        Log.e(TAG, "Unspecified command");
                        break;
                }
                if (provider != null) {
                    activityManager.removeContentProviderExternal("settings", token);
                }
                return value;
            }
            throw new IllegalStateException("Could not find settings provider");
        } catch (Exception e) {
            Log.e(TAG, "Error while accessing settings provider");
        } catch (Throwable th) {
            if (null != null) {
                activityManager.removeContentProviderExternal("settings", token);
            }
        }
    }

    private static String getForUser(IContentProvider provider, int userHandle, String key) {
        String result = null;
        try {
            Bundle arg = new Bundle();
            arg.putInt("_user", userHandle);
            Bundle b = provider.call(null, "GET_secure", key, arg);
            if (b != null) {
                return b.getPairValue();
            }
            return result;
        } catch (RemoteException e) {
            String str = TAG;
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("Can't read key ");
            stringBuilder.append(key);
            stringBuilder.append(" in secure for user ");
            stringBuilder.append(userHandle);
            Log.e(str, stringBuilder.toString());
            return result;
        }
    }

    private static void putForUser(IContentProvider provider, int userHandle, String key, String value) {
        try {
            Bundle arg = new Bundle();
            arg.putString("value", value);
            arg.putInt("_user", userHandle);
            provider.call(null, "PUT_secure", key, arg);
        } catch (RemoteException e) {
            String str = TAG;
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("Can't set key ");
            stringBuilder.append(key);
            stringBuilder.append(" in secure for user ");
            stringBuilder.append(userHandle);
            Log.e(str, stringBuilder.toString());
        }
    }
}


try {
            interceptor.preInvoke(callStack);
        } catch (Throwable t) {
            _logger.log(Level.FINE, "Preinvoke failed for MBeanServer interceptor [{0}].", t.getMessage());
            _logger.log(Level.FINEST, "Preinvoke exception for MBeanServer interceptor.", t);
        }

package com.sun.enterprise.admin.util.proxy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ProxyClass implements InvocationHandler {

    private static InheritableThreadLocal callStackHolder = new InheritableThreadLocal() {

        protected synchronized Object initialValue() {
            return new CallStack();
        }
    };

    private static Logger _logger = getLogger();

    private Object delegate;

    private Interceptor interceptor;

    /**
     * Creates a new instance of Proxy
     */
    public ProxyClass(Object handler, Interceptor interceptor) {
        delegate = handler;
        this.interceptor = interceptor;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Call call = new Call(method, args);
        CallStack callStack = (CallStack) callStackHolder.get();
        callStack.beginCall(call);

        Object result = null;
        boolean success = true;
        Throwable failReason = null;
        try {
            result = method.invoke(delegate, args);
        } catch (InvocationTargetException ite) {
            success = false;
            failReason = ite.getTargetException();
            throw failReason;
        } catch (Throwable t) {
            success = false;
            failReason = t;
            throw failReason;
        } finally {
            if (!success) {
                call.setState(CallState.FAILED);
                call.setFailureReason(failReason);
            }
            call.setResult(result);
            if (!(call.getState().isFailed()))
                call.setState(CallState.SUCCESS);
            try {
                interceptor.postInvoke(callStack);
            } catch (Throwable t) {
                _logger.log(Level.FINE, "Postinvoke failed for MBeanServer interceptor [{0}].", t.getMessage());
                _logger.log(Level.FINEST, "Postinvoke exception for MBeanServer interceptor.", t);
            }
            callStack.endCall();
        }
        return result;
    }

    private static Logger getLogger() {
        String loggerName = System.getProperty("com.sun.aas.admin.logger.name");
        if (loggerName == null) {
            loggerName = "global";
        }
        return Logger.getLogger(loggerName);
    }
}


default Object getKeyWithContext(K input, Object context) {
        return getKey(input);
    }

package org.dataloader;

/**
 * Function that is invoked on input keys of type {@code K} to derive keys that are required by the {@link CacheMap}
 * implementation.
 *
 * @param <K> type parameter indicating the type of the input key
 *
 * @author Arnold Schrijver
 */
@FunctionalInterface
public interface CacheKey<K> {

    /**
     * Returns the cache key that is created from the provided input key.
     *
     * @param input the input key
     *
     * @return the cache key
     */
    Object getKey(K input);

    /**
     * Returns the cache key that is created from the provided input key and context.
     *
     * @param input the input key
     *
     * @param context the context
     *
     * @return the cache key
     */


public void onMonitorPacketReceive(CommonPacket packet, Player player);

package com.bergerkiller.bukkit.common.protocol;

import org.bukkit.entity.Player;

/**
 * Allows a plugin to monitor the packets being received and sent, but not alter
 * the outcome
 */
public interface PacketMonitor {

    /**
     * Called when a packet is going to be sent to a player. This method does
     * not allow the packet to be altered - use a {@link PacketListener} for
     * that!
     *
     * @param packet to send
     * @param player to send to
     */
    public void onMonitorPacketSend(CommonPacket packet, Player player);

    /**
     * Called when a packet is about to be received by the server from a player.
     * This method does not allow the packet to be altered - use a
     * {@link PacketListener} for that!
     *
     * @param packet to receive
     * @param player from which the packet came
     */


@SuppressWarnings("PMD.UselessParentheses")
    private boolean shouldShrinkBuffer() {
        // We want to shrink the buffer if it has been under-utilized UNDER_USE_THRESHOLD
        // times in a row, and the size after shrinking would not be smaller than the minimum size
        return bufferUnderUsedCounter > UNDER_USE_THRESHOLD && shrinkBufferSize() >= minimumSize;
    }

package com.facebook.nifty.core;

import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import javax.annotation.concurrent.NotThreadSafe;

/**
 * Implementation of {@link TTransport} that buffers the output of a single message,
 * so that an async client can grab the buffer and send it
 *
 * Allows for reusing the same transport to write multiple messages via
 * {@link com.facebook.nifty.core.TChannelBufferOutputTransport#resetOutputBuffer()}
 */
@NotThreadSafe
public class TChannelBufferOutputTransport extends TTransport {

    private static final int DEFAULT_MINIMUM_SIZE = 1024;

    // This threshold sets how many times the buffer must be under-utilized before we'll
    // reclaim some memory by reallocating it with half the current size
    private static final int UNDER_USE_THRESHOLD = 5;

    private ChannelBuffer outputBuffer;

    private final int minimumSize;

    private int bufferUnderUsedCounter;

    public TChannelBufferOutputTransport() {
        this.minimumSize = DEFAULT_MINIMUM_SIZE;
        outputBuffer = ChannelBuffers.dynamicBuffer(this.minimumSize);
    }

    public TChannelBufferOutputTransport(int minimumSize) {
        this.minimumSize = Math.min(DEFAULT_MINIMUM_SIZE, minimumSize);
        outputBuffer = ChannelBuffers.dynamicBuffer(this.minimumSize);
    }

    @Override
    public boolean isOpen() {
        return true;
    }

    @Override
    public void open() throws TTransportException {
        throw new UnsupportedOperationException();
    }

    @Override
    public void close() {
        throw new UnsupportedOperationException();
    }

    @Override
    public int read(byte[] buf, int off, int len) throws TTransportException {
        throw new UnsupportedOperationException();
    }

    @Override
    public void write(byte[] buf, int off, int len) throws TTransportException {
        outputBuffer.writeBytes(buf, off, len);
    }

    /**
     * Resets the state of this transport so it can be used to write more messages
     */
    public void resetOutputBuffer() {
        int shrunkenSize = shrinkBufferSize();
        if (outputBuffer.writerIndex() < shrunkenSize) {
            // Less than the shrunken size of the buffer was actually used, so increment
            // the under-use counter
            ++bufferUnderUsedCounter;
        } else {
            // More than the shrunken size of the buffer was actually used, reset
            // the counter so we won't shrink the buffer soon
            bufferUnderUsedCounter = 0;
        }
        if (shouldShrinkBuffer()) {
            outputBuffer = ChannelBuffers.dynamicBuffer(shrunkenSize);
            bufferUnderUsedCounter = 0;
        } else {
            outputBuffer.clear();
        }
    }

    public ChannelBuffer getOutputBuffer() {
        return outputBuffer;
    }

    /**
     * Checks whether we should shrink the buffer, which should happen if we've under-used it
     * UNDER_USE_THRESHOLD times in a row
     */

    /**
     * Returns the size the buffer will be if we shrink it
     */
    private int shrinkBufferSize() {
        return outputBuffer.capacity() >> 1;
    }
}


protected AdminDistributionHelper getHelper() {
        return new AdminDistributionHelper();
    }

/*
 * All rights reserved.
 *
*/
package gov.hhs.fha.nhinc.admindistribution.adapter.proxy;

import gov.hhs.fha.nhinc.adapteradmindistribution.AdapterAdministrativeDistributionSecuredPortType;
import gov.hhs.fha.nhinc.admindistribution.AdminDistributionHelper;
import gov.hhs.fha.nhinc.admindistribution.adapter.proxy.service.AdapterAdminDistributionSecuredServicePortDescriptor;
import gov.hhs.fha.nhinc.admindistribution.aspect.EDXLDistributionEventDescriptionBuilder;
import gov.hhs.fha.nhinc.aspect.AdapterDelegationEvent;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.common.nhinccommonadapter.RespondingGatewaySendAlertMessageSecuredType;
import gov.hhs.fha.nhinc.event.error.ErrorEventException;
import gov.hhs.fha.nhinc.messaging.client.CONNECTCXFClientFactory;
import gov.hhs.fha.nhinc.messaging.client.CONNECTClient;
import gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants.ADAPTER_API_LEVEL;
import gov.hhs.fha.nhinc.webserviceproxy.WebServiceProxyHelper;
import javax.xml.ws.WebServiceException;
import oasis.names.tc.emergency.edxl.de._1.EDXLDistribution;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author dunnek
 */
public class AdapterAdminDistributionProxyWebServiceSecuredImpl implements AdapterAdminDistributionProxy {

    private static final Logger LOG = LoggerFactory.getLogger(AdapterAdminDistributionProxyWebServiceSecuredImpl.class);

    private AdminDistributionHelper adminDistributionHelper;

    public AdapterAdminDistributionProxyWebServiceSecuredImpl() {
        adminDistributionHelper = getHelper();
    }

    /**
     * @return an instance of AdminDistributionHelper.
     */

    /**
     * This method returns CXFClient to implement AdpaterAdmin Dist Secured Service.
     *
     * @param portDescriptor comprises of NameSpaceUri, WSDLFile to read,Port, ServiceName and WS_ADDRESSING_ACTION.
     * @param url targetCommunity Url received.
     * @param assertion Assertion received.
     * @return CXFClient for AdapterAdminDist Secured Service.
     */
    protected CONNECTClient<AdapterAdministrativeDistributionSecuredPortType> getCONNECTClientSecured(ServicePortDescriptor<AdapterAdministrativeDistributionSecuredPortType> portDescriptor, String url, AssertionType assertion) {
        return CONNECTCXFClientFactory.getInstance().getCONNECTClientSecured(portDescriptor, url, assertion);
    }

    protected String getUrl() {
        return adminDistributionHelper.getAdapterUrl(NhincConstants.ADAPTER_ADMIN_DIST_SECURED_SERVICE_NAME, ADAPTER_API_LEVEL.LEVEL_a0);
    }

    /**
     * This method implements SendAlertMessage for AdminDist.
     *
     * @param body Emergency Message Distribution Element transaction message body received.
     * @param assertion Assertion received.
     */
    @AdapterDelegationEvent(beforeBuilder = EDXLDistributionEventDescriptionBuilder.class, afterReturningBuilder = EDXLDistributionEventDescriptionBuilder.class, serviceType = "Admin Distribution", version = "LEVEL_a0")
    @Override
    public void sendAlertMessage(EDXLDistribution body, AssertionType assertion) {
        LOG.debug("Begin sendAlertMessage");
        String url = getUrl();
        try {
            if (StringUtils.isBlank(url)) {
                throw new WebServiceException("Could not determine URL for Admin Distribution Adapter endpoint");
            } else {
                RespondingGatewaySendAlertMessageSecuredType message = new RespondingGatewaySendAlertMessageSecuredType();
                message.setEDXLDistribution(body);
                ServicePortDescriptor<AdapterAdministrativeDistributionSecuredPortType> portDescriptor = new AdapterAdminDistributionSecuredServicePortDescriptor();
                CONNECTClient<AdapterAdministrativeDistributionSecuredPortType> client = getCONNECTClientSecured(portDescriptor, url, assertion);
                client.enableMtom();
                client.invokePort(AdapterAdministrativeDistributionSecuredPortType.class, "sendAlertMessage", message);
            }
        } catch (Exception ex) {
            throw new ErrorEventException(ex, "Unable to call Admin Distribution Adapter");
        }
    }

    /**
     * @return an instance of webServiceProxyHelper.
     */
    protected WebServiceProxyHelper getWebServiceProxyHelper() {
        return new WebServiceProxyHelper();
    }
}


public B fqdn(String fqdn) {
            this.fqdn = fqdn;
            return self();
        }

package org.jclouds.dynect.v3.domain;

import static com.google.common.base.Objects.equal;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import com.google.common.base.Objects;
import com.google.common.base.MoreObjects.ToStringHelper;

public class RecordId extends Node {

    private final long id;

    private final String type;

    @ConstructorProperties({ "zone", "fqdn", "record_type", "record_id" })
    RecordId(String zone, String fqdn, String type, long id) {
        super(zone, fqdn);
        this.id = id;
        this.type = checkNotNull(type, "type of %s", id);
    }

    /**
     * The RRType of the record
     */
    public String getType() {
        return type;
    }

    /**
     * The record id
     */
    public long getId() {
        return id;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(getZone(), getFQDN(), type, id);
    }

    /**
     * permits equals comparisons with subtypes
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null || !(obj instanceof RecordId))
            return false;
        RecordId that = RecordId.class.cast(obj);
        return super.equals(obj) && equal(this.type, that.type) && equal(this.id, that.id);
    }

    @Override
    public String toString() {
        return string().toString();
    }

    protected ToStringHelper string() {
        return toStringHelper(this).add("zone", getZone()).add("fqdn", getFQDN()).add("type", type).add("id", id);
    }

    public static Builder<?> recordIdBuilder() {
        return new ConcreteBuilder();
    }

    public Builder<?> toBuilder() {
        return new ConcreteBuilder().from(this);
    }

    public abstract static class Builder<B extends Builder<B>> {

        protected abstract B self();

        protected String zone;

        protected String fqdn;

        protected String type;

        protected long id;

        /**
         * @see Node#getZone()
         */
        public B zone(String zone) {
            this.zone = zone;
            return self();
        }

        /**
         * @see Node#getFQDN()
         */

        /**
         * @see RecordId#getType()
         */
        public B type(String type) {
            this.type = type;
            return self();
        }

        /**
         * @see RecordId#getId()
         */
        public B id(long id) {
            this.id = id;
            return self();
        }

        public RecordId build() {
            return new RecordId(zone, fqdn, type, id);
        }

        public B from(RecordId in) {
            return zone(in.getZone()).fqdn(in.getFQDN()).type(in.type).id(in.id);
        }
    }

    private static class ConcreteBuilder extends Builder<ConcreteBuilder> {

        protected ConcreteBuilder self() {
            return this;
        }
    }
}


for (int i = 0; i < charArray.length; i++) {
            int relativeIndex = charArray[i] - NUMBER_BASE;
            if (relativeIndex >= 0 && relativeIndex <= 9) {
                int newChar = SMALL_UP_NUMBER_BASE + relativeIndex;
                charArray[i] = (char) newChar;
            }
        }

package gregtech.api.util;

public class SmallDigits {

    private static final int SMALL_DOWN_NUMBER_BASE = '\u2080';

    private static final int SMALL_UP_NUMBER_BASE = '\u2080';

    private static final int NUMBER_BASE = '0';

    public static String toSmallUpNumbers(String string) {
        char[] charArray = string.toCharArray();

        return new String(charArray);
    }

    public static String toSmallDownNumbers(String string) {
        char[] charArray = string.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            int relativeIndex = charArray[i] - NUMBER_BASE;
            if (relativeIndex >= 0 && relativeIndex <= 9) {
                int newChar = SMALL_DOWN_NUMBER_BASE + relativeIndex;
                charArray[i] = (char) newChar;
            }
        }
        return new String(charArray);
    }
}


while (matcher.find()) {
            String searchTextWord = searchTextLower.substring(matcher.start());
            if (searchTextWord.startsWith(searchTermLower)) {
                int foundAt = searchTextWord.indexOf(searchTermLower);
                return new Range(searchFrom + matcher.start() + foundAt, searchFrom + matcher.start() + foundAt + term.length());
            }
        }

package com.defano.wyldcard.search.strategy;

import com.defano.hypertalk.util.Range;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Finds a substring that starts at the beginning of a word. Search term may contain whitespace, and search results may
 * cross word boundaries (but will always start at a word boundary).
 */
public class WholeSearchStrategy implements SearchStrategy {

    private static final Pattern words = Pattern.compile("\\w+");

    @Override
    public Range search(String text, String term, int searchFrom) {
        String searchTextLower = text.substring(searchFrom).toLowerCase();
        String searchTermLower = term.toLowerCase();
        Matcher matcher = words.matcher(searchTextLower);


public void setAttributesMapper(AttributesMapper attributesMapper) {
        this.attributesMapper = attributesMapper;
    }

package org.geoserver.geofence.ldap.dao.impl;

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import javax.naming.NamingException;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.geoserver.geofence.core.dao.RestrictedGenericDAO;
import org.geoserver.geofence.core.model.GSUser;
import org.geoserver.geofence.core.model.UserGroup;
import org.geoserver.geofence.ldap.utils.LdapUtils;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.AbstractContextMapper;
import com.googlecode.genericdao.search.Filter;
import com.googlecode.genericdao.search.ISearch;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;

/**
 * Base DAO Implementation using LDAP services.
 *
 * It uses a spring-ldap LdapTemplate to communicate with the LDAP server.
 *
 * Currently only read type operations are supported (findAll, find, search).
 *
 * Search results are cached in order to avoid too many calls to the LDAP services.
 *
 * @author "Mauro Bartolomeoli - example@nnthink.com"
 * @author Emanuele Tajariol (etj at geo-solutions.it)
 */
public abstract class LDAPBaseDAO<T extends RestrictedGenericDAO<R>, R> implements RestrictedGenericDAO<R>, InitializingBean {

    private static final class LDAPContextMapper extends AbstractContextMapper {

        AttributesMapper mapper;

        public LDAPContextMapper(AttributesMapper mapper) {
            super();
            this.mapper = mapper;
        }

        @Override
        protected Object doMapFromContext(DirContextOperations ctx) {
            try {
                Object result = mapper.mapFromAttributes(ctx.getAttributes());
                if (result instanceof GSUser) {
                    ((GSUser) result).setExtId(ctx.getNameInNamespace());
                }
                if (result instanceof UserGroup) {
                    ((UserGroup) result).setExtId(ctx.getNameInNamespace());
                }
                return result;
            } catch (NamingException e) {
                throw new RuntimeException(e);
            }
        }
    }

    protected Logger LOGGER = LogManager.getLogger(getClass());

    private LdapTemplate ldapTemplate;

    private String searchBase;

    private String searchFilter;

    private AttributesMapper attributesMapper;

    private LoadingCache<String, List<R>> ldapcache;

    private long cachesize = 1000;

    private long cacherefreshsec = 60 * 60;

    private long cacheexpiresec = 60 * 60;

    private final AtomicLong dumpCnt = new AtomicLong(0);

    private long cachedumpmodulo = 10;

    public LDAPBaseDAO() {
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        ldapcache = getCacheBuilder().build(new LDAPLoader());
    }

    protected CacheBuilder getCacheBuilder() {
        CacheBuilder builder = CacheBuilder.newBuilder().maximumSize(cachesize).refreshAfterWrite(cacherefreshsec, // reloadable after x time
        TimeUnit.SECONDS).expireAfterWrite(cacheexpiresec, // throw away entries too old
        TimeUnit.SECONDS).recordStats();
        return builder;
    }

    protected String getLDAPAttribute(String attrName) {
        return ((BaseAttributesMapper) attributesMapper).getLdapAttribute(attrName);
    }

    @Override
    public List<R> findAll() {
        List ret = search(searchFilter);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("findAll returned " + ret.size() + " items");
        }
        return ret;
    }

    @Override
    public R find(Long id) {
        LOGGER.warn(getClass().getSimpleName() + ": search by id is deprecated (id=" + id + ")");
        return null;
    }

    @Override
    public List<R> search(ISearch search) {
        List<R> objects = new ArrayList<>();
        if (search.getFilters().isEmpty()) {
            // no filter
            return paginate(findAll(), search);
        }
        for (Filter filter : search.getFilters()) {
            if (filter != null) {
                List<R> filteredObjects = paginate(search(filter), search);
                objects.addAll(filteredObjects);
            }
        }
        return objects;
    }

    protected List<R> paginate(List<R> list, ISearch search) {
        if (search.getMaxResults() > 0 && search.getPage() >= 0) {
            List<R> result = new ArrayList<R>();
            int start = search.getPage() * search.getMaxResults();
            for (int index = start; index < start + search.getMaxResults() && index < list.size(); index++) {
                result.add(list.get(index));
            }
            return result;
        }
        return list;
    }

    @Override
    public int count(ISearch search) {
        return search(search).size();
    }

    @Override
    public void persist(R... entities) {
        LOGGER.warn(getClass().getSimpleName() + ": persisting not allowed in LDAP");
    }

    @Override
    public R merge(R entity) {
        LOGGER.warn(getClass().getSimpleName() + ": persisting not allowed in LDAP");
        return entity;
    }

    @Override
    public boolean remove(R entity) {
        LOGGER.warn(getClass().getSimpleName() + ": persisting not allowed in LDAP");
        return false;
    }

    @Override
    public boolean removeById(Long id) {
        LOGGER.warn(getClass().getSimpleName() + ": persisting not allowed in LDAP");
        return false;
    }

    /**
     * Does a direct lookup for the distinguished name given.
     *
     * @param dn distinguished name to lookup
     * @return
     */
    public R lookup(String dn) {
        return (R) ldapTemplate.lookup(dn, attributesMapper);
    }

    /**
     * Search using the given filter on the LDAP server. Uses default base, filter and mapper.
     *
     * @param base
     * @param filter
     * @param mapper
     * @return
     */
    public List search(Filter filter) {
        return search(LdapUtils.createLDAPFilter(filter, attributesMapper));
    }

    /**
     * Search using the given filter on the LDAP server. Uses default base, filter and mapper.
     *
     * @param base
     * @param filter
     * @param mapper
     * @return
     */
    public List search(String filter) {
        if (LOGGER.isTraceEnabled())
            LOGGER.trace(getClass().getSimpleName() + ": searching base:'" + searchBase + "', filter: '" + filter + "'");
        if (LOGGER.isInfoEnabled()) {
            if (dumpCnt.incrementAndGet() % cachedumpmodulo == 0) {
                LOGGER.info("LDAP Cache  :" + ldapcache.stats());
            }
        }
        try {
            return ldapcache.get(filter);
        } catch (ExecutionException ex) {
            LOGGER.warn("Error while getting LDAP info: " + ex.getMessage(), ex);
            return Collections.EMPTY_LIST;
        }
    }

    private class LDAPLoader extends CacheLoader<String, List<R>> {

        @Override
        public List<R> load(String filter) throws Exception {
            if (LOGGER.isInfoEnabled())
                LOGGER.info("Loading " + filter);
            return ldapTemplate.search(searchBase, filter, new LDAPContextMapper(attributesMapper));
        }

        @Override
        public ListenableFuture<List<R>> reload(final String filter, List<R> accessInfo) throws Exception {
            if (LOGGER.isInfoEnabled())
                LOGGER.info("RELoading " + filter);
            // this is a sync implementation
            List<R> ldapObjs = ldapTemplate.search(searchBase, filter, new LDAPContextMapper(attributesMapper));
            return Futures.immediateFuture(ldapObjs);
        }
    }

    /**
     * Sets the base name for users in LDAP server.
     *
     * @param searchBase the searchBase to set
     */
    public void setSearchBase(String searchBase) {
        this.searchBase = searchBase;
    }

    /**
     * Sets the filter used to identify objects from the base name.
     *
     * @param searchFilter the searchFilter to set
     */
    public void setSearchFilter(String searchFilter) {
        this.searchFilter = searchFilter;
    }

    /**
     * Sets the AttributeMapper used to build objects from LDAP objects.
     *
     * @param attributesMapper the attributesMapper to set
     */

    /**
     * Sets the LDAP communication object.
     *
     * @param ldapTemplate the ldapTemplate to set
     */
    public void setLdapTemplate(LdapTemplate ldapTemplate) {
        this.ldapTemplate = ldapTemplate;
    }

    public void setCachesize(long cachesize) {
        this.cachesize = cachesize;
    }

    public void setCacherefreshsec(long cacherefreshsec) {
        this.cacherefreshsec = cacherefreshsec;
    }

    public void setCacheexpiresec(long cacheexpiresec) {
        this.cacheexpiresec = cacheexpiresec;
    }

    public void setCachedumpmodulo(long cachedumpmodulo) {
        this.cachedumpmodulo = cachedumpmodulo;
    }
}


for (int index = start; index < start + search.getMaxResults() && index < list.size(); index++) {
                result.add(list.get(index));
            }

package org.geoserver.geofence.ldap.dao.impl;

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import javax.naming.NamingException;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.geoserver.geofence.core.dao.RestrictedGenericDAO;
import org.geoserver.geofence.core.model.GSUser;
import org.geoserver.geofence.core.model.UserGroup;
import org.geoserver.geofence.ldap.utils.LdapUtils;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.AbstractContextMapper;
import com.googlecode.genericdao.search.Filter;
import com.googlecode.genericdao.search.ISearch;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;

/**
 * Base DAO Implementation using LDAP services.
 *
 * It uses a spring-ldap LdapTemplate to communicate with the LDAP server.
 *
 * Currently only read type operations are supported (findAll, find, search).
 *
 * Search results are cached in order to avoid too many calls to the LDAP services.
 *
 * @author "Mauro Bartolomeoli - example@nnthink.com"
 * @author Emanuele Tajariol (etj at geo-solutions.it)
 */
public abstract class LDAPBaseDAO<T extends RestrictedGenericDAO<R>, R> implements RestrictedGenericDAO<R>, InitializingBean {

    private static final class LDAPContextMapper extends AbstractContextMapper {

        AttributesMapper mapper;

        public LDAPContextMapper(AttributesMapper mapper) {
            super();
            this.mapper = mapper;
        }

        @Override
        protected Object doMapFromContext(DirContextOperations ctx) {
            try {
                Object result = mapper.mapFromAttributes(ctx.getAttributes());
                if (result instanceof GSUser) {
                    ((GSUser) result).setExtId(ctx.getNameInNamespace());
                }
                if (result instanceof UserGroup) {
                    ((UserGroup) result).setExtId(ctx.getNameInNamespace());
                }
                return result;
            } catch (NamingException e) {
                throw new RuntimeException(e);
            }
        }
    }

    protected Logger LOGGER = LogManager.getLogger(getClass());

    private LdapTemplate ldapTemplate;

    private String searchBase;

    private String searchFilter;

    private AttributesMapper attributesMapper;

    private LoadingCache<String, List<R>> ldapcache;

    private long cachesize = 1000;

    private long cacherefreshsec = 60 * 60;

    private long cacheexpiresec = 60 * 60;

    private final AtomicLong dumpCnt = new AtomicLong(0);

    private long cachedumpmodulo = 10;

    public LDAPBaseDAO() {
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        ldapcache = getCacheBuilder().build(new LDAPLoader());
    }

    protected CacheBuilder getCacheBuilder() {
        CacheBuilder builder = CacheBuilder.newBuilder().maximumSize(cachesize).refreshAfterWrite(cacherefreshsec, // reloadable after x time
        TimeUnit.SECONDS).expireAfterWrite(cacheexpiresec, // throw away entries too old
        TimeUnit.SECONDS).recordStats();
        return builder;
    }

    protected String getLDAPAttribute(String attrName) {
        return ((BaseAttributesMapper) attributesMapper).getLdapAttribute(attrName);
    }

    @Override
    public List<R> findAll() {
        List ret = search(searchFilter);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("findAll returned " + ret.size() + " items");
        }
        return ret;
    }

    @Override
    public R find(Long id) {
        LOGGER.warn(getClass().getSimpleName() + ": search by id is deprecated (id=" + id + ")");
        return null;
    }

    @Override
    public List<R> search(ISearch search) {
        List<R> objects = new ArrayList<>();
        if (search.getFilters().isEmpty()) {
            // no filter
            return paginate(findAll(), search);
        }
        for (Filter filter : search.getFilters()) {
            if (filter != null) {
                List<R> filteredObjects = paginate(search(filter), search);
                objects.addAll(filteredObjects);
            }
        }
        return objects;
    }

    protected List<R> paginate(List<R> list, ISearch search) {
        if (search.getMaxResults() > 0 && search.getPage() >= 0) {
            List<R> result = new ArrayList<R>();
            int start = search.getPage() * search.getMaxResults();

            return result;
        }
        return list;
    }

    @Override
    public int count(ISearch search) {
        return search(search).size();
    }

    @Override
    public void persist(R... entities) {
        LOGGER.warn(getClass().getSimpleName() + ": persisting not allowed in LDAP");
    }

    @Override
    public R merge(R entity) {
        LOGGER.warn(getClass().getSimpleName() + ": persisting not allowed in LDAP");
        return entity;
    }

    @Override
    public boolean remove(R entity) {
        LOGGER.warn(getClass().getSimpleName() + ": persisting not allowed in LDAP");
        return false;
    }

    @Override
    public boolean removeById(Long id) {
        LOGGER.warn(getClass().getSimpleName() + ": persisting not allowed in LDAP");
        return false;
    }

    /**
     * Does a direct lookup for the distinguished name given.
     *
     * @param dn distinguished name to lookup
     * @return
     */
    public R lookup(String dn) {
        return (R) ldapTemplate.lookup(dn, attributesMapper);
    }

    /**
     * Search using the given filter on the LDAP server. Uses default base, filter and mapper.
     *
     * @param base
     * @param filter
     * @param mapper
     * @return
     */
    public List search(Filter filter) {
        return search(LdapUtils.createLDAPFilter(filter, attributesMapper));
    }

    /**
     * Search using the given filter on the LDAP server. Uses default base, filter and mapper.
     *
     * @param base
     * @param filter
     * @param mapper
     * @return
     */
    public List search(String filter) {
        if (LOGGER.isTraceEnabled())
            LOGGER.trace(getClass().getSimpleName() + ": searching base:'" + searchBase + "', filter: '" + filter + "'");
        if (LOGGER.isInfoEnabled()) {
            if (dumpCnt.incrementAndGet() % cachedumpmodulo == 0) {
                LOGGER.info("LDAP Cache  :" + ldapcache.stats());
            }
        }
        try {
            return ldapcache.get(filter);
        } catch (ExecutionException ex) {
            LOGGER.warn("Error while getting LDAP info: " + ex.getMessage(), ex);
            return Collections.EMPTY_LIST;
        }
    }

    private class LDAPLoader extends CacheLoader<String, List<R>> {

        @Override
        public List<R> load(String filter) throws Exception {
            if (LOGGER.isInfoEnabled())
                LOGGER.info("Loading " + filter);
            return ldapTemplate.search(searchBase, filter, new LDAPContextMapper(attributesMapper));
        }

        @Override
        public ListenableFuture<List<R>> reload(final String filter, List<R> accessInfo) throws Exception {
            if (LOGGER.isInfoEnabled())
                LOGGER.info("RELoading " + filter);
            // this is a sync implementation
            List<R> ldapObjs = ldapTemplate.search(searchBase, filter, new LDAPContextMapper(attributesMapper));
            return Futures.immediateFuture(ldapObjs);
        }
    }

    /**
     * Sets the base name for users in LDAP server.
     *
     * @param searchBase the searchBase to set
     */
    public void setSearchBase(String searchBase) {
        this.searchBase = searchBase;
    }

    /**
     * Sets the filter used to identify objects from the base name.
     *
     * @param searchFilter the searchFilter to set
     */
    public void setSearchFilter(String searchFilter) {
        this.searchFilter = searchFilter;
    }

    /**
     * Sets the AttributeMapper used to build objects from LDAP objects.
     *
     * @param attributesMapper the attributesMapper to set
     */
    public void setAttributesMapper(AttributesMapper attributesMapper) {
        this.attributesMapper = attributesMapper;
    }

    /**
     * Sets the LDAP communication object.
     *
     * @param ldapTemplate the ldapTemplate to set
     */
    public void setLdapTemplate(LdapTemplate ldapTemplate) {
        this.ldapTemplate = ldapTemplate;
    }

    public void setCachesize(long cachesize) {
        this.cachesize = cachesize;
    }

    public void setCacherefreshsec(long cacherefreshsec) {
        this.cacherefreshsec = cacherefreshsec;
    }

    public void setCacheexpiresec(long cacheexpiresec) {
        this.cacheexpiresec = cacheexpiresec;
    }

    public void setCachedumpmodulo(long cachedumpmodulo) {
        this.cachedumpmodulo = cachedumpmodulo;
    }
}


try {
            return ldapcache.get(filter);
        } catch (ExecutionException ex) {
            LOGGER.warn("Error while getting LDAP info: " + ex.getMessage(), ex);
            return Collections.EMPTY_LIST;
        }

package org.geoserver.geofence.ldap.dao.impl;

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import javax.naming.NamingException;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.geoserver.geofence.core.dao.RestrictedGenericDAO;
import org.geoserver.geofence.core.model.GSUser;
import org.geoserver.geofence.core.model.UserGroup;
import org.geoserver.geofence.ldap.utils.LdapUtils;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.AbstractContextMapper;
import com.googlecode.genericdao.search.Filter;
import com.googlecode.genericdao.search.ISearch;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;

/**
 * Base DAO Implementation using LDAP services.
 *
 * It uses a spring-ldap LdapTemplate to communicate with the LDAP server.
 *
 * Currently only read type operations are supported (findAll, find, search).
 *
 * Search results are cached in order to avoid too many calls to the LDAP services.
 *
 * @author "Mauro Bartolomeoli - example@nnthink.com"
 * @author Emanuele Tajariol (etj at geo-solutions.it)
 */
public abstract class LDAPBaseDAO<T extends RestrictedGenericDAO<R>, R> implements RestrictedGenericDAO<R>, InitializingBean {

    private static final class LDAPContextMapper extends AbstractContextMapper {

        AttributesMapper mapper;

        public LDAPContextMapper(AttributesMapper mapper) {
            super();
            this.mapper = mapper;
        }

        @Override
        protected Object doMapFromContext(DirContextOperations ctx) {
            try {
                Object result = mapper.mapFromAttributes(ctx.getAttributes());
                if (result instanceof GSUser) {
                    ((GSUser) result).setExtId(ctx.getNameInNamespace());
                }
                if (result instanceof UserGroup) {
                    ((UserGroup) result).setExtId(ctx.getNameInNamespace());
                }
                return result;
            } catch (NamingException e) {
                throw new RuntimeException(e);
            }
        }
    }

    protected Logger LOGGER = LogManager.getLogger(getClass());

    private LdapTemplate ldapTemplate;

    private String searchBase;

    private String searchFilter;

    private AttributesMapper attributesMapper;

    private LoadingCache<String, List<R>> ldapcache;

    private long cachesize = 1000;

    private long cacherefreshsec = 60 * 60;

    private long cacheexpiresec = 60 * 60;

    private final AtomicLong dumpCnt = new AtomicLong(0);

    private long cachedumpmodulo = 10;

    public LDAPBaseDAO() {
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        ldapcache = getCacheBuilder().build(new LDAPLoader());
    }

    protected CacheBuilder getCacheBuilder() {
        CacheBuilder builder = CacheBuilder.newBuilder().maximumSize(cachesize).refreshAfterWrite(cacherefreshsec, // reloadable after x time
        TimeUnit.SECONDS).expireAfterWrite(cacheexpiresec, // throw away entries too old
        TimeUnit.SECONDS).recordStats();
        return builder;
    }

    protected String getLDAPAttribute(String attrName) {
        return ((BaseAttributesMapper) attributesMapper).getLdapAttribute(attrName);
    }

    @Override
    public List<R> findAll() {
        List ret = search(searchFilter);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("findAll returned " + ret.size() + " items");
        }
        return ret;
    }

    @Override
    public R find(Long id) {
        LOGGER.warn(getClass().getSimpleName() + ": search by id is deprecated (id=" + id + ")");
        return null;
    }

    @Override
    public List<R> search(ISearch search) {
        List<R> objects = new ArrayList<>();
        if (search.getFilters().isEmpty()) {
            // no filter
            return paginate(findAll(), search);
        }
        for (Filter filter : search.getFilters()) {
            if (filter != null) {
                List<R> filteredObjects = paginate(search(filter), search);
                objects.addAll(filteredObjects);
            }
        }
        return objects;
    }

    protected List<R> paginate(List<R> list, ISearch search) {
        if (search.getMaxResults() > 0 && search.getPage() >= 0) {
            List<R> result = new ArrayList<R>();
            int start = search.getPage() * search.getMaxResults();
            for (int index = start; index < start + search.getMaxResults() && index < list.size(); index++) {
                result.add(list.get(index));
            }
            return result;
        }
        return list;
    }

    @Override
    public int count(ISearch search) {
        return search(search).size();
    }

    @Override
    public void persist(R... entities) {
        LOGGER.warn(getClass().getSimpleName() + ": persisting not allowed in LDAP");
    }

    @Override
    public R merge(R entity) {
        LOGGER.warn(getClass().getSimpleName() + ": persisting not allowed in LDAP");
        return entity;
    }

    @Override
    public boolean remove(R entity) {
        LOGGER.warn(getClass().getSimpleName() + ": persisting not allowed in LDAP");
        return false;
    }

    @Override
    public boolean removeById(Long id) {
        LOGGER.warn(getClass().getSimpleName() + ": persisting not allowed in LDAP");
        return false;
    }

    /**
     * Does a direct lookup for the distinguished name given.
     *
     * @param dn distinguished name to lookup
     * @return
     */
    public R lookup(String dn) {
        return (R) ldapTemplate.lookup(dn, attributesMapper);
    }

    /**
     * Search using the given filter on the LDAP server. Uses default base, filter and mapper.
     *
     * @param base
     * @param filter
     * @param mapper
     * @return
     */
    public List search(Filter filter) {
        return search(LdapUtils.createLDAPFilter(filter, attributesMapper));
    }

    /**
     * Search using the given filter on the LDAP server. Uses default base, filter and mapper.
     *
     * @param base
     * @param filter
     * @param mapper
     * @return
     */
    public List search(String filter) {
        if (LOGGER.isTraceEnabled())
            LOGGER.trace(getClass().getSimpleName() + ": searching base:'" + searchBase + "', filter: '" + filter + "'");
        if (LOGGER.isInfoEnabled()) {
            if (dumpCnt.incrementAndGet() % cachedumpmodulo == 0) {
                LOGGER.info("LDAP Cache  :" + ldapcache.stats());
            }
        }

    }

    private class LDAPLoader extends CacheLoader<String, List<R>> {

        @Override
        public List<R> load(String filter) throws Exception {
            if (LOGGER.isInfoEnabled())
                LOGGER.info("Loading " + filter);
            return ldapTemplate.search(searchBase, filter, new LDAPContextMapper(attributesMapper));
        }

        @Override
        public ListenableFuture<List<R>> reload(final String filter, List<R> accessInfo) throws Exception {
            if (LOGGER.isInfoEnabled())
                LOGGER.info("RELoading " + filter);
            // this is a sync implementation
            List<R> ldapObjs = ldapTemplate.search(searchBase, filter, new LDAPContextMapper(attributesMapper));
            return Futures.immediateFuture(ldapObjs);
        }
    }

    /**
     * Sets the base name for users in LDAP server.
     *
     * @param searchBase the searchBase to set
     */
    public void setSearchBase(String searchBase) {
        this.searchBase = searchBase;
    }

    /**
     * Sets the filter used to identify objects from the base name.
     *
     * @param searchFilter the searchFilter to set
     */
    public void setSearchFilter(String searchFilter) {
        this.searchFilter = searchFilter;
    }

    /**
     * Sets the AttributeMapper used to build objects from LDAP objects.
     *
     * @param attributesMapper the attributesMapper to set
     */
    public void setAttributesMapper(AttributesMapper attributesMapper) {
        this.attributesMapper = attributesMapper;
    }

    /**
     * Sets the LDAP communication object.
     *
     * @param ldapTemplate the ldapTemplate to set
     */
    public void setLdapTemplate(LdapTemplate ldapTemplate) {
        this.ldapTemplate = ldapTemplate;
    }

    public void setCachesize(long cachesize) {
        this.cachesize = cachesize;
    }

    public void setCacherefreshsec(long cacherefreshsec) {
        this.cacherefreshsec = cacherefreshsec;
    }

    public void setCacheexpiresec(long cacheexpiresec) {
        this.cacheexpiresec = cacheexpiresec;
    }

    public void setCachedumpmodulo(long cachedumpmodulo) {
        this.cachedumpmodulo = cachedumpmodulo;
    }
}