text:
package com.he5ed.lib.cloudprovider.apis;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.he5ed.lib.cloudprovider.CloudProvider;
import com.he5ed.lib.cloudprovider.R;
import com.he5ed.lib.cloudprovider.auth.Authenticator;
import com.he5ed.lib.cloudprovider.exceptions.RequestFailException;
import com.he5ed.lib.cloudprovider.models.CFile;
import com.he5ed.lib.cloudprovider.models.CFolder;
import com.he5ed.lib.cloudprovider.models.User;
import com.he5ed.lib.cloudprovider.utils.FilesUtils;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okio.BufferedSink;

/**
 * Microsoft OneDrive cloud service API implementation
 *
 * @hide
 */
public class OneDriveApi extends BaseApi {

    // API server constant values
    public static final String AUTH_URL = "https://login.live.com/oauth20_authorize.srf";
    public static final String TOKEN_URL = "https://login.live.com/oauth20_token.srf";
    public static final String REVOKE_URL = "https://login.live.com/oauth20_logout.srf";
    public static final String LIVE_API_URL = "https://apis.live.net/v5.0";

    public static final String API_BASE_URL = "https://api.onedrive.com/v1.0";

    public static final String ROOT_ID = "root";
    public static final String ROOT_PATH = "/drive/root:";

    /**
     * Must override with the correct values
     */
    public static String CLIENT_ID = null;
    public static String CLIENT_SECRET = null;
    public static String REDIRECT_URL = null;

    // enable API
    public static boolean ENABLE_API = false;

    // class constant values
    public static final String NAME = "Microsoft OneDrive";
    public static final int ICON_RESOURCE = R.drawable.ic_onedrive_color_24dp;
    public static final String TAG = "OneDriveApi";
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    /**
     * Build authorization url base on type of cloud service
     *
     * @return Uri
     */
    public static Uri buildAuthUri(String stateString) {
        Uri uri = Uri.parse(AUTH_URL);
        return uri.buildUpon()
                .appendQueryParameter("response_type", "code")
                .appendQueryParameter("client_id", CLIENT_ID)
                .appendQueryParameter("redirect_uri", REDIRECT_URL)
                .appendQueryParameter("state", stateString)
                .appendQueryParameter("scope", "wl.emails wl.offline_access onedrive.readwrite")
                .build();
    }

    /**
     * Get parameters to be passed to Volley request to get access token
     *
     * @param authCode code from authorization process
     * @return RequestBody
     */
    public static RequestBody getAccessTokenBody(String authCode) {
        return new FormEncodingBuilder()
                .addEncoded("grant_type", "authorization_code")
                .addEncoded("code", authCode)
                .addEncoded("client_id", CLIENT_ID)
                .addEncoded("client_secret", CLIENT_SECRET)
                .addEncoded("redirect_uri", REDIRECT_URL)
                .build();
    }

    /**
     * Build form body to be passed to access token
     *
     * @param refreshToken code from authorization process
     * @return RequestBody
     */
    public static RequestBody getRefreshTokenBody(String refreshToken) {
        return new FormEncodingBuilder()
                .addEncoded("grant_type", "refresh_token")
                .addEncoded("refresh_token", refreshToken)
                .addEncoded("client_id", CLIENT_ID)
                .addEncoded("client_secret", CLIENT_SECRET)
                .addEncoded("redirect_uri", REDIRECT_URL)
                .build();
    }

    /**
     * Extract access token from the JSONObject
     *
     * @param jsonObject JSONObject that contain access token
     * @return Map
     * @throws JSONException
     */
    public static Map<String, String> extractAccessToken(JSONObject jsonObject) throws JSONException {
        Map<String, String> map = new HashMap<>();
        map.put(Authenticator.KEY_ACCESS_TOKEN, jsonObject.getString("access_token"));
        map.put(Authenticator.KEY_EXPIRY, String.valueOf(jsonObject.getLong("expires_in")));
        map.put(Authenticator.KEY_REFRESH_TOKEN, jsonObject.getString("refresh_token"));
        return map;
    }

    /**
     * Get current user information uri
     *
     * @return Uri
     */
    public static Uri getUserInfoUri() {
        Uri uri = Uri.parse(LIVE_API_URL);
        return uri.buildUpon().appendEncodedPath("me").build();
    }

    /**
     * Create request to get user information
     *
     * @param accessToken access token for authorization
     * @return Request
     */
    public static Request getUserInfoRequest(String accessToken) {
        return new Request.Builder()
                .url(getUserInfoUri().toString())
                .addHeader("Authorization", String.format("Bearer %s", accessToken))
                .build();
    }

    /**
     * Extract user information from the JSONObject
     *
     * @param jsonObject JSONObject that contain user information
     * @return User
     * @throws JSONException
     */
    public static User extractUser(JSONObject jsonObject) throws JSONException {
        User user = new User();
        user.id = jsonObject.getString("id");
        user.name = jsonObject.getString("name");
        user.displayName = jsonObject.getString("name");
        JSONObject emails = jsonObject.getJSONObject("emails");
        user.email = emails.getString("account");

        return user;
    }

