Example usage for java.util.concurrent FutureTask get

List of usage examples for java.util.concurrent FutureTask get

Introduction

In this page you can find the example usage for java.util.concurrent FutureTask get.

Prototype

public V get() throws InterruptedException, ExecutionException 

Source Link

Usage

From source file:com.bilibili.boxing.utils.CameraPickerHelper.java

/**
 * start system camera to take a picture
 *
 * @param activity      not null if fragment is null.
 * @param fragment      not null if activity is null.
 * @param subFolderPath a folder in external DCIM,must start with "/".
 *///ww  w .  j  a v  a 2s  .c o m
public void startCamera(final Activity activity, final Fragment fragment, final String subFolderPath) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || !takePhotoSecure(activity, fragment, subFolderPath)) {
        FutureTask<Boolean> task = BoxingExecutor.getInstance().runWorker(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                try {
                    // try...try...try
                    Camera camera = Camera.open();
                    camera.release();
                } catch (Exception e) {
                    BoxingLog.d("camera is not available.");
                    return false;
                }
                return true;
            }
        });
        try {
            if (task != null && task.get()) {
                startCameraIntent(activity, fragment, subFolderPath, MediaStore.ACTION_IMAGE_CAPTURE,
                        REQ_CODE_CAMERA);
            } else {
                callbackError();
            }
        } catch (InterruptedException | ExecutionException ignore) {
            callbackError();
        }

    }
}

From source file:com.luke.lukef.lukeapp.tools.LukeNetUtils.java

/**
 * Fetches all ranks from the backend/*from  w  ww .  j  a v a2s  .c o m*/
 * @return Arraylist of Rank objects
 * @throws ExecutionException
 * @throws InterruptedException
 */
public ArrayList<Rank> getAllRanks() throws ExecutionException, InterruptedException {
    Callable<ArrayList<Rank>> arrayListCallable = new Callable<ArrayList<Rank>>() {
        @Override
        public ArrayList<Rank> call() throws Exception {
            String allRanks = getMethod("http://www.balticapp.fi/lukeA/rank");
            JSONArray allRanksJson = new JSONArray(allRanks);
            ArrayList<Rank> ranks = LukeUtils.parseRanksFromJsonArray(allRanksJson);
            return ranks;
        }
    };
    FutureTask<ArrayList<Rank>> arrayListFutureTask = new FutureTask<ArrayList<Rank>>(arrayListCallable);
    Thread t = new Thread(arrayListFutureTask);
    t.start();
    return arrayListFutureTask.get();
}

From source file:com.luke.lukef.lukeapp.tools.LukeNetUtils.java

/**
 * Checks the server if a username is available
 *
 * @param usernameToCheck The username that should be checked
 * @return <b>true</b> if the username exists already, <b>false</b> if not
 * @throws ExecutionException/*from ww w.  j av  a 2  s  .co  m*/
 * @throws InterruptedException
 */
public boolean checkUsernameAvailable(final String usernameToCheck)
        throws ExecutionException, InterruptedException {
    Callable<Boolean> booleanCallable = new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            try {
                String response = getMethod(
                        "http://www.balticapp.fi/lukeA/user/available?username=" + usernameToCheck);
                JSONObject jsonObject;
                try {
                    jsonObject = new JSONObject(response);
                    // TODO: 17/11/2016 make alert that username is taken
                    if (jsonObject.has("exists")) {
                        return !jsonObject.getBoolean("exists");
                    } else {
                        return false;
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "onPostExecute: ", e);
                    return false;
                }

            } catch (MalformedURLException e) {
                Log.e(TAG, "doInBackground: ", e);
                return false;
            } catch (IOException e) {
                Log.e(TAG, "doInBackground: ", e);
                return false;
            }
        }
    };
    FutureTask<Boolean> booleanFutureTask = new FutureTask<>(booleanCallable);
    Thread thread = new Thread(booleanFutureTask);
    thread.start();
    return booleanFutureTask.get();

}

From source file:com.luke.lukef.lukeapp.tools.LukeNetUtils.java

/**
 * Fetches user data from the backend based on given userId
 *
 * @param userId The ID of the user whose data is fetched
 * @return {@link UserFromServer} object containing the user data
 * @throws ExecutionException/*from  w  ww . jav  a2s .  c o  m*/
 * @throws InterruptedException
 */
public UserFromServer getUserFromUserId(final String userId) throws ExecutionException, InterruptedException {
    Callable<UserFromServer> userFromServerCallable = new Callable<UserFromServer>() {
        @Override
        public UserFromServer call() throws Exception {
            String jsonString;
            jsonString = getMethod("http://www.balticapp.fi/lukeA/user?id=" + userId);

            if (!TextUtils.isEmpty(jsonString)) {
                final JSONObject jsonObject = new JSONObject(jsonString);
                return LukeUtils.parseUserFromJsonObject(jsonObject);
            } else {
                return null;
            }
        }
    };
    FutureTask<UserFromServer> userFromServerFutureTask = new FutureTask<>(userFromServerCallable);
    Thread t = new Thread(userFromServerFutureTask);
    t.start();
    return userFromServerFutureTask.get();

}

