try {
            Log.d(TAG, activity.getPackageName());
            packageInfo = activity.getPackageManager().getPackageInfo(activity.getPackageName(), PackageManager.GET_PERMISSIONS);
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "A problem occurred when retrieving permissions", e);
        }

package com.wsg.xsytrade.runtimepermissions;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.util.Log;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * A class to help you manage your permissions simply.
 */
public class PermissionsManager {

    private static final String TAG = PermissionsManager.class.getSimpleName();

    private final Set<String> mPendingRequests = new HashSet<String>(1);

    private final Set<String> mPermissions = new HashSet<String>(1);

    private final List<WeakReference<PermissionsResultAction>> mPendingActions = new ArrayList<WeakReference<PermissionsResultAction>>(1);

    private static PermissionsManager mInstance = null;

    public static PermissionsManager getInstance() {
        if (mInstance == null) {
            mInstance = new PermissionsManager();
        }
        return mInstance;
    }

    private PermissionsManager() {
        initializePermissionsMap();
    }

    /**
     * This method uses reflection to read all the permissions in the Manifest class.
     * This is necessary because some permissions do not exist on older versions of Android,
     * since they do not exist, they will be denied when you check whether you have permission
     * which is problematic since a new permission is often added where there was no previous
     * permission required. We initialize a Set of available permissions and check the set
     * when checking if we have permission since we want to know when we are denied a permission
     * because it doesn't exist yet.
     */
    private synchronized void initializePermissionsMap() {
        Field[] fields = Manifest.permission.class.getFields();
        for (Field field : fields) {
            String name = null;
            try {
                name = (String) field.get("");
            } catch (IllegalAccessException e) {
                Log.e(TAG, "Could not access field", e);
            }
            mPermissions.add(name);
        }
    }

    /**
     * This method retrieves all the permissions declared in the application's manifest.
     * It returns a non null array of permisions that can be declared.
     *
     * @param activity the Activity necessary to check what permissions we have.
     * @return a non null array of permissions that are declared in the application manifest.
     */
    @NonNull
    private synchronized String[] getManifestPermissions(@NonNull final Activity activity) {
        PackageInfo packageInfo = null;
        List<String> list = new ArrayList<String>(1);

        if (packageInfo != null) {
            String[] permissions = packageInfo.requestedPermissions;
            if (permissions != null) {
                for (String perm : permissions) {
                    Log.d(TAG, "Manifest contained permission: " + perm);
                    list.add(perm);
                }
            }
        }
        return list.toArray(new String[list.size()]);
    }

    /**
     * This method adds the {@link PermissionsResultAction} to the current list
     * of pending actions that will be completed when the permissions are
     * received. The list of permissions passed to this method are registered
     * in the PermissionsResultAction object so that it will be notified of changes
     * made to these permissions.
     *
     * @param permissions the required permissions for the action to be executed.
     * @param action      the action to add to the current list of pending actions.
     */
    private synchronized void addPendingAction(@NonNull String[] permissions, @Nullable PermissionsResultAction action) {
        if (action == null) {
            return;
        }
        action.registerPermissions(permissions);
        mPendingActions.add(new WeakReference<PermissionsResultAction>(action));
    }

    /**
     * This method removes a pending action from the list of pending actions.
     * It is used for cases where the permission has already been granted, so
     * you immediately wish to remove the pending action from the queue and
     * execute the action.
     *
     * @param action the action to remove
     */
    private synchronized void removePendingAction(@Nullable PermissionsResultAction action) {
        for (Iterator<WeakReference<PermissionsResultAction>> iterator = mPendingActions.iterator(); iterator.hasNext(); ) {
            WeakReference<PermissionsResultAction> weakRef = iterator.next();
            if (weakRef.get() == action || weakRef.get() == null) {
                iterator.remove();
            }
        }
    }

    /**
     * This static method can be used to check whether or not you have a specific permission.
     * It is basically a less verbose method of using {@link ActivityCompat#checkSelfPermission(Context, String)}
     * and will simply return a boolean whether or not you have the permission. If you pass
     * in a null Context object, it will return false as otherwise it cannot check the permission.
     * However, the Activity parameter is nullable so that you can pass in a reference that you
     * are not always sure will be valid or not (e.g. getActivity() from Fragment).
     *
     * @param context    the Context necessary to check the permission
     * @param permission the permission to check
     * @return true if you have been granted the permission, false otherwise
     */
    @SuppressWarnings("unused")
    public synchronized boolean hasPermission(@Nullable Context context, @NonNull String permission) {
        return context != null && (ActivityCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED || !mPermissions.contains(permission));
    }

    /**
     * This static method can be used to check whether or not you have several specific permissions.
     * It is simpler than checking using {@link ActivityCompat#checkSelfPermission(Context, String)}
     * for each permission and will simply return a boolean whether or not you have all the permissions.
     * If you pass in a null Context object, it will return false as otherwise it cannot check the
     * permission. However, the Activity parameter is nullable so that you can pass in a reference
     * that you are not always sure will be valid or not (e.g. getActivity() from Fragment).
     *
     * @param context     the Context necessary to check the permission
     * @param permissions the permissions to check
     * @return true if you have been granted all the permissions, false otherwise
     */
    @SuppressWarnings("unused")
    public synchronized boolean hasAllPermissions(@Nullable Context context, @NonNull String[] permissions) {
        if (context == null) {
            return false;
        }
        boolean hasAllPermissions = true;
        for (String perm : permissions) {
            hasAllPermissions &= hasPermission(context, perm);
        }
        return hasAllPermissions;
    }

    /**
     * This method will request all the permissions declared in your application manifest
     * for the specified {@link PermissionsResultAction}. The purpose of this method is to enable
     * all permissions to be requested at one shot. The PermissionsResultAction is used to notify
     * you of the user allowing or denying each permission. The Activity and PermissionsResultAction
     * parameters are both annotated Nullable, but this method will not work if the Activity
     * is null. It is only annotated Nullable as a courtesy to prevent crashes in the case
     * that you call this from a Fragment where {@link Fragment#getActivity()} could yield
     * null. Additionally, you will not receive any notification of permissions being granted
     * if you provide a null PermissionsResultAction.
     *
     * @param activity the Activity necessary to request and check permissions.
     * @param action   the PermissionsResultAction used to notify you of permissions being accepted.
     */
    @SuppressWarnings("unused")
    public synchronized void requestAllManifestPermissionsIfNecessary(@Nullable final Activity activity, @Nullable final PermissionsResultAction action) {
        if (activity == null) {
            return;
        }
        String[] perms = getManifestPermissions(activity);
        requestPermissionsIfNecessaryForResult(activity, perms, action);
    }