    /**
     * Build folder from JSONObject
     *
     * @param jsonObject from http response
     * @return CFolder
     */
    public static CFolder buildFolder(JSONObject jsonObject) {
        Map<String, Object> map = new HashMap<>();
        try {
            map.put(CFolder.ID, jsonObject.getString("id"));
            map.put(CFolder.NAME, jsonObject.getString("name"));
            map.put(CFolder.DATE_FORMAT, "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            if (jsonObject.has("createdDateTime"))
                map.put(CFolder.CREATED, jsonObject.getString("createdDateTime"));
            if (jsonObject.has("lastModifiedDateTime"))
                map.put(CFolder.MODIFIED, jsonObject.getString("lastModifiedDateTime"));
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }

        return new CFolder(map);
    }

    /**
     * Build file from JSONObject
     *
     * @param jsonObject from http response
     * @return CFolder
     */
    public static CFile buildFile(JSONObject jsonObject) {
        Map<String, Object> map = new HashMap<>();
        try {
            map.put(CFolder.ID, jsonObject.getString("id"));
            map.put(CFolder.NAME, jsonObject.getString("name"));
            map.put(CFolder.DATE_FORMAT, "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            if (jsonObject.has("createdDateTime"))
                map.put(CFolder.CREATED, jsonObject.getString("createdDateTime"));
            if (jsonObject.has("lastModifiedDateTime"))
                map.put(CFolder.MODIFIED, jsonObject.getString("lastModifiedDateTime"));
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }

        return new CFile(map);
    }

    private Context mContext;
    private CloudProvider mCloudProvider;
    private Account mAccount;
    private BaseApi.OnPrepareListener mPrepareListener;
    private OkHttpClient mHttpClient;
    private String mAccessToken;

    /**
     * Constructor for OneDrive API
     *
     * @param account to be used must be OneDrive cloud type
     */
    public OneDriveApi(Context context, Account account) {
        mContext = context;
        mAccount = account;
        mCloudProvider = CloudProvider.getInstance(mContext);
        mHttpClient = new OkHttpClient();
    }

    @Override
    public synchronized void prepareApi(BaseApi.OnPrepareListener prepareListener) {
        mPrepareListener = prepareListener;

        AccountManager.get(mContext).getAuthToken(mAccount, CloudProvider.AUTH_TYPE, false,
                new AccountManagerCallback<Bundle>() {
                    @Override
                    public void run(AccountManagerFuture<Bundle> future) {
                        try {
                            mAccessToken = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);

                            validateAccessToken();
                        } catch (OperationCanceledException e) {
                            e.printStackTrace();
                            Log.e(TAG, e.getMessage());
                            if (mPrepareListener != null)
                                mPrepareListener.onPrepareFail(e);
                        } catch (IOException e) {
                            e.printStackTrace();
                            Log.e(TAG, e.getMessage());
                            if (mPrepareListener != null)
                                mPrepareListener.onPrepareFail(e);
                        } catch (AuthenticatorException e) {
                            e.printStackTrace();
                            Log.e(TAG, e.getMessage());
                            if (mPrepareListener != null)
                                mPrepareListener.onPrepareFail(e);
                        }
                    }
                }, null);
    }

    /**
     * Ensure that the access token is still valid
     * Access token can be expired or revoked by user
     * Try to refresh the access token if it is expired
     */
    private void validateAccessToken() {
        Request request = getUserInfoRequest(mAccessToken);

        mHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                e.printStackTrace();
                if (mPrepareListener != null)
                    mPrepareListener.onPrepareFail(e);
                Log.e(TAG, e.getMessage());
            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful() && response.code() == 200) {
                    if (mPrepareListener != null)
                        mPrepareListener.onPrepareSuccessful();
                } else {
                    switch (response.code()) {
                        case 401:
                            // unauthorized
                            refreshAccessToken();
                            break;
                        default:
                            break;
                    }
                    Log.e(TAG, response.code() + ": " + response.body().string());
                }
            }
        });
    }

    /**
     * Try to get a fresh access token using the refresh token
     */
    private void refreshAccessToken() {
        final String refreshToken = mCloudProvider.getUserData(mAccount, Authenticator.KEY_REFRESH_TOKEN);
        if (!TextUtils.isEmpty(refreshToken)) {
            Request request = new Request.Builder()
                    .url(TOKEN_URL)
                    .post(getRefreshTokenBody(refreshToken))
                    .build();

            mHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    e.printStackTrace();
                    Log.e(TAG, e.getMessage());

                    resetAccount();
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    if (response.isSuccessful()) {
                        // convert string into json
                        try {
                            JSONObject jsonObject = new JSONObject(response.body().string());
                            Map<String, String> tokenInfo = extractAccessToken(jsonObject);
                            mCloudProvider.updateAccount(mAccount, tokenInfo);
                            mAccessToken = tokenInfo.get(Authenticator.KEY_ACCESS_TOKEN);
                            // validate again
                            validateAccessToken();
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Log.e(TAG, e.getMessage());
                        }
                    } else {
                        Log.e(TAG, response.code() + ": " + response.body().string());
                        resetAccount();
                    }

                }
            });
        } else {
            resetAccount();
        }
    }

    /**
     * Remove the staled account and add a new one
     */
    private void resetAccount() {
        logout(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {

            }
        });
        // use Authenticator to update account
        mCloudProvider.removeAccount(mAccount);
        mCloudProvider.addAccount(getClass().getCanonicalName(), (Activity) mContext);
    }

    @Override
    public void logout(@NonNull Callback callback) {
        RequestBody body = new FormEncodingBuilder()
                .add("client_id", CLIENT_ID)
                .add("client_secret", CLIENT_SECRET)
                .add("token", mAccessToken)
                .build();

        Request request = new Request.Builder()
                .url(REVOKE_URL)
                .post(body)
                .build();

        mHttpClient.newCall(request).enqueue(callback);
    }

    @Override
    public synchronized List<Object> exploreFolder(@NonNull CFolder folder, int offset) throws RequestFailException {
        if (TextUtils.isEmpty(mAccessToken)) {
            throw new RequestFailException("Access token not available");
        }

        List<Object> list = new ArrayList<>();

        Request request = new Request.Builder()
                .url(API_BASE_URL + "/drive/items/" + folder.getId() + "/children")
                .header("Authorization", String.format("Bearer %s", mAccessToken))
                .get()
                .build();

        try {
            Response response = mHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                JSONObject jsonObject = new JSONObject(response.body().string());
                JSONArray entries = jsonObject.getJSONArray("value");
                if (entries.length() > 0) {
                    list.addAll(createFilteredItemsList(entries, null));
                } else {
                    // return null if no item found
                    return null;
                }
                // pagination available
                if (jsonObject.has("@odata.nextLink")) {
                    list.addAll(exploreFolderContinue(jsonObject.getString("@odata.nextLink")));
                }
                return list;
            } else {
                throw new RequestFailException(response.message(), response.code());
            }
        } catch (JSONException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }
    }

    /**
     * Get continue folder items
     *
     * @param url for the next page of items
     * @return List that contains CFile and CFolder
     * @throws RequestFailException that content various error types
     */
    public synchronized List<Object> exploreFolderContinue(String url) throws RequestFailException {
        if (TextUtils.isEmpty(mAccessToken)) {
            throw new RequestFailException("Access token not available");
        }

        List<Object> list = new ArrayList<>();

        Request request = new Request.Builder()
                .url(url)
                .header("Authorization", String.format("Bearer %s", mAccessToken))
                .get()
                .build();

        try {
            Response response = mHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                JSONObject jsonObject = new JSONObject(response.body().string());
                JSONArray entries = jsonObject.getJSONArray("data");
                if (entries.length() > 0) {
                    list.addAll(createFilteredItemsList(entries, null));
                } else {
                    // return null if no item found
                    return null;
                }
                // pagination available
                if (jsonObject.has("@odata.nextLink")) {
                    list.addAll(exploreFolderContinue(jsonObject.getString("@odata.nextLink")));
                }
                return list;
            } else {
                throw new RequestFailException(response.message(), response.code());
            }
        } catch (JSONException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }
    }

    @Override
    public CFolder getRoot() {
        // create root folder manually
        CFolder root = new CFolder(null);
        root.setId(ROOT_ID);
        root.setPath(ROOT_PATH);
        root.setName(mContext.getString(R.string.home_folder_title));
        root.setRoot(true);
        return root;
    }

    @Override
    public CFolder getFolderInfo(@NonNull String folderId) throws RequestFailException {
        if (TextUtils.isEmpty(mAccessToken)) {
            throw new RequestFailException("Access token not available");
        }

        if (TextUtils.isEmpty(folderId)) return null;

        Request request = new Request.Builder()
                .url(API_BASE_URL + "/drive/items/" + folderId)
                .header("Authorization", String.format("Bearer %s", mAccessToken))
                .get()
                .build();

        try {
            Response response = mHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                // new file created
                JSONObject jsonObject = new JSONObject(response.body().string());
                return buildFolder(jsonObject);
            } else {
                throw new RequestFailException(response.message(), response.code());
            }
        } catch (JSONException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }
    }

    @Override
    public CFolder createFolder(@NonNull String name, @Nullable CFolder parent) throws RequestFailException {
        if (TextUtils.isEmpty(mAccessToken)) {
            throw new RequestFailException("Access token not available");
        }

        // create parameter as json
        final JSONObject params= new JSONObject();
        try {
            params.put("name", name);
            params.put("folder", new JSONObject());
            params.put("@name.conflictBehavior", "fail");
        } catch (JSONException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }

        RequestBody body = new RequestBody() {
            @Override
            public MediaType contentType() {
                return JSON;
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                sink.writeUtf8(params.toString());
            }
        };

        Request request = new Request.Builder()
                .url(API_BASE_URL + "/drive/items/" +
                        (parent != null ? parent.getId() : getRoot().getId()) + "/children")
                .header("Authorization", String.format("Bearer %s", mAccessToken))
                .post(body)
                .build();

        try {
            Response response = mHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                JSONObject jsonObject = new JSONObject(response.body().string());
                return buildFolder(jsonObject);
            } else {
                throw new RequestFailException(response.message(), response.code());
            }
        } catch (JSONException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }
    }

    @Override
    public CFolder renameFolder(@NonNull CFolder folder, String name) throws RequestFailException {
        if (TextUtils.isEmpty(mAccessToken)) {
            throw new RequestFailException("Access token not available");
        }

        // exit if root or same name
        if (folder.isRoot() || folder.getName().equals(name)) return folder;

        // create parameter as json
        final JSONObject params= new JSONObject();
        try {
            params.put("name", name);
        } catch (JSONException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }

        RequestBody body = new RequestBody() {
            @Override
            public MediaType contentType() {
                return JSON;
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                sink.writeUtf8(params.toString());
            }
        };

        Request request = new Request.Builder()
                .url(API_BASE_URL + "/drive/items/" + folder.getId())
                .header("Authorization", String.format("Bearer %s", mAccessToken))
                .patch(body)
                .build();

        try {
            Response response = mHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                // return folder object
                return buildFolder(new JSONObject(response.body().string()));
            } else {
                throw new RequestFailException(response.message(), response.code());
            }
        } catch (JSONException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }
    }

    @Override
    public CFolder moveFolder(@NonNull CFolder folder, @Nullable CFolder parent) throws RequestFailException {
        if (TextUtils.isEmpty(mAccessToken)) {
            throw new RequestFailException("Access token not available");
        }

        // exit if root or same name
        if (folder.isRoot() || parent != null && folder.getId().equals(parent.getId())) return folder;

        // create parameter as json
        final JSONObject params= new JSONObject();
        try {
            params.put("parentReference", new JSONObject()
                    .put("id", parent != null ? parent.getId() : getRoot().getId()));
        } catch (JSONException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }

        RequestBody body = new RequestBody() {
            @Override
            public MediaType contentType() {
                return JSON;
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                sink.writeUtf8(params.toString());
            }
        };

        Request request = new Request.Builder()
                .url(API_BASE_URL + "/drive/items/" + folder.getId())
                .header("Authorization", String.format("Bearer %s", mAccessToken))
                .patch(body)
                .build();

        try {
            Response response = mHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                // return folder object
                return buildFolder(new JSONObject(response.body().string()));
            } else {
                throw new RequestFailException(response.message(), response.code());
            }
        } catch (JSONException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }
    }

    @Override
    public void deleteFolder(@NonNull CFolder folder) throws RequestFailException {
        if (TextUtils.isEmpty(mAccessToken)) {
            throw new RequestFailException("Access token not available");
        }

        Request request = new Request.Builder()
                .url(API_BASE_URL + "/drive/items/" + folder.getId())
                .header("Authorization", String.format("Bearer %s", mAccessToken))
                .delete()
                .build();

        try {
            Response response = mHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                Log.d(TAG, "CFolder with the id: " + folder.getName() + " deleted");
            } else {
                throw new RequestFailException(response.message(), response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }
    }

    @Override
    public CFile getFileInfo(@NonNull String fileId) throws RequestFailException {
        if (TextUtils.isEmpty(mAccessToken)) {
            throw new RequestFailException("Access token not available");
        }

        if (TextUtils.isEmpty(fileId)) return null;

        Request request = new Request.Builder()
                .url(API_BASE_URL + "/drive/items/" + fileId)
                .header("Authorization", String.format("Bearer %s", mAccessToken))
                .get()
                .build();

        try {
            Response response = mHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                // new file created
                JSONObject jsonObject = new JSONObject(response.body().string());
                return buildFile(jsonObject);
            } else {
                throw new RequestFailException(response.message(), response.code());
            }
        } catch (JSONException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }
    }

    @Override
    public CFile uploadFile(@NonNull final File file, @Nullable CFolder parent) throws RequestFailException {
        if (TextUtils.isEmpty(mAccessToken)) {
            throw new RequestFailException("Access token not available");
        }

        Uri uri = Uri.parse(API_BASE_URL);
        String url = uri.buildUpon()
                .appendEncodedPath("drive/items/" +
                        (parent != null ? parent.getId() : getRoot().getId()) + "/children/" +
                        file.getName() + "/content")
                .appendQueryParameter("@name.conflictBehavior", "fail")
                .build()
                .toString();

        RequestBody fileBody = new RequestBody() {
            @Override
            public MediaType contentType() {
                return null;
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                // copy file into RequestBody
                FilesUtils.copyFile(new FileInputStream(file), sink.outputStream());
            }
        };

        Request request = new Request.Builder()
                .url(url)
                .header("Authorization", String.format("Bearer %s", mAccessToken))
                .put(fileBody)
                .build();

        try {
            Response response = mHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                // new file created
                JSONObject jsonObject = new JSONObject(response.body().string());
                return buildFile(jsonObject);
            } else {
                throw new RequestFailException(response.message(), response.code());
            }
        } catch (JSONException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }
    }

    @Override
    public CFile updateFile(@NonNull CFile file, final File content) throws RequestFailException {
        if (TextUtils.isEmpty(mAccessToken)) {
            throw new RequestFailException("Access token not available");
        }

        Uri uri = Uri.parse(API_BASE_URL);
        String url = uri.buildUpon()
                .appendEncodedPath("drive/items/" + file.getId() + "/content")
                .appendQueryParameter("@name.conflictBehavior", "replace")
                .build()
                .toString();

        RequestBody fileBody = new RequestBody() {
            @Override
            public MediaType contentType() {
                return null;
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                // copy file into RequestBody
                FilesUtils.copyFile(new FileInputStream(content), sink.outputStream());
            }
        };

        Request request = new Request.Builder()
                .url(url)
                .header("Authorization", String.format("Bearer %s", mAccessToken))
                .put(fileBody)
                .build();

        try {
            Response response = mHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                // new file created
                JSONObject jsonObject = new JSONObject(response.body().string());
                return buildFile(jsonObject);
            } else {
                throw new RequestFailException(response.message(), response.code());
            }
        } catch (JSONException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }
    }

    @Override
    public CFile renameFile(@NonNull CFile file, String name) throws RequestFailException {
        if (TextUtils.isEmpty(mAccessToken)) {
            throw new RequestFailException("Access token not available");
        }

        // exist if same filename
        if (file.getName().equals(name)) return file;

        // create parameter as json
        final JSONObject params= new JSONObject();
        try {
            params.put("name", name);
        } catch (JSONException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }

        RequestBody body = new RequestBody() {
            @Override
            public MediaType contentType() {
                return JSON;
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                sink.writeUtf8(params.toString());
            }
        };

        Request request = new Request.Builder()
                .url(API_BASE_URL + "/drive/items/" + file.getId())
                .header("Authorization", String.format("Bearer %s", mAccessToken))
                .patch(body)
                .build();

        try {
            Response response = mHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                // return file object
                return buildFile(new JSONObject(response.body().string()));
            } else {
                throw new RequestFailException(response.message(), response.code());
            }
        } catch (JSONException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }
    }

    @Override
    public CFile moveFile(@NonNull CFile file, @Nullable CFolder folder) throws RequestFailException {
        if (TextUtils.isEmpty(mAccessToken)) {
            throw new RequestFailException("Access token not available");
        }

        // create parameter as json
        final JSONObject params= new JSONObject();
        try {
            params.put("parentReference", new JSONObject()
                    .put("id", folder != null ? folder.getId() : getRoot().getId()));
        } catch (JSONException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }

        RequestBody body = new RequestBody() {
            @Override
            public MediaType contentType() {
                return JSON;
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                sink.writeUtf8(params.toString());
            }
        };

        Request request = new Request.Builder()
                .url(API_BASE_URL + "/drive/items/" + file.getId())
                .header("Authorization", String.format("Bearer %s", mAccessToken))
                .patch(body)
                .build();

        try {
            Response response = mHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                // return file object
                return buildFile(new JSONObject(response.body().string()));
            } else {
                throw new RequestFailException(response.message(), response.code());
            }
        } catch (JSONException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }
    }

    @Override
    public File downloadFile(@NonNull CFile file, String filename) throws RequestFailException {
        if (TextUtils.isEmpty(mAccessToken)) {
            throw new RequestFailException("Access token not available");
        }

        // assign filename
        if (TextUtils.isEmpty(filename)) filename = file.getName();

        Request request = new Request.Builder()
                .url(API_BASE_URL + "/drive/items/" + file.getId() + "/content")
                .header("Authorization", String.format("Bearer %s", mAccessToken))
                .get()
                .build();

        try {
            Response response = mHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                switch (response.code()) {
                    case 200:
                        // redirect to url
                        return downloadFile(response.request(), filename);
                    case 302:
                        // redirect to url
                        return downloadFile(response.request(), filename);
                }
            } else {
                throw new RequestFailException(response.message(), response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }
        return null;
    }

    /**
     * Download file from redirect request
     *
     * @param request for redirect
     * @return File
     * @throws RequestFailException
     */
    public synchronized File downloadFile(@NonNull Request request, String filename) throws RequestFailException {
        try {
            File file = new File(mContext.getFilesDir(),
                    TextUtils.isEmpty(filename) ? "Untitled" : filename);

            Response response = mHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                FilesUtils.copyFile(response.body().byteStream(), new FileOutputStream(file));
            } else {
                throw new RequestFailException(response.message(), response.code());
            }
            return file;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }
    }

    @Override
    public void deleteFile(@NonNull CFile file) throws RequestFailException {
        if (TextUtils.isEmpty(mAccessToken)) {
            throw new RequestFailException("Access token not available");
        }

        Request request = new Request.Builder()
                .url(API_BASE_URL + "/drive/items/" + file.getId())
                .header("Authorization", String.format("Bearer %s", mAccessToken))
                .delete()
                .build();

        try {
            Response response = mHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                Log.d(TAG, "File with the id: " + file.getName() + " deleted");
            } else {
                throw new RequestFailException(response.message(), response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }
    }

    @Override
    public List<CFile> searchFile(@NonNull String keyword, CFolder folder) throws RequestFailException {
        // check cast for search result
        List<CFile> output = new ArrayList<>();
        for (Object item : search(keyword, folder)) {
            if (CFile.class.isAssignableFrom(item.getClass()))
                output.add(CFile.class.cast(item));
        }
        return output;
    }

    @Override
    public List<CFolder> searchFolder(@NonNull String keyword, CFolder folder) throws RequestFailException {
        // check cast for search result
        List<CFolder> output = new ArrayList<>();
        for (Object item : search(keyword, folder)) {
            if (CFolder.class.isAssignableFrom(item.getClass()))
                output.add(CFolder.class.cast(item));
        }
        return output;
    }

    @Override
    public List<Object> search(@NonNull String keyword, CFolder folder) throws RequestFailException {
        if (TextUtils.isEmpty(mAccessToken)) {
            throw new RequestFailException("Access token not available");
        }

        List<Object> list = new ArrayList<>();

        Uri uri = Uri.parse(API_BASE_URL);
        String url = uri.buildUpon()
                .appendEncodedPath("drive/items/" + folder.getId() + "/view.search")
                .appendQueryParameter("q", keyword)
                .build()
                .toString();

        Request request = new Request.Builder()
                .url(url)
                .header("Authorization", String.format("Bearer %s", mAccessToken))
                .get()
                .build();

        try {
            Response response = mHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                JSONObject jsonObject = new JSONObject(response.body().string());
                JSONArray entries = jsonObject.getJSONArray("value");
                if (entries.length() > 0) {
                    list.addAll(createFilteredItemsList(entries, folder));
                } else {
                    // return null if no item found
                    return null;
                }
                // pagination available
                if (jsonObject.has("@odata.nextLink")) {
                    list.addAll(searchContinue(jsonObject.getString("@odata.nextLink"), folder));
                }
                return list;
            } else {
                throw new RequestFailException(response.message(), response.code());
            }
        } catch (JSONException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }
    }

    /**
     * Get continue search items
     *
     * @param url for the next page of items
     * @param folder where the search is looking at
     * @return List that contains CFile and CFolder
     * @throws RequestFailException that content various error types
     */
    public synchronized List<Object> searchContinue(String url, CFolder folder) throws RequestFailException {
        if (TextUtils.isEmpty(mAccessToken)) {
            throw new RequestFailException("Access token not available");
        }

        List<Object> list = new ArrayList<>();

        Request request = new Request.Builder()
                .url(url)
                .header("Authorization", String.format("Bearer %s", mAccessToken))
                .get()
                .build();

        try {
            Response response = mHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                JSONObject jsonObject = new JSONObject(response.body().string());
                JSONArray entries = jsonObject.getJSONArray("data");
                if (entries.length() > 0) {
                    list.addAll(createFilteredItemsList(entries, folder));
                } else {
                    // return null if no item found
                    return null;
                }
                // pagination available
                if (jsonObject.has("@odata.nextLink")) {
                    list.addAll(searchContinue(jsonObject.getString("@odata.nextLink"), folder));
                }
                return list;
            } else {
                throw new RequestFailException(response.message(), response.code());
            }
        } catch (JSONException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }
    }

    @Override
    public File getThumbnail(@NonNull CFile file) throws RequestFailException {
        if (TextUtils.isEmpty(mAccessToken)) {
            throw new RequestFailException("Access token not available");
        }

        Request request = new Request.Builder()
                .url(API_BASE_URL + "/drive/items/" + file.getId() + "/thumbnails/0/medium/content")
                .header("Authorization", String.format("Bearer %s", mAccessToken))
                .get()
                .build();

        try {
            Response response = mHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                switch (response.code()) {
                    case 200:
                        // redirect to url
                        return downloadFile(response.request(), file.getId() + ".jpg");
                    case 302:
                        // redirect to url
                        return downloadFile(response.request(), file.getId() + ".jpg");
                }
            } else {
                throw new RequestFailException(response.message(), response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RequestFailException(e.getMessage());
        }
        return null;
    }

    /**
     * Create files or folders from the JSONArray search result
     *
     * @param jsonArray that contain files and folders information
     * @param parent folder that contain the items returned
     * @return list that contains CFile and CFolder that belong to the parent folder
     * @throws RequestFailException
     */
    private List<Object> createFilteredItemsList(JSONArray jsonArray, CFolder parent) throws RequestFailException {
        if (jsonArray == null || jsonArray.length() == 0) return null;

        List<Object> list = new ArrayList<>();

        for (int i = 0; i < jsonArray.length(); i++) {
            try {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                // filter parent
                JSONObject parentReference = jsonObject.getJSONObject("parentReference");
                if (parent != null &&
                        !parentReference.getString("id").equals(parent.getId()) &&
                        !parentReference.getString("path").equals(parent.getPath()))
                    continue;

                if (jsonObject.has("file")) {
                    list.add(buildFile(jsonObject));
                } else if (jsonObject.has("folder")) {
                    list.add(buildFolder(jsonObject));
                } else {
                    Log.e(TAG, "Unknown type found");
                }
            } catch (JSONException e) {
                e.printStackTrace();
                throw new RequestFailException(e.getMessage());
            }
        }

        return list;
    }
}