From source file:org.jactr.eclipse.runtime.launching.norm.AbstractACTRLaunchConfiguration.java

@Override
public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor)
        throws CoreException {
    _session = null;/*w  w w .j  av  a 2s .  com*/
    boolean shouldCleanUp = false;

    verify(configuration);

    SessionTracker tracker = getSessionTracker();
    if (tracker != null && tracker.hasActiveSessions()) {
        /*
         * prompt the user. should we defer?
         */
        FutureTask<Integer> response = new FutureTask<Integer>(new Callable<Integer>() {
            public Integer call() {
                String[] buttons = new String[] { "Cancel", "Run Now", "Run Later" };
                MessageDialog prompt = new MessageDialog(Display.getDefault().getActiveShell(), "Run when?",
                        null, "A session is already running. Run now or queue for later?",
                        MessageDialog.QUESTION, buttons, 2);

                return prompt.open();
            }
        });

        Display.getDefault().syncExec(response);

        try {
            switch (response.get()) {
            case 0:
                return;
            case 2:
                tracker.addDeferredLaunch(configuration, mode);
                return;
            }
        } catch (Exception e) {
            throw new CoreException(
                    new Status(IStatus.ERROR, RuntimePlugin.PLUGIN_ID, 0, "Could not launch runtime", e));
        }
    }

    ILaunchConfigurationWorkingCopy workingCopy = null;
    try {

        /*
         * this is needed to correctly resolve the data and config directories..
         */
        ACTRProjectVariableResolver.setCurrentProject(ACTRLaunchConfigurationUtils.getProject(configuration));

        /*
         * we create the reference to the configuration file, which is needed in
         * order to set working directories and commandline parameters for the run
         */
        IFile envFile = EnvironmentConfigurator.createRuntimeEnvironmentFile(configuration, mode, monitor);

        workingCopy = createActualConfiguration(configuration, mode, envFile, monitor);

        _session = createSession(workingCopy, launch, mode, envFile, monitor);
    } catch (CoreException ce) {
        throw ce;
    }

    try {
        configuration = workingCopy.doSave();

        super.launch(configuration, mode, launch, monitor);

        shouldCleanUp = monitor.isCanceled();

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Launched shouldCleanUp:" + shouldCleanUp);
    } catch (CoreException ce) {
        shouldCleanUp = true;
        throw ce;
    } finally {
        if (_session != null && shouldCleanUp)
            stopSession(_session);

        try {
            configuration.delete();
        } catch (CoreException ce) {
            CorePlugin.error("Could not delete temporary launch config", ce);
        }
    }
}

From source file:com.luke.lukef.lukeapp.tools.LukeNetUtils.java

/**
 * Fetches all submissions by a user from the server.
 *
 * @param userID The ID of the user whose submissions should be fetched.
 * @return Returns an ArrayList of {@link Submission} objects.
 *///w w  w.  jav  a  2s.co m
public ArrayList<Submission> getSubmissionsByUser(final String userID) {
    Callable<ArrayList<Submission>> booleanCallable = new Callable<ArrayList<Submission>>() {
        @Override
        public ArrayList<Submission> call() throws Exception {
            String jsonString = getMethod("http://www.balticapp.fi/lukeA/report?submitterId=" + userID);
            if (!TextUtils.isEmpty(jsonString)) {
                JSONArray jsonArray = new JSONArray(jsonString);
                Log.e(TAG, "call: jsonArray" + jsonArray.toString());
                return LukeUtils.parseSubmissionsFromJsonArray(jsonArray);
            } else {
                return null;
            }

        }
    };

    FutureTask<ArrayList<Submission>> booleanFutureTask = new FutureTask<>(booleanCallable);
    Thread t = new Thread(booleanFutureTask);
    t.start();
    try {
        return booleanFutureTask.get();
    } catch (InterruptedException e) {
        Log.e(TAG, "reportSubmission: ", e);
        return null;
    } catch (ExecutionException e) {
        Log.e(TAG, "reportSubmission: ", e);
        return null;
    }
}

From source file:com.luke.lukef.lukeapp.tools.LukeNetUtils.java

/**
 * Fewtches all users from the backend./*from   ww  w  .  ja v  a  2  s.  co m*/
 * @return Arraylist of User objects
 * @throws ExecutionException
 * @throws InterruptedException
 */