    /**
     * This method should be used to execute a {@link PermissionsResultAction} for the array
     * of permissions passed to this method. This method will request the permissions if
     * they need to be requested (i.e. we don't have permission yet) and will add the
     * PermissionsResultAction to the queue to be notified of permissions being granted or
     * denied. In the case of pre-Android Marshmallow, permissions will be granted immediately.
     * The Activity variable is nullable, but if it is null, the method will fail to execute.
     * This is only nullable as a courtesy for Fragments where getActivity() may yeild null
     * if the Fragment is not currently added to its parent Activity.
     *
     * @param activity    the activity necessary to request the permissions.
     * @param permissions the list of permissions to request for the {@link PermissionsResultAction}.
     * @param action      the PermissionsResultAction to notify when the permissions are granted or denied.
     */
    @SuppressWarnings("unused")
    public synchronized void requestPermissionsIfNecessaryForResult(@Nullable Activity activity, @NonNull String[] permissions, @Nullable PermissionsResultAction action) {
        if (activity == null) {
            return;
        }
        addPendingAction(permissions, action);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            doPermissionWorkBeforeAndroidM(activity, permissions, action);
        } else {
            List<String> permList = getPermissionsListToRequest(activity, permissions, action);
            if (permList.isEmpty()) {
                // if there is no permission to request, there is no reason to keep the action int the list
                removePendingAction(action);
            } else {
                String[] permsToRequest = permList.toArray(new String[permList.size()]);
                mPendingRequests.addAll(permList);
                ActivityCompat.requestPermissions(activity, permsToRequest, 1);
            }
        }
    }

    /**
     * This method should be used to execute a {@link PermissionsResultAction} for the array
     * of permissions passed to this method. This method will request the permissions if
     * they need to be requested (i.e. we don't have permission yet) and will add the
     * PermissionsResultAction to the queue to be notified of permissions being granted or
     * denied. In the case of pre-Android Marshmallow, permissions will be granted immediately.
     * The Fragment variable is used, but if {@link Fragment#getActivity()} returns null, this method
     * will fail to work as the activity reference is necessary to check for permissions.
     *
     * @param fragment    the fragment necessary to request the permissions.
     * @param permissions the list of permissions to request for the {@link PermissionsResultAction}.
     * @param action      the PermissionsResultAction to notify when the permissions are granted or denied.
     */
    @SuppressWarnings("unused")
    public synchronized void requestPermissionsIfNecessaryForResult(@NonNull Fragment fragment, @NonNull String[] permissions, @Nullable PermissionsResultAction action) {
        Activity activity = fragment.getActivity();
        if (activity == null) {
            return;
        }
        addPendingAction(permissions, action);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            doPermissionWorkBeforeAndroidM(activity, permissions, action);
        } else {
            List<String> permList = getPermissionsListToRequest(activity, permissions, action);
            if (permList.isEmpty()) {
                // if there is no permission to request, there is no reason to keep the action int the list
                removePendingAction(action);
            } else {
                String[] permsToRequest = permList.toArray(new String[permList.size()]);
                mPendingRequests.addAll(permList);
                fragment.requestPermissions(permsToRequest, 1);
            }
        }
    }

    /**
     * This method notifies the PermissionsManager that the permissions have change. If you are making
     * the permissions requests using an Activity, then this method should be called from the
     * Activity callback onRequestPermissionsResult() with the variables passed to that method. If
     * you are passing a Fragment to make the permissions request, then you should call this in
     * the {@link Fragment#onRequestPermissionsResult(int, String[], int[])} method.
     * It will notify all the pending PermissionsResultAction objects currently
     * in the queue, and will remove the permissions request from the list of pending requests.
     *
     * @param permissions the permissions that have changed.
     * @param results     the values for each permission.
     */
    @SuppressWarnings("unused")
    public synchronized void notifyPermissionsChange(@NonNull String[] permissions, @NonNull int[] results) {
        int size = permissions.length;
        if (results.length < size) {
            size = results.length;
        }
        Iterator<WeakReference<PermissionsResultAction>> iterator = mPendingActions.iterator();
        while (iterator.hasNext()) {
            PermissionsResultAction action = iterator.next().get();
            for (int n = 0; n < size; n++) {
                if (action == null || action.onResult(permissions[n], results[n])) {
                    iterator.remove();
                    break;
                }
            }
        }
        for (int n = 0; n < size; n++) {
            mPendingRequests.remove(permissions[n]);
        }
    }

    /**
     * When request permissions on devices before Android M (Android 6.0, API Level 23)
     * Do the granted or denied work directly according to the permission status
     *
     * @param activity    the activity to check permissions
     * @param permissions the permissions names
     * @param action      the callback work object, containing what we what to do after
     *                    permission check
     */
    private void doPermissionWorkBeforeAndroidM(@NonNull Activity activity, @NonNull String[] permissions, @Nullable PermissionsResultAction action) {
        for (String perm : permissions) {
            if (action != null) {
                if (!mPermissions.contains(perm)) {
                    action.onResult(perm, Permissions.NOT_FOUND);
                } else if (ActivityCompat.checkSelfPermission(activity, perm) != PackageManager.PERMISSION_GRANTED) {
                    action.onResult(perm, Permissions.DENIED);
                } else {
                    action.onResult(perm, Permissions.GRANTED);
                }
            }
        }
    }

    /**
     * Filter the permissions list:
     * If a permission is not granted, add it to the result list
     * if a permission is granted, do the granted work, do not add it to the result list
     *
     * @param activity    the activity to check permissions
     * @param permissions all the permissions names
     * @param action      the callback work object, containing what we what to do after
     *                    permission check
     * @return a list of permissions names that are not granted yet
     */
    @NonNull
    private List<String> getPermissionsListToRequest(@NonNull Activity activity, @NonNull String[] permissions, @Nullable PermissionsResultAction action) {
        List<String> permList = new ArrayList<String>(permissions.length);
        for (String perm : permissions) {
            if (!mPermissions.contains(perm)) {
                if (action != null) {
                    action.onResult(perm, Permissions.NOT_FOUND);
                }
            } else if (ActivityCompat.checkSelfPermission(activity, perm) != PackageManager.PERMISSION_GRANTED) {
                if (!mPendingRequests.contains(perm)) {
                    permList.add(perm);
                }
            } else {
                if (action != null) {
                    action.onResult(perm, Permissions.GRANTED);
                }
            }
        }
        return permList;
    }
}


public List<String> getSelected() {
        return selected;
    }

package com.jaxio.jpa.querybyexample;

import javax.persistence.metamodel.SingularAttribute;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
import static org.apache.commons.lang.StringUtils.isNotBlank;

public class TermSelector implements Serializable {

    private static final long serialVersionUID = 1L;

    private final PathHolder pathHolder;

    private List<String> selected = newArrayList();

    private boolean orMode = true;

    public TermSelector() {
        this.pathHolder = null;
    }

    public TermSelector(SingularAttribute<?, ?> attribute) {
        this.pathHolder = new PathHolder(attribute);
    }

    public SingularAttribute<?, ?> getAttribute() {
        return pathHolder != null ? (SingularAttribute<?, ?>) pathHolder.getAttributes().get(0) : null;
    }

    public boolean isOrMode() {
        return orMode;
    }

    public void setOrMode(boolean orMode) {
        this.orMode = orMode;
    }

    public TermSelector or() {
        setOrMode(true);
        return this;
    }

    public TermSelector and() {
        setOrMode(false);
        return this;
    }

    /*
     * Get the possible candidates for property.
     */

    public void setSelected(String selected) {
        this.selected = newArrayList(selected);
    }

    /*
     * Set the possible candidates for property.
     */
    public void setSelected(List<String> selected) {
        this.selected = selected;
    }

    public TermSelector selected(String... selected) {
        setSelected(newArrayList(selected));
        return this;
    }

    public boolean isNotEmpty() {
        if (selected == null || selected.isEmpty()) {
            return false;
        }
        for (String word : selected) {
            if (isNotBlank(word)) {
                return true;
            }
        }
        return false;
    }

    public void clearSelected() {
        if (selected != null) {
            selected.clear();
        }
    }

    @Override
    public String toString() {
        StringBuilder s = new StringBuilder();
        if (selected != null) {
            s.append("term");
            if (selected.size() > 1) {
                s.append('s');
            }
            s.append(": ");
            s.append(Arrays.toString(selected.toArray()));
        }
        if (pathHolder != null) {
            if (s.length() > 0) {
                s.append(' ');
            }
            s.append("on ");
            s.append(pathHolder.getPath());
        }
        return s.toString();
    }
}


for (int i = 0; i < vectors.length; i++) {
                String name = fullFieldNames[selectedFields[i]];
                LogicalType type = fullFieldTypes[selectedFields[i]].getLogicalType();
                vectors[i] = partitionSpec.containsKey(name) ? createFlinkVectorFromConstant(type, partitionSpec.get(name), batchSize) : createFlinkVector(rowBatch.cols[nonPartNames.indexOf(name)], type);
            }

package org.apache.flink.orc;

import org.apache.flink.core.fs.Path;
import org.apache.flink.orc.OrcColumnarRowSplitReader.ColumnBatchGenerator;
import org.apache.flink.orc.shim.OrcShim;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.data.vector.ColumnVector;
import org.apache.flink.table.data.vector.VectorizedColumnBatch;
import org.apache.flink.table.types.DataType;
import org.apache.flink.table.types.logical.ArrayType;
import org.apache.flink.table.types.logical.CharType;
import org.apache.flink.table.types.logical.DecimalType;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.MapType;
import org.apache.flink.table.types.logical.RowType;
import org.apache.flink.table.types.logical.VarCharType;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch;
import org.apache.orc.TypeDescription;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.apache.flink.orc.vector.AbstractOrcColumnVector.createFlinkVector;
import static org.apache.flink.orc.vector.AbstractOrcColumnVector.createFlinkVectorFromConstant;

/**
 * Util for generating {@link OrcSplitReader}.
 */
public class OrcSplitReaderUtil {

    /**
     * Util for generating partitioned {@link OrcColumnarRowSplitReader}.
     */
    public static OrcColumnarRowSplitReader<VectorizedRowBatch> genPartColumnarRowReader(String hiveVersion, Configuration conf, String[] fullFieldNames, DataType[] fullFieldTypes, Map<String, Object> partitionSpec, int[] selectedFields, List<OrcFilters.Predicate> conjunctPredicates, int batchSize, Path path, long splitStart, long splitLength) throws IOException {
        List<String> nonPartNames = getNonPartNames(fullFieldNames, partitionSpec);
        int[] selectedOrcFields = getSelectedOrcFields(fullFieldNames, selectedFields, nonPartNames);
        ColumnBatchGenerator<VectorizedRowBatch> gen = (VectorizedRowBatch rowBatch) -> {
            // create and initialize the row batch
            ColumnVector[] vectors = new ColumnVector[selectedFields.length];

            return new VectorizedColumnBatch(vectors);
        };
        return new OrcColumnarRowSplitReader<>(OrcShim.createShim(hiveVersion), conf, convertToOrcTypeWithPart(fullFieldNames, fullFieldTypes, partitionSpec.keySet()), selectedOrcFields, gen, conjunctPredicates, batchSize, path, splitStart, splitLength);
    }