text:
'use strict';

var _ = require('lodash');
var webpack = require('webpack');
var path = require("path");
var argv = require('minimist')(process.argv.slice(2));

var DEBUG = !argv.release;

var AUTOPREFIXER_LOADER = 'autoprefixer-loader?{browsers:[' +
  '"Android 2.3", "Android >= 4", "Chrome >= 20", "Firefox >= 24", ' +
  '"Explorer >= 8", "iOS >= 6", "Opera >= 12", "Safari >= 6"]}';

var GLOBALS = {
  'process.env.NODE_ENV': DEBUG ? '"development"' : '"production"',
  '__DEV__': DEBUG
};

//
// Common configuration chunk to be used for both
// client-side (app.js) and server-side (server.js) bundles
// -----------------------------------------------------------------------------

var config = {
  output: {
    path: './build/',
    publicPath: './build/',
    sourcePrefix: '  '
  },

  cache: DEBUG,
  debug: DEBUG,
  devtool: DEBUG ? '#inline-source-map' : false,

  stats: {
    colors: true,
    reasons: DEBUG
  },

  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.ResolverPlugin(
            new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
        )
  ],

  resolve: {
    extensions: ['', '.webpack.js', '.web.js', '.js', '.jsx'],
    root: [path.join(__dirname, "bower_components")]
  },

  module: {
    preLoaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'eslint-loader'
      }
    ],

    loaders: [
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader!' + AUTOPREFIXER_LOADER
      },
      {
        test: /\.less$/,
        loader: 'style-loader!css-loader!' + AUTOPREFIXER_LOADER +
                '!less-loader'
      },
      {
        test: /\.gif/,
        loader: 'url-loader?limit=10000&mimetype=image/gif'
      },
      {
        test: /\.jpg/,
        loader: 'url-loader?limit=10000&mimetype=image/jpg'
      },
      {
        test: /\.png/,
        loader: 'url-loader?limit=10000&mimetype=image/png'
      },
      {
        test: /\.svg/,
        loader: 'url-loader?limit=10000&mimetype=image/svg+xml'
      },
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader?experimental'
      }
    ]
  }
};