public ArrayList<UserFromServer> getAllUsers() throws ExecutionException, InterruptedException {

    Callable<ArrayList<UserFromServer>> userFromServerCallable = new Callable<ArrayList<UserFromServer>>() {
        @Override
        public ArrayList<UserFromServer> call() throws Exception {
            String jsonString = getMethod("http://www.balticapp.fi/lukeA/user/get-all");
            Log.e(TAG, "doInBackground: STRING IS " + jsonString);
            if (!TextUtils.isEmpty(jsonString)) {
                ArrayList<UserFromServer> returnjeeben = new ArrayList<>();
                JSONArray jsonArray = new JSONArray(jsonString);
                for (int i = 0; i < jsonArray.length(); i++) {
                    returnjeeben.add(LukeUtils.parseUserFromJsonObject(jsonArray.getJSONObject(i)));
                }
                return returnjeeben;
            } else {
                return null;
            }
        }
    };
    FutureTask<ArrayList<UserFromServer>> userFromServerFutureTask = new FutureTask<>(userFromServerCallable);
    Thread t = new Thread(userFromServerFutureTask);
    t.start();
    return userFromServerFutureTask.get();

}

From source file:com.luke.lukef.lukeapp.tools.LukeNetUtils.java

/**
 * Attempts to log in into the Luke server. If succesful, starts a task to fetch users data
 * @param welcomeActivity/*from  w ww .j av  a2s . co  m*/
 * @param idToken
 */
public void attemptLogin(final WelcomeActivity welcomeActivity, final String idToken) {

    Callable<Boolean> booleanCallable = new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            try {
                URL lukeURL = new URL(welcomeActivity.getString(R.string.loginUrl));
                HttpURLConnection httpURLConnection = (HttpURLConnection) lukeURL.openConnection();
                httpURLConnection.setRequestProperty(welcomeActivity.getString(R.string.authorization),
                        welcomeActivity.getString(R.string.bearer) + idToken);
                if (httpURLConnection.getResponseCode() == 200) {
                    return true;
                } else {
                    Log.e(TAG, "call: LOGIN DIDN'T WORK");
                    // TODO: 12/12/2016 DANIEL
                    return false;
                }
            } catch (MalformedURLException e) {
                Log.e(TAG, "call: ", e);
                return false;
            } catch (IOException e) {
                Log.e(TAG, "call: ", e);
                return false;
            }

        }
    };
    FutureTask<Boolean> booleanFutureTask = new FutureTask<>(booleanCallable);
    Thread thread = new Thread(booleanFutureTask);
    thread.start();

    try {
        if (booleanFutureTask.get()) {
            startFetchUserDataTask(welcomeActivity);
        } else {
            Log.e(TAG, "onAuthentication: booleanFutureTask failed");
        }
    } catch (InterruptedException | ExecutionException e) {
        Log.e(TAG, "onAuthentication: ", e);
    }

}

From source file:com.luke.lukef.lukeapp.tools.LukeNetUtils.java

/**
 * Fetches all existing categories from the server, parses them and adds new ones to the
 * {@link SessionSingleton}. Duplicates do not get added
 *//*from ww w .j a  v  a  2 s . co m*/
public ArrayList<Category> getCategories() throws ExecutionException, InterruptedException {
    Callable<ArrayList<Category>> categoriesCallable = new Callable<ArrayList<Category>>() {
        @Override
        public ArrayList<Category> call() throws Exception {

            String jsonString = getMethod("http://www.balticapp.fi/lukeA/category");
            JSONArray jsonArr = new JSONArray(jsonString);
            return LukeUtils.getCategoryObjectsFromJsonArray(jsonArr);

        }
    };
    FutureTask<ArrayList<Category>> arrayListFutureTask = new FutureTask<ArrayList<Category>>(
            categoriesCallable);
    Thread t = new Thread(arrayListFutureTask);
    t.start();
    return arrayListFutureTask.get();
}

From source file:com.luke.lukef.lukeapp.tools.LukeNetUtils.java

/**
 * Fetches the currently logged user from the server
 * @return User object corresponding to the currently logged user
 * @throws IOException/*from w w w. j a v a 2s.  c  o  m*/
 * @throws ExecutionException
 * @throws InterruptedException
 */
public UserFromServer getOwnUser() throws IOException, ExecutionException, InterruptedException {
    Callable<UserFromServer> userFromServerCallable = new Callable<UserFromServer>() {
        @Override
        public UserFromServer call() throws Exception {
            String jsonString = getMethod("http://www.balticapp.fi/lukeA/user/me");
            JSONObject jsonObject = new JSONObject(jsonString);
            return LukeUtils.parseUserFromJsonObject(jsonObject);

        }
    };
    FutureTask<UserFromServer> userFromServerFutureTask = new FutureTask<UserFromServer>(
            userFromServerCallable);
    Thread t = new Thread(userFromServerFutureTask);
    t.start();
    return userFromServerFutureTask.get();

}