    public static int[] getSelectedOrcFields(String[] fullFieldNames, int[] selectedFields, List<String> nonPartNames) {
        return Arrays.stream(selectedFields).mapToObj(i -> fullFieldNames[i]).filter(nonPartNames::contains).mapToInt(nonPartNames::indexOf).toArray();
    }

    public static List<String> getNonPartNames(String[] fullFieldNames, Collection<String> partitionKeys) {
        return Arrays.stream(fullFieldNames).filter(n -> !partitionKeys.contains(n)).collect(Collectors.toList());
    }

    public static List<String> getNonPartNames(String[] fullFieldNames, Map<String, Object> partitionSpec) {
        return Arrays.stream(fullFieldNames).filter(n -> !partitionSpec.containsKey(n)).collect(Collectors.toList());
    }

    public static TypeDescription convertToOrcTypeWithPart(String[] fullFieldNames, DataType[] fullFieldTypes, Collection<String> partitionKeys) {
        return convertToOrcTypeWithPart(fullFieldNames, Arrays.stream(fullFieldTypes).map(DataType::getLogicalType).toArray(LogicalType[]::new), partitionKeys);
    }

    public static TypeDescription convertToOrcTypeWithPart(String[] fullFieldNames, LogicalType[] fullFieldTypes, Collection<String> partitionKeys) {
        List<String> fullNameList = Arrays.asList(fullFieldNames);
        String[] orcNames = fullNameList.stream().filter(n -> !partitionKeys.contains(n)).toArray(String[]::new);
        LogicalType[] orcTypes = Arrays.stream(orcNames).mapToInt(fullNameList::indexOf).mapToObj(i -> fullFieldTypes[i]).toArray(LogicalType[]::new);
        return logicalTypeToOrcType(RowType.of(orcTypes, orcNames));
    }

    /**
     * See {@code org.apache.flink.table.catalog.hive.util.HiveTypeUtil}.
     */
    public static TypeDescription logicalTypeToOrcType(LogicalType type) {
        type = type.copy(true);
        switch(type.getTypeRoot()) {
            case CHAR:
                return TypeDescription.createChar().withMaxLength(((CharType) type).getLength());
            case VARCHAR:
                int len = ((VarCharType) type).getLength();
                if (len == VarCharType.MAX_LENGTH) {
                    return TypeDescription.createString();
                } else {
                    return TypeDescription.createVarchar().withMaxLength(len);
                }
            case BOOLEAN:
                return TypeDescription.createBoolean();
            case VARBINARY:
                if (type.equals(DataTypes.BYTES().getLogicalType())) {
                    return TypeDescription.createBinary();
                } else {
                    throw new UnsupportedOperationException("Not support other binary type: " + type);
                }
            case DECIMAL:
                DecimalType decimalType = (DecimalType) type;
                return TypeDescription.createDecimal().withScale(decimalType.getScale()).withPrecision(decimalType.getPrecision());
            case TINYINT:
                return TypeDescription.createByte();
            case SMALLINT:
                return TypeDescription.createShort();
            case INTEGER:
                return TypeDescription.createInt();
            case BIGINT:
                return TypeDescription.createLong();
            case FLOAT:
                return TypeDescription.createFloat();
            case DOUBLE:
                return TypeDescription.createDouble();
            case DATE:
                return TypeDescription.createDate();
            case TIMESTAMP_WITHOUT_TIME_ZONE:
                return TypeDescription.createTimestamp();
            case ARRAY:
                ArrayType arrayType = (ArrayType) type;
                return TypeDescription.createList(logicalTypeToOrcType(arrayType.getElementType()));
            case MAP:
                MapType mapType = (MapType) type;
                return TypeDescription.createMap(logicalTypeToOrcType(mapType.getKeyType()), logicalTypeToOrcType(mapType.getValueType()));
            case ROW:
                RowType rowType = (RowType) type;
                TypeDescription struct = TypeDescription.createStruct();
                for (int i = 0; i < rowType.getFieldCount(); i++) {
                    struct.addField(rowType.getFieldNames().get(i), logicalTypeToOrcType(rowType.getChildren().get(i)));
                }
                return struct;
            default:
                throw new UnsupportedOperationException("Unsupported type: " + type);
        }
    }
}


try {
            mCallback = (SelectionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement SelectionListener");
        }

package course.labs.notificationslab;

import android.app.Activity;
import android.app.ListFragment;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class FriendsFragment extends ListFragment {

    // HostingActivity
    private SelectionListener mCallback;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, MainActivity.FRIENDS_NAMES));
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // Make sure that the hosting Activity has implemented
        // the callback interface.

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Enable user interaction only if data is available
        setAllowUserClicks(mCallback.canAllowUserClicks());
    }

    // Enable/disable user interaction
    void setAllowUserClicks(boolean allowUserInteraction) {
        getListView().setEnabled(allowUserInteraction);
        if (allowUserInteraction) {
            getListView().setBackgroundColor(Color.WHITE);
        } else {
            getListView().setBackgroundColor(Color.DKGRAY);
        }
    }

    @Override
    public void onListItemClick(ListView l, View view, int position, long id) {
        // Inform hosting Activity of user's selection
        if (null != mCallback) {
            mCallback.onItemSelected(position);
        }
    }
}


try {
            optionalCasesFile.writeTo(System.out);
        } catch (IOException e) {
            e.printStackTrace();
        }

package com.leacox.motif.cases;

import com.leacox.motif.generate.CasesGenerator;
import com.leacox.motif.generate.Match0MethodSpec;
import com.leacox.motif.generate.Match1MethodSpec;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeVariableName;
import java.io.IOException;
import java.util.Optional;

/**
 * Generator for {@link Optional} match cases.
 *
 * @author John Leacox
 */
final class OptionalCasesGenerator {

    private OptionalCasesGenerator() {
    }