//
// Configuration for the client-side bundle (app.js)
// -----------------------------------------------------------------------------

var appConfig = _.merge({}, config, {
  entry: './src/client/app.js',
  output: {
    filename: 'app.js'
  },
  plugins: config.plugins.concat([
      new webpack.DefinePlugin(_.merge(GLOBALS, {'__SERVER__': false}))
    ].concat(DEBUG ? [] : [
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.UglifyJsPlugin(),
      new webpack.optimize.AggressiveMergingPlugin()
    ])
  )
});

//
// Configuration for the server-side bundle (server.js)
// -----------------------------------------------------------------------------

var serverConfig = _.merge({}, config, {
  entry: './src/server/server.js',
  output: {
    filename: 'server.js',
    libraryTarget: 'commonjs2'
  },
  target: 'node',
  externals: /^[a-z\-0-9]+$/,
  node: {
    console: false,
    global: false,
    process: false,
    Buffer: false,
    __filename: false,
    __dirname: false
  },
  plugins: config.plugins.concat(
    new webpack.DefinePlugin(_.merge(GLOBALS, {'__SERVER__': true}))
  ),
  module: {
    loaders: config.module.loaders.map(function(loader) {
      // Remove style-loader
      return _.merge(loader, {
        loader: loader.loader = loader.loader.replace('style-loader!', '')
      });
    })
  }
});

// module.exports = [serverConfig];
module.exports = [appConfig, serverConfig];

redpajama_set_name: RedPajamaGithub


text:
#include <stdio.h>
#include <string.h>
#include "cbor.h"

#ifdef __GNUC__
#define UNUSED(x) __attribute__((__unused__)) x
#else
#define UNUSED(x) x
#endif

void usage() {
  printf("Usage: streaming_parser [input file]\n");
  exit(1);
}

/*
 * Illustrates how one might skim through a map (which is assumed to have
 * string keys and values only), looking for the value of a specific key
 *
 * Use the examples/data/map.cbor input to test this.
 */

const char* key = "a secret key";
bool key_found = false;

void find_string(void* UNUSED(_ctx), cbor_data buffer, size_t len) {
  if (key_found) {
    printf("Found the value: %.*s\n", (int)len, buffer);
    key_found = false;
  } else if (len == strlen(key)) {
    key_found = (memcmp(key, buffer, len) == 0);
  }
}

int main(int argc, char* argv[]) {
  if (argc != 2) usage();
  FILE* f = fopen(argv[1], "rb");
  if (f == NULL) usage();
  fseek(f, 0, SEEK_END);
  size_t length = (size_t)ftell(f);
  fseek(f, 0, SEEK_SET);
  unsigned char* buffer = malloc(length);
  fread(buffer, length, 1, f);

  struct cbor_callbacks callbacks = cbor_empty_callbacks;
  struct cbor_decoder_result decode_result;
  size_t bytes_read = 0;
  callbacks.string = find_string;
  while (bytes_read < length) {
    decode_result = cbor_stream_decode(buffer + bytes_read, length - bytes_read,
                                       &callbacks, NULL);
    bytes_read += decode_result.read;
  }

  free(buffer);
  fclose(f);
}


text:
package com.bullhornsdk.data;

import org.junit.Before;

import com.bullhornsdk.data.api.BullhornData;
import com.bullhornsdk.data.api.mock.MockBullhornData;

public class BaseTest {

	public TestEntities testEntities;

	public BullhornData bullhornData;

	@Before
	public void scaffoldTests() {
		this.bullhornData = new MockBullhornData();
		this.testEntities = new TestEntities();
	}

}


text:
package io.restassured.internal.path.xml;

import io.restassured.path.xml.element.Node;
import io.restassured.path.xml.element.NodeChildren;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

class NodeChildrenImpl extends NodeBase implements NodeChildren {
    public List<Node> nodeList = new ArrayList<>();
    public Object groovyNodes;

    @Override
    public Node get(int index) {
        return nodeList.get(index);
    }

    @Override
    public int size() {
        return nodeList.size();
    }

    @Override
    public boolean isEmpty() {
        return nodeList.isEmpty();
    }

    @Override
    public Iterator<String> iterator() {
        return new NodeListIterator(nodeList.iterator());
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        nodeList.forEach(it -> builder.append(it.toString()));
        return builder.toString();
    }

    @Override
    public Iterable<Node> nodeIterable() {
        return nodeList;
    }

    @Override
    public Object get(String name) {
        return get(name, nodeList.iterator(), false);
    }

    @Override
    public Object getPath(String path) {
        XMLAssertion xmlAssertion = new XMLAssertion();
        xmlAssertion.setKey(path);
        return xmlAssertion.getChildResultAsJavaObject(groovyNodes);
    }

    @Override
    public Iterator<Node> nodeIterator() {
        return nodeList.iterator();
    }

    @Override
    public List<Node> list() {
        return Collections.unmodifiableList(nodeList);
    }

    @Override
    public <T> List<T> getList(String name) {
        return get(name, nodeList.iterator(), true);
    }

    @Override
    public Object getBackingGroovyObject() {
        return groovyNodes;
    }

    @SuppressWarnings("unused")
    Object leftShift(Node node) {
        nodeList.add(node);
        return nodeList;
    }

    static class NodeListIterator implements Iterator<String> {
        private final Iterator<Node> iterator;

        public NodeListIterator(Iterator<Node> nodeList) {
            this.iterator = nodeList;
        }

        @Override
        public boolean hasNext() {
            return iterator.hasNext();
        }

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

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


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorAccent">#FF4081</color>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <string name="app_name">Japi</string>
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>


text:
// =================================================================================================
// ADOBE SYSTEMS INCORPORATED
// Copyright 2010 Adobe Systems Incorporated
// All Rights Reserved
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms
// of the Adobe license agreement accompanying it.
// =================================================================================================

#ifndef _IChunkBehavior_h_
#define _IChunkBehavior_h_

#include "public/include/XMP_Environment.h"	// ! This must be the first include.
#include "public/include/XMP_Const.h"
#include "public/include/XMP_IO.hpp"
#include <vector>

namespace IFF_RIFF
{

/**
	The IChunkBehavior is an interface that provides access to algorithm
	for the read and write process of IFF/RIFF formated streams.
	A file format specific instance based on this interface gets injected into
	the class ChunkController and offers format specific algorithm wherever
	the processing of a certain file format differs from the general specification
	of RIFF/IFF.
	That is e.g. the RF64 format where it is possible that the size value of the
	top level chunk doesn't represent the real size. Or AVI, where are special rules
	if the size of a chunk exceed the 4GB border.
*/

class IChunkContainer;
class Chunk;
struct ChunkIdentifier;
class ChunkPath;

class IChunkBehavior
{
public:
			 IChunkBehavior() : mMovablePaths(NULL) {}
	virtual ~IChunkBehavior() {};

	/**
	 * Set list of chunk paths of chunks that might be moved within the hierarchy
	 */
	inline void setMovablePaths( std::vector<ChunkPath>* paths )		{ mMovablePaths = paths; }

	/**
		Validate the passed in size value, identify the valid size if the passed in isn't valid
		and return the valid size.
		throw an exception if the passed in size isn't valid and there's no way to identify a
		valid size.

		@param	size	Size value
		@param	id		Identifier of chunk
		@param	tree	Chunk tree
		@param	stream	Stream handle

		@return		Valid size value.
	*/
	virtual	XMP_Uns64		getRealSize( const XMP_Uns64 size, const ChunkIdentifier& id, IChunkContainer& tree, XMP_IO* stream )	= 0;