    public static void main(String[] args) {
        TypeName T = TypeVariableName.get("T");
        TypeName o = ParameterizedTypeName.get(ClassName.get(Optional.class), T);
        Match0MethodSpec noneMatch = Match0MethodSpec.builder().withName("none").withSummaryJavadoc("Matches an empty {@link Optional}.\n").withMatchExtractor(OptionalNoneFieldExtractor.class).build();
        Match1MethodSpec someMatch = Match1MethodSpec.builder().withName("some").withSummaryJavadoc("Matches a non-empty {@link Optional}.\n").withMatchExtractor(OptionalFieldExtractor.class).withParamA(T, "t").build();
        JavaFile optionalCasesFile = CasesGenerator.newBuilder("com.leacox.motif.cases", "OptionalCases", o).addFileComment(Copyright.COPYRIGHT_NOTICE).addJavadoc("Motif cases for matching an {@link Optional}.\n").addMatch0Method(noneMatch).addMatch1Method(someMatch).build().generate();


for (int i = 0; i <= queueSize; i++) {
                queue.offer(node.left);
                queue.offer(node.right);
                if (i == queueSize) {
                    node.next = null;
                    break;
                }
                Node temp = queue.poll();
                node.next = temp;
                node = temp;
            }

package com.leosanqing.leetcode.medium.tree;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class _116_populating_next_right_pointers_in_each_node {

    public static void main(String[] args) {
        Node treeNode = new Node(1);
        treeNode.left = new Node(2);
        treeNode.right = new Node(3);
        treeNode.left.left = new Node(4);
        treeNode.left.right = new Node(5);
        treeNode.right.left = new Node(6);
        treeNode.right.right = new Node(7);
        connect(treeNode);
    }

    public static Node connect(Node root) {
        if (root == null) {
            return null;
        }
        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int queueSize = queue.size() - 1;
            Node node = queue.poll();
            // because of perfect binary tree
            if (node == null) {
                break;
            }


for (int i = 0; i < ISSUES_NAMES.length; i++) {
            generateIssue(i);
        }

package fr.putnami.pwt.tutorial.server.service;

import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Service;
import fr.putnami.pwt.tutorial.shared.domain.Issue;
import fr.putnami.pwt.tutorial.shared.domain.Type;
import fr.putnami.pwt.tutorial.shared.service.IssueService;

@Service
public class IssueServiceImpl implements IssueService {

    private static final AtomicLong SEQUENCE = new AtomicLong();

    private Map<Long, Issue> issues = Maps.newHashMap();

    @Override
    public List<Issue> listIssues() {
        return Lists.newArrayList(issues.values());
    }

    @Override
    public List<Issue> searchIssues(final String name, final String label) {
        Iterable<Issue> filteredIterable = Iterables.filter(issues.values(), new Predicate<Issue>() {

            @Override
            public boolean apply(Issue issue) {
                boolean result = true;
                if (name != null) {
                    result = issue.getName() != null && issue.getName().toLowerCase().contains(name.toLowerCase());
                }
                if (result && label != null) {
                    Iterable<String> filteredLabels = Iterables.filter(issue.getLabels(), new Predicate<String>() {

                        @Override
                        public boolean apply(String issueLabel) {
                            return issueLabel != null && issueLabel.toLowerCase().contains(label.toLowerCase());
                        }
                    });
                    result = result && filteredLabels.iterator().hasNext();
                }
                return result;
            }
        });
        return Lists.newArrayList(filteredIterable);
    }

    @Override
    public Issue saveIssue(Issue issue) {
        if (issue.getId() == null) {
            issue.setId(SEQUENCE.incrementAndGet());
        }
        issues.put(issue.getId(), issue);
        return issue;
    }

    public IssueServiceImpl() {

    }

    private void generateIssue(int i) {
        Issue issue = new Issue();
        issue.setId(SEQUENCE.incrementAndGet());
        issue.setName(ISSUES_NAMES[i]);
        issue.getLabels().add(nextValue(ISSUES_LABEL));
        if (new Random().nextBoolean()) {
            issue.getLabels().add("Duplicate");
        }
        if (new Random().nextBoolean()) {
            issue.getLabels().add("Invalid");
        }
        if (new Random().nextBoolean()) {
            issue.getLabels().add("WontFix");
        }
        issue.setDescription("This is a sample description");
        issue.setType(nextValue(Type.values()));
        issues.put(issue.getId(), issue);
    }

    private <T> T nextValue(T[] array) {
        return array[new Random().nextInt(array.length)];
    }

    private static final String[] ISSUES_NAMES = { "UI - Image", "Ui - InputRadioBox", "Ui - Progress Bar", "Ui - Icon customisation", "Ui - InputCheckBox", "Eclipse GWT classpath", "Code editor - IE issue" };

    private static final String[] ISSUES_LABEL = { "Bug", "Enhancement", "Question" };
}


public void setError(String error) {
        this.error = error;
    }

package ucar.ui.widget;

/**
 * Subclass this for use in a ProgressMonitor. Responsibilities of your subclass:
 *

 *
You must provide the run method, which actually does the work that the ProgressMonitor
 * is showing progress for.
 *
You must set the done flag for the ProgressMonitor to complete. To avoid race conditions,
 * do eveything else before you set the done flag.
 *
You should override setProgress() and return a real count that corresponds to progressMaxCount in
 * ProgressMonitor.start().
 *
If possible, you should stop working if isCancel(). Usually this means checking the
 * cancel flag in an iteration.
 *
You should set the success flag if everything worked ok.
 *
You should set an error message if there is an error. Normally you would also
 * set done=true, and stop working. The ProgressMonitor will detect this and exit.
 *

 * The ProgressMonitor will:
 *

 *
Call cancel() if the user pressed cancel.
 *
Set progress value by counting elapsed seconds. You may overrride this by overridding getProgress()
 * and/or getNote().
 *

 *
 * Also can be adapted as a CancelTask implementation.
 *
 * @see ProgressMonitor
 */
public abstract class ProgressMonitorTask implements Runnable {

    protected boolean done;

    protected boolean success;

    protected boolean cancel;

    protected String error;

    protected String note;

    protected int progress;

    /**
     * Here is where the work gets done.
     */
    public abstract void run();

    /**
     * Application calls to see if task is success.
     */
    public boolean isSuccess() {
        return success;
    }

    /**
     * Application calls to see if task is cancelled.
     */
    public boolean isCancel() {
        return cancel;
    }

    /**
     * Applications call this to find out if there was an error.
     */
    public boolean isError() {
        return error != null;
    }

    /**
     * Applications call this to get an error message.
     */
    public String getErrorMessage() {
        return error;
    }

    /**
     * ProgressMonitor calls to see if task is done.
     */
    public boolean isDone() {
        return done;
    }

    /**
     * ProgressMonitor will call this when the user cancels.
     */
    public void cancel() {
        cancel = true;
        success = false;
    }

    /**
     * ProgressMonitor displays this note in the ProgressMonitor. If null, ProgressMonitor will show
     * elasped seconds.
     */
    public String getNote() {
        return note;
    }

    /**
     * ProgressMonitor displays this progress value in the ProgressMonitor. If <0, ProgressMonitor will show
     * elasped seconds.
     */
    public int getProgress() {
        return progress;
    }

    /**
     * for compatibility with ucar.nc2.CancelTask
     */

    public void setProgress(String msg, int progress) {
        this.note = msg;
        if (progress > 0)
            this.progress = progress;
    }

    public void setDone(boolean done) {
        this.done = done;
    }
}


@Override
        public Class<?> getReturnType() {
            return method.getReturnType();
        }

package org.apache.velocity.util.introspection;

import org.apache.velocity.exception.VelocityException;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.runtime.parser.node.AbstractExecutor;
import org.apache.velocity.runtime.parser.node.BooleanPropertyExecutor;
import org.apache.velocity.runtime.parser.node.GetExecutor;
import org.apache.velocity.runtime.parser.node.MapGetExecutor;
import org.apache.velocity.runtime.parser.node.MapSetExecutor;
import org.apache.velocity.runtime.parser.node.PropertyExecutor;
import org.apache.velocity.runtime.parser.node.PutExecutor;
import org.apache.velocity.runtime.parser.node.SetExecutor;
import org.apache.velocity.runtime.parser.node.SetPropertyExecutor;
import org.apache.velocity.util.ArrayIterator;
import org.apache.velocity.util.ArrayListWrapper;
import org.apache.velocity.util.ClassUtils;
import org.apache.velocity.util.EnumerationIterator;
import org.apache.velocity.util.RuntimeServicesAware;
import org.slf4j.Logger;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;

/**
 *  Implementation of Uberspect to provide the default introspective
 *  functionality of Velocity
 *
 * @author Geir Magnusson Jr.
 * @author Henning P. Schmiedehausen
 * @version $Id$
 */
public class UberspectImpl implements Uberspect, RuntimeServicesAware {

    /**
     *  Our runtime logger.
     */
    protected Logger log;

    protected Introspector introspector;

    /**
     * the conversion handler
     */
    protected TypeConversionHandler conversionHandler;

    /**
     * runtime services
     */
    protected RuntimeServices rsvc;

    /**
     *  init - generates the Introspector. As the setup code
     *  makes sure that the log gets set before this is called,
     *  we can initialize the Introspector using the log object.
     */
    @Override
    public void init() {
        introspector = new Introspector(log, conversionHandler);
    }

    public TypeConversionHandler getConversionHandler() {
        return conversionHandler;
    }

    /**
     * sets the runtime services
     * @param rs runtime services
     */
    @Override
    @SuppressWarnings("deprecation")
    public void setRuntimeServices(RuntimeServices rs) {
        rsvc = rs;
        log = rsvc.getLog("introspection");
        Object conversionHandlerInstance = rs.getProperty(RuntimeConstants.CONVERSION_HANDLER_INSTANCE);
        if (conversionHandlerInstance == null) {
            String conversionHandlerClass = rs.getString(RuntimeConstants.CONVERSION_HANDLER_CLASS);
            if (conversionHandlerClass != null && !conversionHandlerClass.equals("none")) {
                try {
                    conversionHandlerInstance = ClassUtils.getNewInstance(conversionHandlerClass);
                } catch (ClassNotFoundException cnfe) {
                    String err = "The specified class for ConversionHandler (" + conversionHandlerClass + ") does not exist or is not accessible to the current classloader.";
                    log.error(err);
                    throw new VelocityException(err, cnfe);
                } catch (InstantiationException ie) {
                    throw new VelocityException("Could not instantiate class '" + conversionHandlerClass + "'", ie);
                } catch (IllegalAccessException ae) {
                    throw new VelocityException("Cannot access class '" + conversionHandlerClass + "'", ae);
                }
            }
        }
        if (conversionHandlerInstance != null) {
            if (conversionHandlerInstance instanceof ConversionHandler) {
                log.warn("The ConversionHandler interface is deprecated - see the TypeConversionHandler interface");
                final ConversionHandler ch = (ConversionHandler) conversionHandlerInstance;
                conversionHandler = new TypeConversionHandler() {

                    @Override
                    public boolean isExplicitlyConvertible(Type formal, Class<?> actual, boolean possibleVarArg) {
                        Class<?> formalClass = IntrospectionUtils.getTypeClass(formal);
                        if (formalClass != null)
                            return ch.isExplicitlyConvertible(formalClass, actual, possibleVarArg);
                        else
                            return false;
                    }

                    @Override
                    public Converter<?> getNeededConverter(Type formal, Class<?> actual) {
                        Class<?> formalClass = IntrospectionUtils.getTypeClass(formal);
                        if (formalClass != null)
                            return ch.getNeededConverter(formalClass, actual);
                        else
                            return null;
                    }

                    @Override
                    public void addConverter(Type formal, Class<?> actual, Converter<?> converter) {
                        Class<?> formalClass = IntrospectionUtils.getTypeClass(formal);
                        if (formalClass != null)
                            ch.addConverter(formalClass, actual, converter);
                        else
                            throw new UnsupportedOperationException("This conversion handler doesn't know how to handle Type: " + formal.getTypeName());
                    }
                };
            } else if (!(conversionHandlerInstance instanceof TypeConversionHandler)) {
                String err = "The specified class or provided instance for the conversion handler (" + conversionHandlerInstance.getClass().getName() + ") does not implement " + TypeConversionHandler.class.getName() + "; Velocity is not initialized correctly.";
                log.error(err);
                throw new VelocityException(err, null, rsvc.getLogContext().getStackTrace());
            } else {
                conversionHandler = (TypeConversionHandler) conversionHandlerInstance;
            }
        }
    }

    /**
     *  Sets the runtime logger - this must be called before anything
     *  else.
     *
     * @param log The logger instance to use.
     * @since 1.5
     * @deprecated logger is now set by default to the namespace logger "velocity.rendering".
     */
    public void setLog(Logger log) {
        this.log = log;
    }

    /**
     *  To support iterative objects used in a #foreach()
     *  loop.
     *
     * @param obj The iterative object.
     * @param i Info about the object's location.
     * @return An {@link Iterator} object.
     */
    @Override
    public Iterator getIterator(Object obj, Info i) {
        if (obj.getClass().isArray()) {
            return new ArrayIterator(obj);
        } else if (obj instanceof Iterable) {
            return ((Iterable) obj).iterator();
        } else if (obj instanceof Map) {
            return ((Map) obj).values().iterator();
        } else if (obj instanceof Iterator) {
            log.debug("The iterative object in the #foreach() loop at {}" + " is of type java.util.Iterator.  Because " + "it is not resettable, if used in more than once it " + "may lead to unexpected results.", i);
            return ((Iterator) obj);
        } else if (obj instanceof Enumeration) {
            log.debug("The iterative object in the #foreach() loop at {}" + " is of type java.util.Enumeration.  Because " + "it is not resettable, if used in more than once it " + "may lead to unexpected results.", i);
            return new EnumerationIterator((Enumeration) obj);
        } else {
            // look for an iterator() method to support the JDK5 Iterable
            // interface or any user tools/DTOs that want to work in
            // foreach without implementing the Collection interface
            Class<?> type = obj.getClass();
            try {
                Method iter = type.getMethod("iterator");
                Class<?> returns = iter.getReturnType();
                if (Iterator.class.isAssignableFrom(returns)) {
                    try {
                        return (Iterator) iter.invoke(obj);
                    } catch (IllegalAccessException e) {
                        // Cannot invoke this method, just give up
                    } catch (Exception e) {
                        throw new VelocityException("Error invoking the method 'iterator' on class '" + obj.getClass().getName() + "'", e, rsvc.getLogContext().getStackTrace());
                    }
                } else {
                    log.debug("iterator() method of reference in #foreach loop at " + "{} does not return a true Iterator.", i);
                }
            } catch (NoSuchMethodException nsme) {
                // eat this one, but let all other exceptions thru
            }
        }
        /*  we have no clue what this is  */
        log.debug("Could not determine type of iterator in #foreach loop at {}", i);
        return null;
    }

    /**
     *  Method
     * @param obj
     * @param methodName
     * @param args
     * @param i
     * @return A Velocity Method.
     */
    @Override
    public VelMethod getMethod(Object obj, String methodName, Object[] args, Info i) {
        if (obj == null) {
            return null;
        }
        Method m = introspector.getMethod(obj.getClass(), methodName, args);
        if (m != null) {
            return new VelMethodImpl(m, false, getNeededConverters(m.getGenericParameterTypes(), args));
        }
        Class<?> cls = obj.getClass();
        // if it's an array
        if (cls.isArray()) {
            // check for support via our array->list wrapper
            m = introspector.getMethod(ArrayListWrapper.class, methodName, args);
            if (m != null) {
                // and create a method that knows to wrap the value
                // before invoking the method
                return new VelMethodImpl(m, true, getNeededConverters(m.getGenericParameterTypes(), args));
            }
        } else // watch for classes, to allow calling their static methods (VELOCITY-102)
        if (cls == Class.class) {
            m = introspector.getMethod((Class<?>) obj, methodName, args);
            if (m != null) {
                return new VelMethodImpl(m, false, getNeededConverters(m.getGenericParameterTypes(), args));
            }
        }
        return null;
    }

    /**
     * get the list of needed converters to adapt passed argument types to method types
     * @return null if not conversion needed, otherwise an array containing needed converters
     */
    private Converter<?>[] getNeededConverters(Type[] expected, Object[] provided) {
        if (conversionHandler == null)
            return null;
        // var args are not handled here - CB TODO
        int n = Math.min(expected.length, provided.length);
        Converter<?>[] converters = null;
        for (int i = 0; i < n; ++i) {
            Object arg = provided[i];
            if (arg == null)
                continue;
            Converter<?> converter = conversionHandler.getNeededConverter(expected[i], arg.getClass());
            if (converter != null) {
                if (converters == null) {
                    converters = new Converter[expected.length];
                }
                converters[i] = converter;
            }
        }
        return converters;
    }

    /**
     * Property  getter
     * @param obj
     * @param identifier
     * @param i
     * @return A Velocity Getter Method.
     */
    @Override
    public VelPropertyGet getPropertyGet(Object obj, String identifier, Info i) {
        if (obj == null) {
            return null;
        }
        Class<?> claz = obj.getClass();
        /*
         *  first try for a getFoo() type of property
         *  (also getfoo() )
         */
        AbstractExecutor executor = new PropertyExecutor(log, introspector, claz, identifier);
        /*
         * Let's see if we are a map...
         */
        if (!executor.isAlive()) {
            executor = new MapGetExecutor(log, obj, identifier);
        }
        if (!executor.isAlive()) {
            executor = new GetExecutor(log, introspector, claz, identifier);
        }
        if (!executor.isAlive()) {
            executor = new BooleanPropertyExecutor(log, introspector, claz, identifier);
        }
        /*
         * and idem on an array
         */
        if (!executor.isAlive() && obj.getClass().isArray()) {
            executor = new BooleanPropertyExecutor(log, introspector, ArrayListWrapper.class, identifier, true);
        }
        return (executor.isAlive()) ? new VelGetterImpl(executor) : null;
    }

    /**
     * Property setter
     * @param obj
     * @param identifier
     * @param arg
     * @param i
     * @return A Velocity Setter method.
     */
    @Override
    public VelPropertySet getPropertySet(Object obj, String identifier, Object arg, Info i) {
        if (obj == null) {
            return null;
        }
        Class<?> claz = obj.getClass();
        /*
         *  first try for a setFoo() type of property
         *  (also setfoo() )
         */
        SetExecutor executor = new SetPropertyExecutor(log, introspector, claz, identifier, arg);
        /*
         * Let's see if we are a map...
         */
        if (!executor.isAlive()) {
            executor = new MapSetExecutor(log, claz, identifier);
        }
        if (!executor.isAlive()) {
            executor = new PutExecutor(log, introspector, claz, arg, identifier);
        }
        return (executor.isAlive()) ? new VelSetterImpl(executor) : null;
    }

    /**
     *  Implementation of VelMethod
     */
    public static class VelMethodImpl implements VelMethod {

        final Method method;

        Boolean isVarArg;

        boolean wrapArray;

        Converter<?>[] converters;

        /**
         * @param m
         */
        public VelMethodImpl(Method m) {
            this(m, false, null);
        }

        /**
         * @param method
         * @param wrapArray
         * @since 1.6
         */
        public VelMethodImpl(Method method, boolean wrapArray) {
            this(method, wrapArray, null);
        }

        /**
         * @param method
         * @param wrapArray
         * @param converters
         * @since 2.0
         */
        public VelMethodImpl(Method method, boolean wrapArray, Converter<?>[] converters) {
            this.method = method;
            this.wrapArray = wrapArray;
            this.converters = converters;
        }

        private VelMethodImpl() {
            method = null;
        }

        /**
         * @param o
         * @param actual
         * @return invocation result
         * @see VelMethod#invoke(java.lang.Object, java.lang.Object[])
         */
        @Override
        public Object invoke(Object o, Object[] actual) throws IllegalAccessException, InvocationTargetException {
            // if we're pretending an array is a list...
            if (wrapArray) {
                o = new ArrayListWrapper(o);
            }
            if (isVarArg()) {
                Class<?>[] formal = method.getParameterTypes();
                int index = formal.length - 1;
                if (actual.length >= index) {
                    Class<?> type = formal[index].getComponentType();
                    actual = handleVarArg(type, index, actual);
                }
            }
            if (converters != null) {
                // some converters may throw an ArithmeticException
                // which we want to wrap into an IllegalArgumentException
                try {
                    for (int i = 0; i < actual.length; ++i) {
                        if (converters[i] != null) {
                            actual[i] = converters[i].convert(actual[i]);
                        }
                    }
                } catch (ArithmeticException ae) {
                    throw new IllegalArgumentException(ae);
                }
            }
            // call extension point invocation
            return doInvoke(o, actual);
        }

        /**
         * Offers an extension point for subclasses (in alternate Uberspects)
         * to alter the invocation after any array wrapping or varargs handling
         * has already been completed.
         * @param o target object
         * @param actual arguments
         * @return invocation result
         * @throws IllegalAccessException
         * @throws InvocationTargetException
         * @since 1.6
         */
        protected Object doInvoke(Object o, Object[] actual) throws IllegalAccessException, InvocationTargetException {
            return method.invoke(o, actual);
        }

        /**
         * @return true if this method can accept a variable number of arguments
         * @since 1.6
         */
        public boolean isVarArg() {
            if (isVarArg == null) {
                Class<?>[] formal = method.getParameterTypes();
                if (formal.length == 0) {
                    this.isVarArg = Boolean.FALSE;
                } else {
                    Class<?> last = formal[formal.length - 1];
                    // if the last arg is an array, then
                    // we consider this a varargs method
                    this.isVarArg = last.isArray();
                }
            }
            return isVarArg;
        }

        /**
         * @param type The vararg class type (aka component type
         *             of the expected array arg)
         * @param index The index of the vararg in the method declaration
         *              (This will always be one less than the number of
         *               expected arguments.)
         * @param actual The actual parameters being passed to this method
         * @return The actual parameters adjusted for the varargs in order
         *          to fit the method declaration.
         */
        private Object[] handleVarArg(final Class<?> type, final int index, Object[] actual) {
            // if no values are being passed into the vararg
            if (actual.length == index) {
                // copy existing args to new array
                Object[] newActual = new Object[actual.length + 1];
                System.arraycopy(actual, 0, newActual, 0, actual.length);
                // create an empty array of the expected type
                newActual[index] = Array.newInstance(type, 0);
                actual = newActual;
            } else // if one value is being passed into the vararg
            if (actual.length == index + 1 && actual[index] != null) {
                // make sure the last arg is an array of the expected type
                Class<?> argClass = actual[index].getClass();
                if (!argClass.isArray() && IntrospectionUtils.isMethodInvocationConvertible(type, argClass, false)) {
                    // create a 1-length array to hold and replace the last param
                    Object lastActual = Array.newInstance(type, 1);
                    Array.set(lastActual, 0, actual[index]);
                    actual[index] = lastActual;
                }
            } else // if multiple values are being passed into the vararg
            if (actual.length > index + 1) {
                // put the last and extra actual in an array of the expected type
                int size = actual.length - index;
                Object lastActual = Array.newInstance(type, size);
                for (int i = 0; i < size; i++) {
                    Array.set(lastActual, i, actual[index + i]);
                }
                // put all into a new actual array of the appropriate size
                Object[] newActual = new Object[index + 1];
                System.arraycopy(actual, 0, newActual, 0, index);
                newActual[index] = lastActual;
                // replace the old actual array
                actual = newActual;
            }
            return actual;
        }

        /**
         * @see org.apache.velocity.util.introspection.VelMethod#isCacheable()
         */
        @Override
        public boolean isCacheable() {
            return true;
        }

        /**
         * @see org.apache.velocity.util.introspection.VelMethod#getMethodName()
         */
        @Override
        public String getMethodName() {
            return method.getName();
        }

        /**
         * @see org.apache.velocity.util.introspection.VelMethod#getMethod()
         */
        @Override
        public Method getMethod() {
            return method;
        }

        /**
         * @see org.apache.velocity.util.introspection.VelMethod#getReturnType()
         */

    }

    public static class VelGetterImpl implements VelPropertyGet {

        final AbstractExecutor getExecutor;

        /**
         * @param exec
         */
        public VelGetterImpl(AbstractExecutor exec) {
            getExecutor = exec;
        }

        private VelGetterImpl() {
            getExecutor = null;
        }

        /**
         * @see org.apache.velocity.util.introspection.VelPropertyGet#invoke(java.lang.Object)
         */
        @Override
        public Object invoke(Object o) throws IllegalAccessException, InvocationTargetException {
            return getExecutor.execute(o);
        }

        /**
         * @see org.apache.velocity.util.introspection.VelPropertyGet#isCacheable()
         */
        @Override
        public boolean isCacheable() {
            return true;
        }

        /**
         * @see org.apache.velocity.util.introspection.VelPropertyGet#getMethodName()
         */
        @Override
        public String getMethodName() {
            return getExecutor.isAlive() ? getExecutor.getMethod().getName() : null;
        }
    }

    public static class VelSetterImpl implements VelPropertySet {

        private final SetExecutor setExecutor;

        /**
         * @param setExecutor
         */
        public VelSetterImpl(final SetExecutor setExecutor) {
            this.setExecutor = setExecutor;
        }

        private VelSetterImpl() {
            setExecutor = null;
        }

        /**
         * Invoke the found Set Executor.
         *
         * @param o is the Object to invoke it on.
         * @param value in the Value to set.
         * @return The resulting Object.
         */
        @Override
        public Object invoke(final Object o, final Object value) throws IllegalAccessException, InvocationTargetException {
            return setExecutor.execute(o, value);
        }

        /**
         * @see org.apache.velocity.util.introspection.VelPropertySet#isCacheable()
         */
        @Override
        public boolean isCacheable() {
            return true;
        }

        /**
         * @see org.apache.velocity.util.introspection.VelPropertySet#getMethodName()
         */
        @Override
        public String getMethodName() {
            return setExecutor.isAlive() ? setExecutor.getMethod().getName() : null;
        }
    }
}


for (int i = 0; i < actual.length; ++i) {
                        if (converters[i] != null) {
                            actual[i] = converters[i].convert(actual[i]);
                        }
                    }

package org.apache.velocity.util.introspection;

import org.apache.velocity.exception.VelocityException;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.runtime.parser.node.AbstractExecutor;
import org.apache.velocity.runtime.parser.node.BooleanPropertyExecutor;
import org.apache.velocity.runtime.parser.node.GetExecutor;
import org.apache.velocity.runtime.parser.node.MapGetExecutor;
import org.apache.velocity.runtime.parser.node.MapSetExecutor;
import org.apache.velocity.runtime.parser.node.PropertyExecutor;
import org.apache.velocity.runtime.parser.node.PutExecutor;
import org.apache.velocity.runtime.parser.node.SetExecutor;
import org.apache.velocity.runtime.parser.node.SetPropertyExecutor;
import org.apache.velocity.util.ArrayIterator;
import org.apache.velocity.util.ArrayListWrapper;
import org.apache.velocity.util.ClassUtils;
import org.apache.velocity.util.EnumerationIterator;
import org.apache.velocity.util.RuntimeServicesAware;
import org.slf4j.Logger;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;

/**
 *  Implementation of Uberspect to provide the default introspective
 *  functionality of Velocity
 *
 * @author Geir Magnusson Jr.
 * @author Henning P. Schmiedehausen
 * @version $Id$
 */
public class UberspectImpl implements Uberspect, RuntimeServicesAware {

    /**
     *  Our runtime logger.
     */
    protected Logger log;

    protected Introspector introspector;

    /**
     * the conversion handler
     */
    protected TypeConversionHandler conversionHandler;

    /**
     * runtime services
     */
    protected RuntimeServices rsvc;

    /**
     *  init - generates the Introspector. As the setup code
     *  makes sure that the log gets set before this is called,
     *  we can initialize the Introspector using the log object.
     */
    @Override
    public void init() {
        introspector = new Introspector(log, conversionHandler);
    }

    public TypeConversionHandler getConversionHandler() {
        return conversionHandler;
    }

    /**
     * sets the runtime services
     * @param rs runtime services
     */
    @Override
    @SuppressWarnings("deprecation")
    public void setRuntimeServices(RuntimeServices rs) {
        rsvc = rs;
        log = rsvc.getLog("introspection");
        Object conversionHandlerInstance = rs.getProperty(RuntimeConstants.CONVERSION_HANDLER_INSTANCE);
        if (conversionHandlerInstance == null) {
            String conversionHandlerClass = rs.getString(RuntimeConstants.CONVERSION_HANDLER_CLASS);
            if (conversionHandlerClass != null && !conversionHandlerClass.equals("none")) {
                try {
                    conversionHandlerInstance = ClassUtils.getNewInstance(conversionHandlerClass);
                } catch (ClassNotFoundException cnfe) {
                    String err = "The specified class for ConversionHandler (" + conversionHandlerClass + ") does not exist or is not accessible to the current classloader.";
                    log.error(err);
                    throw new VelocityException(err, cnfe);
                } catch (InstantiationException ie) {
                    throw new VelocityException("Could not instantiate class '" + conversionHandlerClass + "'", ie);
                } catch (IllegalAccessException ae) {
                    throw new VelocityException("Cannot access class '" + conversionHandlerClass + "'", ae);
                }
            }
        }
        if (conversionHandlerInstance != null) {
            if (conversionHandlerInstance instanceof ConversionHandler) {
                log.warn("The ConversionHandler interface is deprecated - see the TypeConversionHandler interface");
                final ConversionHandler ch = (ConversionHandler) conversionHandlerInstance;
                conversionHandler = new TypeConversionHandler() {

                    @Override
                    public boolean isExplicitlyConvertible(Type formal, Class<?> actual, boolean possibleVarArg) {
                        Class<?> formalClass = IntrospectionUtils.getTypeClass(formal);
                        if (formalClass != null)
                            return ch.isExplicitlyConvertible(formalClass, actual, possibleVarArg);
                        else
                            return false;
                    }

                    @Override
                    public Converter<?> getNeededConverter(Type formal, Class<?> actual) {
                        Class<?> formalClass = IntrospectionUtils.getTypeClass(formal);
                        if (formalClass != null)
                            return ch.getNeededConverter(formalClass, actual);
                        else
                            return null;
                    }

                    @Override
                    public void addConverter(Type formal, Class<?> actual, Converter<?> converter) {
                        Class<?> formalClass = IntrospectionUtils.getTypeClass(formal);
                        if (formalClass != null)
                            ch.addConverter(formalClass, actual, converter);
                        else
                            throw new UnsupportedOperationException("This conversion handler doesn't know how to handle Type: " + formal.getTypeName());
                    }
                };
            } else if (!(conversionHandlerInstance instanceof TypeConversionHandler)) {
                String err = "The specified class or provided instance for the conversion handler (" + conversionHandlerInstance.getClass().getName() + ") does not implement " + TypeConversionHandler.class.getName() + "; Velocity is not initialized correctly.";
                log.error(err);
                throw new VelocityException(err, null, rsvc.getLogContext().getStackTrace());
            } else {
                conversionHandler = (TypeConversionHandler) conversionHandlerInstance;
            }
        }
    }

    /**
     *  Sets the runtime logger - this must be called before anything
     *  else.
     *
     * @param log The logger instance to use.
     * @since 1.5
     * @deprecated logger is now set by default to the namespace logger "velocity.rendering".
     */
    public void setLog(Logger log) {
        this.log = log;
    }

    /**
     *  To support iterative objects used in a #foreach()
     *  loop.
     *
     * @param obj The iterative object.
     * @param i Info about the object's location.
     * @return An {@link Iterator} object.
     */
    @Override
    public Iterator getIterator(Object obj, Info i) {
        if (obj.getClass().isArray()) {
            return new ArrayIterator(obj);
        } else if (obj instanceof Iterable) {
            return ((Iterable) obj).iterator();
        } else if (obj instanceof Map) {
            return ((Map) obj).values().iterator();
        } else if (obj instanceof Iterator) {
            log.debug("The iterative object in the #foreach() loop at {}" + " is of type java.util.Iterator.  Because " + "it is not resettable, if used in more than once it " + "may lead to unexpected results.", i);
            return ((Iterator) obj);
        } else if (obj instanceof Enumeration) {
            log.debug("The iterative object in the #foreach() loop at {}" + " is of type java.util.Enumeration.  Because " + "it is not resettable, if used in more than once it " + "may lead to unexpected results.", i);
            return new EnumerationIterator((Enumeration) obj);
        } else {
            // look for an iterator() method to support the JDK5 Iterable
            // interface or any user tools/DTOs that want to work in
            // foreach without implementing the Collection interface
            Class<?> type = obj.getClass();
            try {
                Method iter = type.getMethod("iterator");
                Class<?> returns = iter.getReturnType();
                if (Iterator.class.isAssignableFrom(returns)) {
                    try {
                        return (Iterator) iter.invoke(obj);
                    } catch (IllegalAccessException e) {
                        // Cannot invoke this method, just give up
                    } catch (Exception e) {
                        throw new VelocityException("Error invoking the method 'iterator' on class '" + obj.getClass().getName() + "'", e, rsvc.getLogContext().getStackTrace());
                    }
                } else {
                    log.debug("iterator() method of reference in #foreach loop at " + "{} does not return a true Iterator.", i);
                }
            } catch (NoSuchMethodException nsme) {
                // eat this one, but let all other exceptions thru
            }
        }
        /*  we have no clue what this is  */
        log.debug("Could not determine type of iterator in #foreach loop at {}", i);
        return null;
    }

    /**
     *  Method
     * @param obj
     * @param methodName
     * @param args
     * @param i
     * @return A Velocity Method.
     */
    @Override
    public VelMethod getMethod(Object obj, String methodName, Object[] args, Info i) {
        if (obj == null) {
            return null;
        }
        Method m = introspector.getMethod(obj.getClass(), methodName, args);
        if (m != null) {
            return new VelMethodImpl(m, false, getNeededConverters(m.getGenericParameterTypes(), args));
        }
        Class<?> cls = obj.getClass();
        // if it's an array
        if (cls.isArray()) {
            // check for support via our array->list wrapper
            m = introspector.getMethod(ArrayListWrapper.class, methodName, args);
            if (m != null) {
                // and create a method that knows to wrap the value
                // before invoking the method
                return new VelMethodImpl(m, true, getNeededConverters(m.getGenericParameterTypes(), args));
            }
        } else // watch for classes, to allow calling their static methods (VELOCITY-102)
        if (cls == Class.class) {
            m = introspector.getMethod((Class<?>) obj, methodName, args);
            if (m != null) {
                return new VelMethodImpl(m, false, getNeededConverters(m.getGenericParameterTypes(), args));
            }
        }
        return null;
    }

    /**
     * get the list of needed converters to adapt passed argument types to method types
     * @return null if not conversion needed, otherwise an array containing needed converters
     */
    private Converter<?>[] getNeededConverters(Type[] expected, Object[] provided) {
        if (conversionHandler == null)
            return null;
        // var args are not handled here - CB TODO
        int n = Math.min(expected.length, provided.length);
        Converter<?>[] converters = null;
        for (int i = 0; i < n; ++i) {
            Object arg = provided[i];
            if (arg == null)
                continue;
            Converter<?> converter = conversionHandler.getNeededConverter(expected[i], arg.getClass());
            if (converter != null) {
                if (converters == null) {
                    converters = new Converter[expected.length];
                }
                converters[i] = converter;
            }
        }
        return converters;
    }

    /**
     * Property  getter
     * @param obj
     * @param identifier
     * @param i
     * @return A Velocity Getter Method.
     */
    @Override
    public VelPropertyGet getPropertyGet(Object obj, String identifier, Info i) {
        if (obj == null) {
            return null;
        }
        Class<?> claz = obj.getClass();
        /*
         *  first try for a getFoo() type of property
         *  (also getfoo() )
         */
        AbstractExecutor executor = new PropertyExecutor(log, introspector, claz, identifier);
        /*
         * Let's see if we are a map...
         */
        if (!executor.isAlive()) {
            executor = new MapGetExecutor(log, obj, identifier);
        }
        if (!executor.isAlive()) {
            executor = new GetExecutor(log, introspector, claz, identifier);
        }
        if (!executor.isAlive()) {
            executor = new BooleanPropertyExecutor(log, introspector, claz, identifier);
        }
        /*
         * and idem on an array
         */
        if (!executor.isAlive() && obj.getClass().isArray()) {
            executor = new BooleanPropertyExecutor(log, introspector, ArrayListWrapper.class, identifier, true);
        }
        return (executor.isAlive()) ? new VelGetterImpl(executor) : null;
    }

    /**
     * Property setter
     * @param obj
     * @param identifier
     * @param arg
     * @param i
     * @return A Velocity Setter method.
     */
    @Override
    public VelPropertySet getPropertySet(Object obj, String identifier, Object arg, Info i) {
        if (obj == null) {
            return null;
        }
        Class<?> claz = obj.getClass();
        /*
         *  first try for a setFoo() type of property
         *  (also setfoo() )
         */
        SetExecutor executor = new SetPropertyExecutor(log, introspector, claz, identifier, arg);
        /*
         * Let's see if we are a map...
         */
        if (!executor.isAlive()) {
            executor = new MapSetExecutor(log, claz, identifier);
        }
        if (!executor.isAlive()) {
            executor = new PutExecutor(log, introspector, claz, arg, identifier);
        }
        return (executor.isAlive()) ? new VelSetterImpl(executor) : null;
    }

    /**
     *  Implementation of VelMethod
     */
    public static class VelMethodImpl implements VelMethod {

        final Method method;

        Boolean isVarArg;

        boolean wrapArray;

        Converter<?>[] converters;

        /**
         * @param m
         */
        public VelMethodImpl(Method m) {
            this(m, false, null);
        }

        /**
         * @param method
         * @param wrapArray
         * @since 1.6
         */
        public VelMethodImpl(Method method, boolean wrapArray) {
            this(method, wrapArray, null);
        }

        /**
         * @param method
         * @param wrapArray
         * @param converters
         * @since 2.0
         */
        public VelMethodImpl(Method method, boolean wrapArray, Converter<?>[] converters) {
            this.method = method;
            this.wrapArray = wrapArray;
            this.converters = converters;
        }

        private VelMethodImpl() {
            method = null;
        }

        /**
         * @param o
         * @param actual
         * @return invocation result
         * @see VelMethod#invoke(java.lang.Object, java.lang.Object[])
         */
        @Override
        public Object invoke(Object o, Object[] actual) throws IllegalAccessException, InvocationTargetException {
            // if we're pretending an array is a list...
            if (wrapArray) {
                o = new ArrayListWrapper(o);
            }
            if (isVarArg()) {
                Class<?>[] formal = method.getParameterTypes();
                int index = formal.length - 1;
                if (actual.length >= index) {
                    Class<?> type = formal[index].getComponentType();
                    actual = handleVarArg(type, index, actual);
                }
            }
            if (converters != null) {
                // some converters may throw an ArithmeticException
                // which we want to wrap into an IllegalArgumentException
                try {

                } catch (ArithmeticException ae) {
                    throw new IllegalArgumentException(ae);
                }
            }
            // call extension point invocation
            return doInvoke(o, actual);
        }

        /**
         * Offers an extension point for subclasses (in alternate Uberspects)
         * to alter the invocation after any array wrapping or varargs handling
         * has already been completed.
         * @param o target object
         * @param actual arguments
         * @return invocation result
         * @throws IllegalAccessException
         * @throws InvocationTargetException
         * @since 1.6
         */
        protected Object doInvoke(Object o, Object[] actual) throws IllegalAccessException, InvocationTargetException {
            return method.invoke(o, actual);
        }

        /**
         * @return true if this method can accept a variable number of arguments
         * @since 1.6
         */
        public boolean isVarArg() {
            if (isVarArg == null) {
                Class<?>[] formal = method.getParameterTypes();
                if (formal.length == 0) {
                    this.isVarArg = Boolean.FALSE;
                } else {
                    Class<?> last = formal[formal.length - 1];
                    // if the last arg is an array, then
                    // we consider this a varargs method
                    this.isVarArg = last.isArray();
                }
            }
            return isVarArg;
        }

        /**
         * @param type The vararg class type (aka component type
         *             of the expected array arg)
         * @param index The index of the vararg in the method declaration
         *              (This will always be one less than the number of
         *               expected arguments.)
         * @param actual The actual parameters being passed to this method
         * @return The actual parameters adjusted for the varargs in order
         *          to fit the method declaration.
         */
        private Object[] handleVarArg(final Class<?> type, final int index, Object[] actual) {
            // if no values are being passed into the vararg
            if (actual.length == index) {
                // copy existing args to new array
                Object[] newActual = new Object[actual.length + 1];
                System.arraycopy(actual, 0, newActual, 0, actual.length);
                // create an empty array of the expected type
                newActual[index] = Array.newInstance(type, 0);
                actual = newActual;
            } else // if one value is being passed into the vararg
            if (actual.length == index + 1 && actual[index] != null) {
                // make sure the last arg is an array of the expected type
                Class<?> argClass = actual[index].getClass();
                if (!argClass.isArray() && IntrospectionUtils.isMethodInvocationConvertible(type, argClass, false)) {
                    // create a 1-length array to hold and replace the last param
                    Object lastActual = Array.newInstance(type, 1);
                    Array.set(lastActual, 0, actual[index]);
                    actual[index] = lastActual;
                }
            } else // if multiple values are being passed into the vararg
            if (actual.length > index + 1) {
                // put the last and extra actual in an array of the expected type
                int size = actual.length - index;
                Object lastActual = Array.newInstance(type, size);
                for (int i = 0; i < size; i++) {
                    Array.set(lastActual, i, actual[index + i]);
                }
                // put all into a new actual array of the appropriate size
                Object[] newActual = new Object[index + 1];
                System.arraycopy(actual, 0, newActual, 0, index);
                newActual[index] = lastActual;
                // replace the old actual array
                actual = newActual;
            }
            return actual;
        }

        /**
         * @see org.apache.velocity.util.introspection.VelMethod#isCacheable()
         */
        @Override
        public boolean isCacheable() {
            return true;
        }

        /**
         * @see org.apache.velocity.util.introspection.VelMethod#getMethodName()
         */
        @Override
        public String getMethodName() {
            return method.getName();
        }

        /**
         * @see org.apache.velocity.util.introspection.VelMethod#getMethod()
         */
        @Override
        public Method getMethod() {
            return method;
        }

        /**
         * @see org.apache.velocity.util.introspection.VelMethod#getReturnType()
         */
        @Override
        public Class<?> getReturnType() {
            return method.getReturnType();
        }
    }

    public static class VelGetterImpl implements VelPropertyGet {

        final AbstractExecutor getExecutor;

        /**
         * @param exec
         */
        public VelGetterImpl(AbstractExecutor exec) {
            getExecutor = exec;
        }

        private VelGetterImpl() {
            getExecutor = null;
        }

        /**
         * @see org.apache.velocity.util.introspection.VelPropertyGet#invoke(java.lang.Object)
         */
        @Override
        public Object invoke(Object o) throws IllegalAccessException, InvocationTargetException {
            return getExecutor.execute(o);
        }

        /**
         * @see org.apache.velocity.util.introspection.VelPropertyGet#isCacheable()
         */
        @Override
        public boolean isCacheable() {
            return true;
        }

        /**
         * @see org.apache.velocity.util.introspection.VelPropertyGet#getMethodName()
         */
        @Override
        public String getMethodName() {
            return getExecutor.isAlive() ? getExecutor.getMethod().getName() : null;
        }
    }

    public static class VelSetterImpl implements VelPropertySet {

        private final SetExecutor setExecutor;

        /**
         * @param setExecutor
         */
        public VelSetterImpl(final SetExecutor setExecutor) {
            this.setExecutor = setExecutor;
        }

        private VelSetterImpl() {
            setExecutor = null;
        }

        /**
         * Invoke the found Set Executor.
         *
         * @param o is the Object to invoke it on.
         * @param value in the Value to set.
         * @return The resulting Object.
         */
        @Override
        public Object invoke(final Object o, final Object value) throws IllegalAccessException, InvocationTargetException {
            return setExecutor.execute(o, value);
        }

        /**
         * @see org.apache.velocity.util.introspection.VelPropertySet#isCacheable()
         */
        @Override
        public boolean isCacheable() {
            return true;
        }

        /**
         * @see org.apache.velocity.util.introspection.VelPropertySet#getMethodName()
         */
        @Override
        public String getMethodName() {
            return setExecutor.isAlive() ? setExecutor.getMethod().getName() : null;
        }
    }
}