	/**
		Return the maximum size of a single chunk, i.e. the maximum size of a top-level chunk.

		@return		Maximum size
	*/
	virtual XMP_Uns64		getMaxChunkSize() const																							= 0;

	/**
		Return true if the passed identifier is valid for top-level chunks of a certain format.

		@param	id			Chunk identifier
		@param	chunkNo		order number of top-level chunk
		@return				true, if passed id is a valid top-level chunk
	*/
	virtual	bool			isValidTopLevelChunk( const ChunkIdentifier& id, XMP_Uns32 chunkNo )											= 0;

	/**
		Fix the hierarchy of chunks depending ones based on size changes of one or more chunks
		and second based on format specific rules.
		Throw an exception if the hierarchy can't be fixed.

		@param	tree		Vector of root chunks.
	*/
	virtual	void			fixHierarchy( IChunkContainer& tree )																			= 0;

	/**
		Insert a new chunk into the hierarchy of chunks. The behavior needs to decide the position
		of the new chunk and has to do the insertion.

		@param	tree	Chunk tree
		@param	chunk	New chunk
	*/
	virtual	void			insertChunk( IChunkContainer& tree, Chunk& chunk )																= 0;

	/**
		Remove the chunk described by the passed ChunkPath.

		@param	tree	Chunk tree
		@param	path	Path to the chunk that needs to be removed

		@return			true if the chunk was removed and need to be deleted
	*/
	virtual	bool			removeChunk( IChunkContainer& tree, Chunk& chunk )																= 0;

protected:
		/**
		Create a FREE chunk.
		If the chunkSize is smaller than the header+type - size then create an annotation chunk.
		If the passed size is odd, then add a pad byte.

		@param chunkSize	Total size including header
		@return				New FREE chunk
	*/
	virtual Chunk*			createFREE( XMP_Uns64 chunkSize )																				= 0;

	/**
		Check if the passed chunk is a FREE chunk.
		(Could be also a small annotation chunk with zero bytes in its data)

		@param	chunk	A chunk

		@return			true if the passed chunk is a FREE chunk
	*/
	virtual XMP_Bool		isFREEChunk( const Chunk& chunk ) const																			= 0;

	/**
		Return the minimum size of a FREE chunk
	*/
	virtual XMP_Uns64		getMinFREESize( ) const
																																			= 0;
protected:
	/************************************************************************/
	/* END of Interface. The following are helper functions for all derived */
	/* Behavior Classes                                                     */
	/************************************************************************/

	/**
		Find a FREE chunk with the passed total size (including header). If the FREE chunk is found then
		take care of the fact that is has to be that large (or larger) then the minimum size of a FREE chunk.
		The method takes also into account that the passed size probably not includes a pad byte

		@param	tree			Parent tree
		@param	requiredSize	Required total size (including header)

		@return					Index of found FREE chunk
	*/
	XMP_Int32		findFREEChunk( const IChunkContainer& tree, XMP_Uns64 requiredSize );

	/**
		May we move a chunk of passed id/type

		@param	identifier		id and type of chunk
		@return					true if such a chunk might be moved within the tree
	*/
	bool			isMovable( const Chunk& chunk ) const;

	/**
		Validate recursively the offset values of all chunks.
		Throws an exception if there is any discrepancy with the calculated offset.

		@param	tree			(Sub-)tree of chunks
		@param	startOffset		First offset in the (sub-)tree
	*/
	void			validateOffsets( IChunkContainer& tree, XMP_Uns64 startOffset = 0 );

	/**
		Retrieve the free space at the passed position in the child list of the parent tree.
		If there's a FREE chunk then return it.

		@param outFreeBytes		On return it takes the number of free bytes
		@param tree				Parent tree
		@param index			Position in the child list of the parent tree

		@return					FREE chunk if available
	*/
	Chunk*			getFreeSpace( XMP_Int64& outFreeBytes, const IChunkContainer& tree, XMP_Uns32 index ) const ;

	/**
		Try to arrange all chunks of the source tree at their current location.
		The method looks for FREE chunk around or for size changes of the chunks around and try that space.
		If a chunk can't be arrange at its location it is moved to the end of the destination tree.

		@param srcTree		Tree that consists of the chunks that needs to be arranged
		@param destTree		Tree where chunks are added to if they can't be arranged

		@return				Index of last proceeded chunk
		*/
	void			arrangeChunksInPlace( IChunkContainer& srcTree, IChunkContainer& destTree );

	/**
		This method proceeds the list of Chunks of the source tree in the passed range and looks for FREE chunks
		in the destination tree to move the source chunks to.
		Source tree and destination tree could be one and the same but it's not required. If both trees are the
		same then it's not allowed to cross source and destination ranges.

		@param srcTree		Tree that consists of the chunks that needs to be arranged
		@param destTree		Tree where the method looks for FREE chunks
		@param srcStart		Start index within the source tree
		@param srcEnd		End index within the source tree (if booth, srcStart and srcEnd are zero then the complete list
							of the source tree is proceeded)
		@param destStart	Start index within the destination tree
		@param destEnd		End index within the destination tree (if booth, destStart and destEnd are zero then the complete list
							of the destination tree is proceeded)
	*/
	void	 		arrangeChunksInTree( IChunkContainer& srcTree, IChunkContainer& destTree );

	/**
		Try to merge existing FREE chunks at the passed position in the child list
		of the passed parent tree.
		The algorithm looks at the position, before the position and after the position.

		@param tree			Parent tree
		@param index		Position in the child list of the parent tree

		@return				FREE chunk if available at the passed position (in case of a merge
							the merged FREE chunk)
	*/
	Chunk*			mergeFreeChunks( IChunkContainer& tree, XMP_Uns32 index );

	/**
		Move a range of chunks from one container to another starting at the start index up to the
		end of the srcTree.

		@param srcTree		Source container
		@param destTree		Destination container
		@param start		Start index of source container
	 */
	void			moveChunks( IChunkContainer& srcTree, IChunkContainer& destTree, XMP_Uns32 start );

private:
	std::vector<ChunkPath>*	 mMovablePaths;
};

} // IChunkBehavior

#endif


text:
package joptsimple;

import java.util.List;
import java.util.Optional;

/**
 * Describes options that an option parser recognizes.
 *
 *
Instances of this interface are returned by the "fluent interface" methods to allow retrieval of option arguments
 * in a type-safe manner.  Here's an example:

 *
 *

 *     OptionParser parser = new OptionParser();
 *     OptionSpec<Integer> count =
 *         parser.accepts( "count" ).withRequiredArg().ofType( Integer.class );
 *     OptionSet options = parser.parse( "--count", "2" );
 *     assert options.has( count );
 *     int countValue = options.valueOf( count );
 *     assert countValue == count.value( options );
 *     List<Integer> countValues = options.valuesOf( count );
 *     assert countValues.equals( count.values( options ) );
 *

 *
 * @param <V> represents the type of the arguments this option accepts
 * @author Paul Holser
 */
public interface OptionSpec<V> {
    /**
     * Gives any arguments associated with the given option in the given set of detected options.
     *
     *
Specifying a {@linkplain ArgumentAcceptingOptionSpec#defaultsTo(Object, Object[]) default argument value}
     * for this option will cause this method to return that default value even if this option was not detected on the
     * command line, or if this option can take an optional argument but did not have one on the command line.

     *
     * @param detectedOptions the detected options to search in
     * @return the arguments associated with this option; an empty list if no such arguments are present, or if this
     * option was not detected
     * @throws OptionException if there is a problem converting this option's arguments to the desired type; for
     * example, if the type does not implement a correct conversion constructor or method
     * @throws NullPointerException if {@code detectedOptions} is {@code null}
     * @see OptionSet#valuesOf(OptionSpec)
     */
    List<V> values( OptionSet detectedOptions );

    /**
     * Gives the argument associated with the given option in the given set of detected options.
     *
     *
Specifying a {@linkplain ArgumentAcceptingOptionSpec#defaultsTo(Object, Object[]) default argument value}
     * for this option will cause this method to return that default value even if this option was not detected on the
     * command line, or if this option can take an optional argument but did not have one on the command line.

     *
     * @param detectedOptions the detected options to search in
     * @return the argument of the this option; {@code null} if no argument is present, or that option was not detected
     * @throws OptionException if more than one argument was detected for the option
     * @throws NullPointerException if {@code detectedOptions} is {@code null}
     * @throws ClassCastException if the arguments of this option are not of the expected type
     * @see OptionSet#valueOf(OptionSpec)
     */
    V value( OptionSet detectedOptions );

    /**
     * Gives the argument associated with the given option in the given set of detected options
     * as an {@link Optional}.
     *
     *
Specifying a {@linkplain ArgumentAcceptingOptionSpec#defaultsTo(Object, Object[]) default argument value}
     * for this option will cause this method to return that default value even if this option was not detected on the
     * command line, or if this option can take an optional argument but did not have one on the command line.

     *
     * @param detectedOptions the detected options to search in
     * @return the argument of the this option as an {@code Optional}
     * @throws OptionException if more than one argument was detected for the option
     * @throws NullPointerException if {@code detectedOptions} is {@code null}
     * @throws ClassCastException if the arguments of this option are not of the expected type
     * @see OptionSet#valueOf(OptionSpec)
     */
    default Optional<V> valueOptional( OptionSet detectedOptions ) {
        return Optional.ofNullable( value( detectedOptions ) );
    }

    /**
     * @return the string representations of this option
     */
    List<String> options();

    /**
     * Tells whether this option is designated as a "help" option. The presence of a "help" option on a command line
     * means that missing "required" options will not cause parsing to fail.
     *
     * @return whether this option is designated as a "help" option
     */
    boolean isForHelp();
}


text:
<?xml version="1.0"?>

<alvisnlp-doc author="Robert Bossy" date="2012-04-30" target="fr.inra.maiage.bibliome.alvisnlp.bibliomefactory.converters.SourceStreamParamConverter">
  <synopsis>

Converts into a data source.

  </synopsis>

  <converter-doc>
    <string-conversion>

The data source takes either the form of a file/directory path, or an URL. The following protocols are recognized:

file: the data is in the specified regular file path;

dir: the data is in several files in the specified directory path, if the specified path is a regular file the it behaves like file;

stream: the data comes from the AlvisNLP standard input, the host part of the URI must be "stdin" (stream://stdin);

resource: the data is embedded with the AlvisNLP distribution, the host and directory part of the URL specifies the resource to be used: each module should document which suitable resources are available;

http, https, ftp ...: the data is at the specified URL, AlvisNLP will fetch the data across the net.

      If an absolute or relative path is specified, then dir is assumed.
      Relative paths are relative to the current working directory.

    </string-conversion>

    <xml-conversion>

	<xverb><param value="URL"/></xverb>
	or
	<xverb><param file="URL"/></xverb>
	or
	<xverb><param path="URL"/></xverb>
	or
	<xverb><param url="URL"/></xverb>
	or
	<xverb><param href="URL"/></xverb>
	or
	<xverb><param dir="URL"/></xverb>
	or
	<xverb><param resource="URL"/></xverb>
	or
	<xverb><param>URL</param></xverb>
	URL is converted as described in the string conversion.
	All different forms are equivalent; the name of the used attribute has no influence on the data source type.
	It is thus perfectly legal to write <xverb><param resource="dir:///path/to/dir"/></xverb>.
	Other attributes allow to specify the data source:

charset: specifies the character encoding of the data ("UTF-8" by default);

encoding: same as above;

filter: a regular expression that specifies which files to read for the dir scheme (no filter by default);

fullNameFilter: a boolean that specifies if the filter applies to the full name of the files in the directory (false by default: the filter applies to the file name);

wholeMatch: a boolean that specifies if the filter must match the entire name (or full name) of the file in the directory (false by default: the regular expression is searched within the file name);

recursive: a boolean that specifies if sub-directories should be read in the dir scheme (false by default);

compression: compression algorithm of the stream: none, gz or gzip (none by default);

If <xverb>param</xverb> has children elements, then each element will be converted as a data source. The resulting is the concatenation of all data sources.

    </xml-conversion>
  </converter-doc>
</alvisnlp-doc>


text:
package gov.nih.nci.cabig.caaers.web.admin;

import gov.nih.nci.cabig.caaers.dao.StudyDao;
import gov.nih.nci.cabig.caaers.dao.query.*;
import gov.nih.nci.cabig.caaers.domain.*;
import gov.nih.nci.cabig.caaers.domain.ajax.StudyAjaxableDomainObject;
import gov.nih.nci.cabig.caaers.domain.ajax.UserAjaxableDomainObject;
import gov.nih.nci.cabig.caaers.domain.repository.*;
import gov.nih.nci.cabig.caaers.tools.ObjectTools;
import gov.nih.nci.cabig.caaers.utils.DateUtils;
import gov.nih.nci.cabig.caaers.utils.ranking.RankBasedSorterUtils;
import gov.nih.nci.cabig.caaers.utils.ranking.Serializer;
import gov.nih.nci.cabig.caaers.web.AbstractAjaxFacade;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author Monish
 *
 */
public class UserAjaxFacade extends AbstractAjaxFacade {

	private static Class<?>[] CONTROLLERS = {EditUserController.class};
	private UserRepository userRepository;
	private OrganizationRepository organizationRepository;
	private StudyDao studyDao;
	private InvestigatorRepository investigatorRepository;
	private ResearchStaffRepository researchStaffRepository;
    private PersonRepository personRepository;
	private static final Log log = LogFactory.getLog(UserAjaxFacade.class);

	@Override
	public Class<?>[] controllers() {
		return CONTROLLERS;
	}

	public UserAjaxFacade(){

	}

	/**
	 * This method is invoked from user.jsp to populate the Organization AutoCompleter.
	 * @param text
	 * @return
	 */
    public List<Organization> restrictOrganization(String text) {
        List<Organization> orgs = organizationRepository.restrictBySubnames(new String[] { text });
        orgs = RankBasedSorterUtils.sort(orgs , text, new Serializer<Organization>(){
            public String serialize(Organization object) {
                return object.getFullName();
            }
        });
        return ObjectTools.reduceAll(orgs, "id", "name", "nciInstituteCode","externalId");
    }

    @SuppressWarnings("unchecked")
	public List<UserAjaxableDomainObject> getResults(HashMap searchCriteriaMap) {

    	List<UserAjaxableDomainObject> searchResults = new ArrayList<UserAjaxableDomainObject>();

/*
    	String firstName = (String)searchCriteriaMap.get("firstName");
    	String lastName = (String)searchCriteriaMap.get("lastName");
*/
    	String name = (String)searchCriteriaMap.get("name");
    	String userName = (String)searchCriteriaMap.get("userName");
    	String personType = (String)searchCriteriaMap.get("personType");
    	String personIdentifier = (String)searchCriteriaMap.get("personIdentifier");
    	String organization = (String)searchCriteriaMap.get("organization");

    	//Only Organization provided
    	if (StringUtils.isEmpty(name) && StringUtils.isEmpty(personIdentifier) && "Please Select".equals(personType) && StringUtils.isEmpty(userName) && !StringUtils.isEmpty(organization)) {
    		searchResults = getResearchStaffTable(searchCriteriaMap);
    		searchResults.addAll(getInvestigatorTable(searchCriteriaMap));
    		return searchResults;
    	}

    	//Only Person Identifier provided
    	if (StringUtils.isEmpty(name) && "Please Select".equals(personType) && StringUtils.isEmpty(userName) && StringUtils.isEmpty(organization) && !StringUtils.isEmpty(personIdentifier)) {
    		searchResults = getResearchStaffTable(searchCriteriaMap);
    		searchResults.addAll(getInvestigatorTable(searchCriteriaMap));
    		return searchResults;
    	}

        if ("ResearchStaff".equals(personType)) {
            return getResearchStaffTable(searchCriteriaMap);
        } else if ("Investigator".equals(personType)) {
            return getInvestigatorTable(searchCriteriaMap);
        } else {
            HashMap resultsMap = new HashMap<String,UserAjaxableDomainObject>();

    		searchResults = getResearchStaffTable(searchCriteriaMap);
    		searchResults.addAll(getInvestigatorTable(searchCriteriaMap));

            for (UserAjaxableDomainObject uado : searchResults) {
                if (StringUtils.isNotEmpty(uado.getUserName()) && !resultsMap.containsKey(uado.getUserName())) {
                    resultsMap.put(uado.getUserName(), uado);
                }
            }

            List<UserAjaxableDomainObject> csmResults = getUserTable(searchCriteriaMap);
            for (UserAjaxableDomainObject uado : csmResults) {
                if (resultsMap.containsKey(uado.getUserName())) {
                    //Do not add it to searchResults
                } else {
                    searchResults.add(uado);
                }
            }

            return searchResults;
    	}
    }

    /**
     * This method is invoked from the user_search.jsp to fetch csm users for the given search criteria
     * @param searchCriteriaMap
     * @return
     */
    @SuppressWarnings("unchecked")
	public List<UserAjaxableDomainObject> getUserTable(HashMap searchCriteriaMap) {
    	List<UserAjaxableDomainObject> ajaxableUserList = new ArrayList<UserAjaxableDomainObject>();
        if(!StringUtils.equals("person", (String)searchCriteriaMap.get("linkType"))) {

            String name = (String)searchCriteriaMap.get("name");
            String fName = (String)searchCriteriaMap.get("firstName");
            String lName = (String)searchCriteriaMap.get("lastName");
            String uName = (String)searchCriteriaMap.get("userName");

            List<gov.nih.nci.security.authorization.domainobjects.User> csmUserList;
            if (StringUtils.isEmpty(name)) {
                csmUserList = userRepository.searchCsmUser(fName, lName, uName);
            } else {
                csmUserList = userRepository.searchCsmUser(name);
            }

            if(StringUtils.equals("user", (String)searchCriteriaMap.get("linkType"))){
                if(CollectionUtils.isNotEmpty(csmUserList)){
                   HashMap<String, gov.nih.nci.security.authorization.domainobjects.User> userMap = new HashMap<String, gov.nih.nci.security.authorization.domainobjects.User>();
                   for(gov.nih.nci.security.authorization.domainobjects.User csmUser : csmUserList){
                      userMap.put(csmUser.getLoginName(),csmUser);
                   }

                   ResearchStaffQuery rsQuery = new ResearchStaffQuery();
                   rsQuery.filterByExactLoginId(userMap.keySet().toArray(new String[]{}));
                   rsQuery.setFiltered(true);

                   List<ResearchStaff> staffs = personRepository.searchLocalResearchStaff(rsQuery);
                   for(ResearchStaff rs : staffs){
                       userMap.remove(rs.getLoginId());
                   }

                   InvestigatorQuery invQuery = new InvestigatorQuery();
                   invQuery.filterByExactLoginId(userMap.keySet().toArray(new String[]{}));
                   invQuery.setFiltered(true);
                   List<Investigator> investigators = personRepository.searchLocalInvestigator(invQuery);
                   for(Investigator inv : investigators){
                       userMap.remove(inv.getLoginId());
                   }
                   csmUserList = new ArrayList<gov.nih.nci.security.authorization.domainobjects.User>(userMap.values());
                }

            }

            UserAjaxableDomainObject ajaxableUser = null;
            for(gov.nih.nci.security.authorization.domainobjects.User csmUser : csmUserList){
                ajaxableUser = new UserAjaxableDomainObject();
                ajaxableUser.setId(csmUser.getUserId().intValue());
                ajaxableUser.setFirstName(csmUser.getFirstName());
                ajaxableUser.setLastName(csmUser.getLastName());
                ajaxableUser.setMiddleName("");
                ajaxableUser.setNumber("");
                ajaxableUser.setExternalId("");
                ajaxableUser.setUserName(csmUser.getLoginName());
                ajaxableUser.setEmailAddress(csmUser.getEmailId());
                ajaxableUser.setRecordType("CSM_RECORD");
                if(csmUser.getEndDate() != null){
                	ajaxableUser.setLocked(DateUtils.compareDate(csmUser.getEndDate(), Calendar.getInstance().getTime()) <= 0);
                }

                ajaxableUserList.add(ajaxableUser);
            }
        }
		return ajaxableUserList;
	}

    @SuppressWarnings("unchecked")
	public List<UserAjaxableDomainObject> getResearchStaffTable(HashMap searchCriteriaMap) {

        List<SiteResearchStaff> siteResearchStaffs = null;
        siteResearchStaffs = constructExecuteSiteResearchStaffQuery(searchCriteriaMap);
        Set<UserAjaxableDomainObject> set = new HashSet<UserAjaxableDomainObject>();

        if(!StringUtils.equals("user", (String) searchCriteriaMap.get("linkType"))){

            for (SiteResearchStaff srs : siteResearchStaffs) {
                UserAjaxableDomainObject rsado = new UserAjaxableDomainObject();
                rsado.setRecordType("RESEARCHSTAFF_RECORD");
                rsado.setFirstName(srs.getResearchStaff().getFirstName());
                rsado.setLastName(srs.getResearchStaff().getLastName());
                rsado.setMiddleName(srs.getResearchStaff().getMiddleName() != null ? srs.getResearchStaff().getMiddleName() : "");
                rsado.setEmailAddress(srs.getResearchStaff().getEmailAddress());
                rsado.setUserName(srs.getResearchStaff().getCaaersUser() != null ? srs.getResearchStaff().getCaaersUser().getLoginName() : "");

                StringBuffer sb = new StringBuffer("");
                for (SiteResearchStaff site : srs.getResearchStaff().getSiteResearchStaffs()) {
                    sb.append(site.getOrganization().getName() + " (" + site.getOrganization().getNciInstituteCode() + ")
");
                }
                rsado.setOrganization(sb.toString());

                rsado.setId(srs.getResearchStaff().getId());
                rsado.setNumber(srs.getResearchStaff().getNciIdentifier() != null ? srs.getResearchStaff().getNciIdentifier() : "");
                rsado.setExternalId(srs.getResearchStaff().getExternalId() != null ? srs.getResearchStaff().getExternalId().trim() : "");
                rsado.setActive(srs.isActive() ? "Active" : "Inactive");
//                if(srs.getResearchStaff().getCaaersUser() != null){
//                	User user = userRepository.getUserByLoginName(srs.getResearchStaff().getCaaersUser().getLoginName());
//                	if(user != null) rsado.setLocked(user.isLocked());
//                }
                set.add(rsado);
            }
        }

        return new ArrayList<UserAjaxableDomainObject>(set);
    }

    @SuppressWarnings({ "unchecked", "finally" })
    private List<SiteResearchStaff> constructExecuteSiteResearchStaffQuery(HashMap searchCriteriaMap) {

        List<SiteResearchStaff> siteResearchStaffs = new ArrayList<SiteResearchStaff>();
        SiteResearchStaffQuery query = new SiteResearchStaffQuery();
        query.setFiltered(true);

        String name = searchCriteriaMap.get("name").toString();

        if (StringUtils.isNotEmpty(name)) {
            if(StringUtils.isNotEmpty((String)searchCriteriaMap.get("name"))){
            	query.filterByName((String)searchCriteriaMap.get("name"));
            }
        } else {
            if(StringUtils.isNotEmpty((String)searchCriteriaMap.get("firstName"))){
            	query.filterByFirstName((String)searchCriteriaMap.get("firstName"));
            }
            if(StringUtils.isNotEmpty((String)searchCriteriaMap.get("lastName"))){
            	query.filterByLastName((String)searchCriteriaMap.get("lastName"));
            }
        }
        if(StringUtils.isNotEmpty((String)searchCriteriaMap.get("organization"))){
        	query.filterByOrganization((String)searchCriteriaMap.get("organization"));
        }
        if(StringUtils.isNotEmpty((String)searchCriteriaMap.get("personIdentifier"))){
        	query.filterByNciIdentifier((String)searchCriteriaMap.get("personIdentifier"));
        }
        if(StringUtils.isNotEmpty((String)searchCriteriaMap.get("userName"))){
        	query.filterByUserName((String)searchCriteriaMap.get("userName"));
        }
        if(searchCriteriaMap.get("linkType") != null) {
            query.excludeUsers();
        }

        try {
            siteResearchStaffs = researchStaffRepository.getSiteResearchStaff(query,searchCriteriaMap);
        }
        catch (Exception e) {
            throw new RuntimeException("Formatting Error", e);
        }
        finally {
            return siteResearchStaffs;
        }
    }

    @SuppressWarnings("unchecked")
	public List<UserAjaxableDomainObject> getInvestigatorTable(HashMap searchCriteriaMap) {

        List<Investigator> investigators = null;
        investigators = constructExecuteInvestigatorQuery(searchCriteriaMap);
        List<UserAjaxableDomainObject> inv = new ArrayList<UserAjaxableDomainObject>();
        if(!StringUtils.equals("user", (String) searchCriteriaMap.get("linkType"))){

            for (Investigator i : investigators) {
                UserAjaxableDomainObject invAdo = new UserAjaxableDomainObject();
                invAdo.setRecordType("INVESTIGATOR_RECORD");
                invAdo.setFirstName(i.getFirstName());
                invAdo.setLastName(i.getLastName());
                invAdo.setMiddleName(i.getMiddleName());
                invAdo.setMiddleName(i.getMiddleName() != null ? i.getMiddleName() : "");
                invAdo.setEmailAddress(i.getEmailAddress());
                invAdo.setUserName(i.getCaaersUser() != null ? i.getCaaersUser().getLoginName() : "");

                StringBuffer sb = new StringBuffer();
                for (SiteInvestigator si : i.getSiteInvestigators()) {
                    sb.append(si.getOrganization().getName() + "
");
                }
                invAdo.setOrganization(sb.toString());

                invAdo.setId(i.getId());
                invAdo.setActive(i.isActive() ? "Active" : "Inactive");
                if(i.getCaaersUser() != null){
                	User user = userRepository.getUserByLoginName(i.getCaaersUser().getLoginName());
                	if(user != null) invAdo.setLocked(user.isLocked());
                }
                invAdo.setNumber(i.getNciIdentifier() != null ? i.getNciIdentifier() : "");
                invAdo.setExternalId(i.getExternalId() != null ? i.getExternalId().trim() : "");
                inv.add(invAdo);
            }
        }
        return inv;
    }

    @SuppressWarnings({ "finally", "unchecked" })
    private List<Investigator> constructExecuteInvestigatorQuery(HashMap searchCriteriaMap) {

        List<Investigator> investigators = new ArrayList<Investigator>();
        InvestigatorQuery q = new InvestigatorQuery();
        q.setFiltered(true);

        String name = (String)searchCriteriaMap.get("name");

        if (StringUtils.isNotEmpty(name)) {
            if(StringUtils.isNotEmpty((String)searchCriteriaMap.get("name"))) {
                q.filterByName((String) searchCriteriaMap.get("name"));
            }
        } else {
            if(StringUtils.isNotEmpty((String)searchCriteriaMap.get("firstName"))) {
                q.filterByFirstName((String) searchCriteriaMap.get("firstName"));
            }
            if(StringUtils.isNotEmpty((String)searchCriteriaMap.get("lastName"))) {
                q.filterByLastName((String) searchCriteriaMap.get("lastName"));
            }
        }

        if(StringUtils.isNotEmpty((String) searchCriteriaMap.get("personIdentifier"))){
            q.filterByNciIdentifier((String) searchCriteriaMap.get("personIdentifier"));
        }

        if(StringUtils.isNotEmpty((String) searchCriteriaMap.get("organization"))){
            q.filterByOrganization((String) searchCriteriaMap.get("organization"));
        }

        if (StringUtils.isNotEmpty((String)searchCriteriaMap.get("userName"))) {
            q.filterByUserName((String) searchCriteriaMap.get("userName"));
        }

        if(searchCriteriaMap.get("linkType") != null) {
            q.excludeUsers();
        }

        try {
            investigators = investigatorRepository.searchInvestigator(q,searchCriteriaMap);
        } catch (Exception e) {
            throw new RuntimeException("Formatting Error", e);
        } finally {
            return investigators;
        }
    }

    /**
     * This method is invoked from user.jsp to populate the Study AutoCompleter.
     * @param text
     * @param organizationCodes
     * @return
     */
    public List<StudyAjaxableDomainObject> matchStudies(String text,String[] organizationCodes) {

    	 StudyQuery studyQuery = new StudyQuery();
    	 studyQuery.filterStudiesWithMatchingText(text);
    	 if (organizationCodes != null && organizationCodes.length > 0) {
    		 studyQuery.filterStudiesByOrganizations(organizationCodes);
    	 }
    	 List<Study> dbStudies = studyDao.find(studyQuery);
    	 List<StudyAjaxableDomainObject> studies = new ArrayList<StudyAjaxableDomainObject>();
    	 StudyAjaxableDomainObject studyAjaxableDomainObject = null;
    	 for(Study study : dbStudies){
    		 studyAjaxableDomainObject = new StudyAjaxableDomainObject();
    		 studyAjaxableDomainObject.setShortTitle(study.getShortTitle());
    		 studyAjaxableDomainObject.setPrimaryIdentifierValue(study.getIdentifierContaining(text));
    		 studyAjaxableDomainObject.setCcIdentifierValue(study.getCoordinatingCenterIdentifierValue());
    		 studies.add(studyAjaxableDomainObject);
    	 }
         studies = RankBasedSorterUtils.sort(studies , text, new Serializer<StudyAjaxableDomainObject>(){
             public String serialize(StudyAjaxableDomainObject object) {
                 return object.getDisplayName();
             }
         });
         return studies;
     }

    public void unlockUserPassword(){
        UserCommand command = (UserCommand) extractCommand();
        User user = command.getUser();
        getUserRepository().unlockUserPassword(user);
    }

    public boolean lockUnlockUser(String userName) {
        try {
        	User user = userRepository.getUserByLoginName(userName);
        	if (user == null) return false;

            if (user.isLocked()) {
                userRepository.unlockUser(user);
            } else {
            	 userRepository.lockUser(user);
            }

            userRepository.createOrUpdateUser(user, null);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public boolean activateUser(int personId, String userName, String action) {
        try {
            Person person = personRepository.getById(personId);
            if (person != null && person instanceof ResearchStaff) {
                ResearchStaff rs = (ResearchStaff)person;
                rs.setActive(!action.equals("Active"));
                personRepository.save(person);
            }
            if (person != null && person instanceof Investigator) {
                Investigator inv = (Investigator)person;
                inv.setActive(!action.equals("Active"));
                personRepository.save(inv);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

	public UserRepository getUserRepository() {
		return userRepository;
	}

	public void setUserRepository(UserRepository userRepository) {
		this.userRepository = userRepository;
	}

	public OrganizationRepository getOrganizationRepository() {
		return organizationRepository;
	}

	public void setOrganizationRepository(
			OrganizationRepository organizationRepository) {
		this.organizationRepository = organizationRepository;
	}

	public StudyDao getStudyDao() {
		return studyDao;
	}

	public void setStudyDao(StudyDao studyDao) {
		this.studyDao = studyDao;
	}

	public void setInvestigatorRepository(
			InvestigatorRepository investigatorRepository) {
		this.investigatorRepository = investigatorRepository;
	}

	public void setResearchStaffRepository(
			ResearchStaffRepository researchStaffRepository) {
		this.researchStaffRepository = researchStaffRepository;
	}

    public PersonRepository getPersonRepository() {
        return personRepository;
    }

    public void setPersonRepository(PersonRepository personRepository) {
        this.personRepository = personRepository;
    }
}


text:
/*
 * position.h
 *
 *  Created on: Apr 15, 2016
 *      Author: astery
 */

#ifndef POSITION_H_
#define POSITION_H_

#include <stdbool.h>
#include "map_typedefs.h"

struct Position {
	int x;
	int y;
};

Position Position_NextToOrientation(Position *pos, Orientation orient);
Position Position_RelativeTo(Position *pos, int x, int y, Orientation orient);
bool Position_IsInMapBoundaries(Position *pos, Map *map);

#endif /* POSITION_H_ */


text:
#ifndef Py_PYPORT_H
#define Py_PYPORT_H

#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif

/* typedefs for some C9X-defined synonyms for integral types. */
#ifdef HAVE_LONG_LONG
#ifndef PY_LONG_LONG
#define PY_LONG_LONG long long
#if defined(LLONG_MAX)
/* If LLONG_MAX is defined in limits.h, use that. */
#define PY_LLONG_MIN LLONG_MIN
#define PY_LLONG_MAX LLONG_MAX
#define PY_ULLONG_MAX ULLONG_MAX
#elif defined(__LONG_LONG_MAX__)
/* Otherwise, if GCC has a builtin define, use that. */
#define PY_LLONG_MAX __LONG_LONG_MAX__
#define PY_LLONG_MIN (-PY_LLONG_MAX-1)
#define PY_ULLONG_MAX (__LONG_LONG_MAX__*2ULL + 1ULL)
#else
/* Otherwise, rely on two's complement. */
#define PY_ULLONG_MAX (~0ULL)
#define PY_LLONG_MAX  ((long long)(PY_ULLONG_MAX>>1))
#define PY_LLONG_MIN (-PY_LLONG_MAX-1)
#endif /* LLONG_MAX */
#endif
#endif /* HAVE_LONG_LONG */

/* Largest possible value of size_t.
   SIZE_MAX is part of C99, so it might be defined on some
   platforms. If it is not defined, (size_t)-1 is a portable
   definition for C89, due to the way signed->unsigned
   conversion is defined. */
#ifdef SIZE_MAX
#define PY_SIZE_MAX SIZE_MAX
#else
#define PY_SIZE_MAX ((size_t)-1)
#endif

/* uintptr_t is the C9X name for an unsigned integral type such that a
 * legitimate void* can be cast to uintptr_t and then back to void* again
 * without loss of information.  Similarly for intptr_t, wrt a signed
 * integral type.
 */
#ifdef HAVE_UINTPTR_T
typedef uintptr_t   Py_uintptr_t;
typedef intptr_t    Py_intptr_t;

#elif SIZEOF_VOID_P <= SIZEOF_INT
typedef unsigned int    Py_uintptr_t;
typedef int     Py_intptr_t;

#elif SIZEOF_VOID_P <= SIZEOF_LONG
typedef unsigned long   Py_uintptr_t;
typedef long        Py_intptr_t;

#elif defined(HAVE_LONG_LONG) && (SIZEOF_VOID_P <= SIZEOF_LONG_LONG)
typedef unsigned PY_LONG_LONG   Py_uintptr_t;
typedef PY_LONG_LONG        Py_intptr_t;

#else
#   error "Python needs a typedef for Py_uintptr_t in pyport.h."
#endif /* HAVE_UINTPTR_T */

/* Py_hash_t is the same size as a pointer. */
#define SIZEOF_PY_HASH_T SIZEOF_SIZE_T
typedef Py_ssize_t Py_hash_t;
/* Py_uhash_t is the unsigned equivalent needed to calculate numeric hash. */
#define SIZEOF_PY_UHASH_T SIZEOF_SIZE_T
typedef size_t Py_uhash_t;

#include <stdarg.h>

#ifdef __va_copy
#define Py_VA_COPY __va_copy
#else
#ifdef VA_LIST_IS_ARRAY
#define Py_VA_COPY(x, y) Py_MEMCPY((x), (y), sizeof(va_list))
#else
#define Py_VA_COPY(x, y) (x) = (y)
#endif
#endif

/*******************************
 * stat() and fstat() fiddling *
 *******************************/

/* We expect that stat and fstat exist on most systems.
 *  It's confirmed on Unix, Mac and Windows.
 *  If you don't have them, add
 *      #define DONT_HAVE_STAT
 * and/or
 *      #define DONT_HAVE_FSTAT
 * to your pyconfig.h. Python code beyond this should check HAVE_STAT and
 * HAVE_FSTAT instead.
 * Also
 *      #define HAVE_SYS_STAT_H
 * if <sys/stat.h> exists on your platform, and
 *      #define HAVE_STAT_H
 * if <stat.h> does.
 */
#ifndef DONT_HAVE_STAT
#define HAVE_STAT
#endif

#ifndef DONT_HAVE_FSTAT
#define HAVE_FSTAT
#endif

#ifdef RISCOS
#include <sys/types.h>
#include "unixstuff.h"
#endif

#ifdef HAVE_SYS_STAT_H
#if defined(PYOS_OS2) && defined(PYCC_GCC)
#include <sys/types.h>
#endif
#include <sys/stat.h>
#elif defined(HAVE_STAT_H)
#include <stat.h>
#else
#endif

#endif /* Py_PYPORT_H */


text:
#ifndef BASE_SET_UTIL_H
#define BASE_SET_UTIL_H

//
// set_synchronize
//
// Given two sets synchronize the 1st (current) set with the 2nd (future)
// one by invoking add or delete functors for values that are:
//   add - present in the 2nd set but not in the 1st;
//   delete - present in the 1st set but not in the 2nd;
//
// The add/delete functors are responsible for adding/deleting appropriate
// elements to/from the 1st set.
//
template <typename SetType, typename AddFunctor, typename DelFunctor>
void set_synchronize(SetType *set1, const SetType *set2,
                     AddFunctor add_fn, DelFunctor del_fn) {
    typename SetType::iterator it1 = set1->begin(), next1 = set1->begin();
    typename SetType::const_iterator it2 = set2->begin();
    while (it1 != set1->end() && it2 != set2->end()) {
        if (*it1 < *it2) {
            ++next1;
            del_fn(it1);
            it1 = next1;
        } else if (*it1 > *it2) {
            add_fn(it2);
            ++it2;
        } else {
            ++it1;
            ++it2;
        }
        next1 = it1;
    }
    for (next1 = it1; it1 != set1->end(); it1 = next1) {
        ++next1;
        del_fn(it1);
    }
    for (; it2 != set2->end(); ++it2) {
        add_fn(it2);
    }
}

#endif  // BASE_SET_UTIL_H


text:
#include "CDHCPKickUserEventHndl.h"
#include "CDHCPServer.h"
#include "BaseDefines.h"

CDHCPKickUserEventHndl::CDHCPKickUserEventHndl(CDHCPServer &server, const Sm_Kick_User* kickInfo)
    : m_server(server)
{
    ACE_DEBUG ((LM_DEBUG,"CDHCPKickUserEventHndl::CDHCPKickUserEventHndl\n"));
    ::memcpy(&m_kickInfo, kickInfo, sizeof(*kickInfo));
}

CDHCPKickUserEventHndl::~CDHCPKickUserEventHndl()
{
    ACE_DEBUG ((LM_DEBUG,"CDHCPKickUserEventHndl::~CDHCPKickUserEventHndl\n"));
}

void CDHCPKickUserEventHndl::Fire()
{
    ACE_DEBUG ((LM_DEBUG, "CDHCPKickUserEventHndl::Fire\n"));

    WORD64 sessionId = m_server.GetSessionID(&m_kickInfo);

    int retVal = m_server.RemoveSession(sessionId);
    if (retVal != 0)
    {
        ACE_DEBUG ((LM_ERROR, "DHCP server failed to remove session with id %#x.\n", sessionId));
    }
}