Search in sources :

Example 51 with GET

use of retrofit2.http.GET in project instructure-android by instructure.

the class SubmissionDetailsFragment method setupCallbacks.

// /////////////////////////////////////////////////////////////////////////
// CallBack
// /////////////////////////////////////////////////////////////////////////
public void setupCallbacks() {
    notoriousConfigCallback = new StatusCallback<NotoriousConfig>() {

        @Override
        public void onResponse(@NonNull Response<NotoriousConfig> response, @NonNull LinkHeaders linkHeaders, @NonNull ApiType type) {
            if (!apiCheck()) {
                return;
            }
            NotoriousConfig notoriousConfig = response.body();
            if (notoriousConfig.isEnabled()) {
                mediaComment.setEnabled(true);
            }
        }
    };
    // We use a NoNetworkErrorDelegate because sometimes old submissions are deleted.
    // We don't want to display unnecessary croutons.
    canvasCallbackSubmission = new StatusCallback<Submission>() {

        @Override
        public void onResponse(@NonNull Response<Submission> response, @NonNull LinkHeaders linkHeaders, @NonNull ApiType type) {
            if (!apiCheck()) {
                return;
            }
            if (response.body() != null) {
                populateAdapter(response.body());
            }
        }
    };
    canvasCallbackMessage = new StatusCallback<Submission>() {

        @Override
        public void onResponse(@NonNull Response<Submission> response, @NonNull LinkHeaders linkHeaders, @NonNull ApiType type) {
            if (!apiCheck()) {
                return;
            }
            // See if it was successful.
            Submission submission = response.body();
            if (submission != null) {
                SubmissionComment comment = submission.getSubmissionComments().get(submission.getSubmissionComments().size() - 1);
                // Our list is a list of Submission, so add the comment to a SubmissionGrade object
                Submission newSub = new Submission();
                ArrayList<SubmissionComment> comments = new ArrayList<>();
                comments.add(comment);
                newSub.setSubmittedAt(comment.getCreatedAt());
                newSub.setSubmissionComments(comments);
                adapter.subList.add(0, newSub);
                message.setText("");
            } else {
                showToast(R.string.errorPostingComment);
            }
            adapter.notifyDataSetChanged();
            // Close the keyboard
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(message.getWindowToken(), 0);
            // Enable the send message button again
            submitComment.setVisibility(View.VISIBLE);
            sendingProgressBar.setVisibility(View.GONE);
            // Clear the attachments list
            attachmentsList.clear();
            attachmentIds.clear();
            attachments.clear();
            refreshAttachments();
        }

        @Override
        public void onFail(@Nullable Call<Submission> call, @NonNull Throwable error, @Nullable Response response) {
            // Enable the send message button again if there was an Error
            submitComment.setVisibility(View.VISIBLE);
            sendingProgressBar.setVisibility(View.GONE);
            // Clear the attachments list
            attachmentsList.clear();
            attachmentIds.clear();
            attachments.clear();
            refreshAttachments();
        }
    };
    canvasCallbackLTITool = new StatusCallback<LTITool>() {

        @Override
        public void onResponse(@NonNull Response<LTITool> response, @NonNull LinkHeaders linkHeaders, @NonNull ApiType type) {
            if (!apiCheck()) {
                return;
            }
            LTITool ltiTool = response.body();
            String url = ltiTool.getUrl();
            // Append platform for quizzes 2 lti tool
            Uri uri = Uri.parse(url).buildUpon().appendQueryParameter("platform", "android").build();
            // Do NOT authenticate or the LTI tool won't load.
            InternalWebviewFragment.Companion.loadInternalWebView(getActivity(), ((Navigation) getActivity()), InternalWebviewFragment.Companion.createBundle(getCanvasContext(), uri.toString(), ltiTool.getName(), false, false, true, assignment.getUrl()));
        }

        @Override
        public void onFail(@Nullable Call<LTITool> call, @NonNull Throwable error, @Nullable Response response) {
            // If it wasn't a network Error, then the LTI tool must be expired or invalid.
            if (APIHelper.hasNetworkConnection() && (response == null || (response != null && response.code() != 504))) {
                showToast(R.string.invalidExternal);
            }
        }
    };
    canvasCallbackAssignment = new StatusCallback<Assignment>() {

        @Override
        public void onResponse(@NonNull Response<Assignment> response, @NonNull LinkHeaders linkHeaders, @NonNull ApiType type) {
            if (!apiCheck()) {
                return;
            }
            Assignment newAssignment = response.body();
            String authenticationURL;
            if (newAssignment == null) {
                authenticationURL = null;
            } else {
                authenticationURL = newAssignment.getUrl();
            }
            // Now get the LTITool
            // This API call handles url being null
            SubmissionManager.getLtiFromAuthenticationUrl(authenticationURL, canvasCallbackLTITool, true);
        }
    };
}
Also used : ArrayList(java.util.ArrayList) InputMethodManager(android.view.inputmethod.InputMethodManager) Uri(android.net.Uri) SubmissionComment(com.instructure.canvasapi2.models.SubmissionComment) Assignment(com.instructure.canvasapi2.models.Assignment) ApiType(com.instructure.canvasapi2.utils.ApiType) Submission(com.instructure.canvasapi2.models.Submission) GradeableStudentSubmission(com.instructure.canvasapi2.models.GradeableStudentSubmission) LTITool(com.instructure.canvasapi2.models.LTITool) LinkHeaders(com.instructure.canvasapi2.utils.LinkHeaders) Response(retrofit2.Response) NotoriousConfig(com.instructure.canvasapi2.models.NotoriousConfig)

Example 52 with GET

use of retrofit2.http.GET in project azure-sdk-for-java by Azure.

the class NetworkWatchersInner method beginGetTroubleshootingResultWithServiceResponseAsync.

/**
     * Get the last completed troubleshooting result on a specified resource.
     *
     * @param resourceGroupName The name of the resource group.
     * @param networkWatcherName The name of the network watcher resource.
     * @param targetResourceId The target resource ID to query the troubleshooting result.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the TroubleshootingResultInner object
     */
public Observable<ServiceResponse<TroubleshootingResultInner>> beginGetTroubleshootingResultWithServiceResponseAsync(String resourceGroupName, String networkWatcherName, String targetResourceId) {
    if (resourceGroupName == null) {
        throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
    }
    if (networkWatcherName == null) {
        throw new IllegalArgumentException("Parameter networkWatcherName is required and cannot be null.");
    }
    if (this.client.subscriptionId() == null) {
        throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
    }
    if (targetResourceId == null) {
        throw new IllegalArgumentException("Parameter targetResourceId is required and cannot be null.");
    }
    final String apiVersion = "2016-12-01";
    QueryTroubleshootingParameters parameters = new QueryTroubleshootingParameters();
    parameters.withTargetResourceId(targetResourceId);
    return service.beginGetTroubleshootingResult(resourceGroupName, networkWatcherName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent()).flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<TroubleshootingResultInner>>>() {

        @Override
        public Observable<ServiceResponse<TroubleshootingResultInner>> call(Response<ResponseBody> response) {
            try {
                ServiceResponse<TroubleshootingResultInner> clientResponse = beginGetTroubleshootingResultDelegate(response);
                return Observable.just(clientResponse);
            } catch (Throwable t) {
                return Observable.error(t);
            }
        }
    });
}
Also used : Response(retrofit2.Response) ServiceResponse(com.microsoft.rest.ServiceResponse) ServiceResponse(com.microsoft.rest.ServiceResponse) Observable(rx.Observable) QueryTroubleshootingParameters(com.microsoft.azure.management.network.QueryTroubleshootingParameters) ResponseBody(okhttp3.ResponseBody)

Example 53 with GET

use of retrofit2.http.GET in project azure-sdk-for-java by Azure.

the class NetworkWatchersInner method getTroubleshootingResultWithServiceResponseAsync.

/**
     * Get the last completed troubleshooting result on a specified resource.
     *
     * @param resourceGroupName The name of the resource group.
     * @param networkWatcherName The name of the network watcher resource.
     * @param targetResourceId The target resource ID to query the troubleshooting result.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
public Observable<ServiceResponse<TroubleshootingResultInner>> getTroubleshootingResultWithServiceResponseAsync(String resourceGroupName, String networkWatcherName, String targetResourceId) {
    if (resourceGroupName == null) {
        throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
    }
    if (networkWatcherName == null) {
        throw new IllegalArgumentException("Parameter networkWatcherName is required and cannot be null.");
    }
    if (this.client.subscriptionId() == null) {
        throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
    }
    if (targetResourceId == null) {
        throw new IllegalArgumentException("Parameter targetResourceId is required and cannot be null.");
    }
    final String apiVersion = "2016-12-01";
    QueryTroubleshootingParameters parameters = new QueryTroubleshootingParameters();
    parameters.withTargetResourceId(targetResourceId);
    Observable<Response<ResponseBody>> observable = service.getTroubleshootingResult(resourceGroupName, networkWatcherName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent());
    return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken<TroubleshootingResultInner>() {
    }.getType());
}
Also used : Response(retrofit2.Response) ServiceResponse(com.microsoft.rest.ServiceResponse) TypeToken(com.google.common.reflect.TypeToken) QueryTroubleshootingParameters(com.microsoft.azure.management.network.QueryTroubleshootingParameters)

Example 54 with GET

use of retrofit2.http.GET in project android-diplicity by zond.

the class MainActivity method onPostCreate.

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();
    addGameButton = (FloatingActionButton) findViewById(R.id.add_game_button);
    addGameButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            handleReq(userStatsService.UserStatsLoad(getLoggedInUser().Id), new Sendable<SingleContainer<UserStats>>() {

                @Override
                public void send(SingleContainer<UserStats> userStatsSingleContainer) {
                    final List<UserStats> statsContainer = new ArrayList<>();
                    statsContainer.add(userStatsSingleContainer.Properties);
                    final AlertDialog dialog = new AlertDialog.Builder(MainActivity.this).setView(R.layout.create_game_dialog).show();
                    final Returner<Game, Boolean> validateGame = new Returner<Game, Boolean>() {

                        @Override
                        public Boolean Return(Game g) {
                            if (g.PhaseLengthMinutes == null)
                                g.PhaseLengthMinutes = DAY_IN_MINUTES;
                            if (g.PhaseLengthMinutes > 30 * DAY_IN_MINUTES) {
                                Toast.makeText(MainActivity.this, R.string.phase_length_must_be_less_than_30_days, Toast.LENGTH_LONG).show();
                                return false;
                            }
                            UserStats us = statsContainer.get(0);
                            if (g.MinRating == null)
                                g.MinRating = 0.0;
                            if (g.MinRating != 0.0 && g.MinRating > us.Glicko.PracticalRating) {
                                Toast.makeText(MainActivity.this, getResources().getString(R.string.minimum_rating_must_be_below_your_rating_x, us.Glicko.PracticalRating), Toast.LENGTH_LONG).show();
                                return false;
                            }
                            if (g.MaxRating == null)
                                g.MaxRating = 0.0;
                            if (g.MaxRating != 0.0 && g.MaxRating < us.Glicko.PracticalRating) {
                                Toast.makeText(MainActivity.this, getResources().getString(R.string.maximum_rating_must_be_above_your_rating_x, us.Glicko.PracticalRating), Toast.LENGTH_LONG).show();
                                return false;
                            }
                            if (g.MinReliability == null)
                                g.MinReliability = 0.0;
                            if (g.MinReliability != 0.0 && g.MinReliability > us.Reliability) {
                                Toast.makeText(MainActivity.this, getResources().getString(R.string.minimum_reliability_must_be_below_your_reliability_x, us.Reliability), Toast.LENGTH_LONG).show();
                                return false;
                            }
                            if (g.MinQuickness == null)
                                g.MinQuickness = 0.0;
                            if (g.MinQuickness != 0.0 && g.MinQuickness > us.Quickness) {
                                Toast.makeText(MainActivity.this, getResources().getString(R.string.minimum_quickness_must_be_below_your_quickness_x, us.Quickness), Toast.LENGTH_LONG).show();
                                return false;
                            }
                            if (g.MaxHated == null)
                                g.MaxHated = 0.0;
                            if (g.MaxHated != 0.0 && g.MaxHated < us.Hated) {
                                Toast.makeText(MainActivity.this, getResources().getString(R.string.maximum_hated_must_be_above_your_hated_x, us.Hated), Toast.LENGTH_LONG).show();
                                return false;
                            }
                            if (g.MaxHater == null)
                                g.MaxHater = 0.0;
                            if (g.MaxHater != 0.0 && g.MaxHater < us.Hater) {
                                Toast.makeText(MainActivity.this, getResources().getString(R.string.maximum_hater_must_be_above_your_hater_x, us.Hater), Toast.LENGTH_LONG).show();
                                return false;
                            }
                            return true;
                        }
                    };
                    final Spinner variants = ((Spinner) dialog.findViewById(R.id.variants));
                    final List<SpinnerVariantElement> variantNames = new ArrayList<>();
                    for (SingleContainer<VariantService.Variant> variantContainer : getVariants().Properties) {
                        SpinnerVariantElement el = new SpinnerVariantElement();
                        el.name = variantContainer.Properties.Name;
                        if (variantContainer.Properties.Nations != null) {
                            el.players = variantContainer.Properties.Nations.size();
                        }
                        variantNames.add(el);
                    }
                    int classical = 0;
                    Collections.sort(variantNames);
                    for (int i = 0; i < variantNames.size(); i++) {
                        if (variantNames.get(i).name.equals("Classical")) {
                            classical = i;
                        }
                    }
                    ArrayAdapter<SpinnerVariantElement> variantAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_item, variantNames);
                    variants.setAdapter(variantAdapter);
                    variantAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    variants.setSelection(classical);
                    final EditText gameNameView = (EditText) dialog.findViewById(R.id.desc);
                    final EditText phaseLengthView = (EditText) dialog.findViewById(R.id.phase_length);
                    final Spinner phaseLengthUnitsSpinner = (Spinner) dialog.findViewById(R.id.phase_length_units);
                    final EditText minRatingView = (EditText) dialog.findViewById(R.id.min_rating);
                    final EditText maxRatingView = (EditText) dialog.findViewById(R.id.max_rating);
                    final EditText minReliabilityView = (EditText) dialog.findViewById(R.id.min_reliability);
                    final EditText minQuicknessView = (EditText) dialog.findViewById(R.id.min_quickness);
                    final EditText maxHatedView = (EditText) dialog.findViewById(R.id.max_hated);
                    final EditText maxHaterView = (EditText) dialog.findViewById(R.id.max_hater);
                    final View.OnFocusChangeListener gameNameListener = new View.OnFocusChangeListener() {

                        private final int key = random.nextInt(Integer.MAX_VALUE);

                        private boolean generatedName = true;

                        @Override
                        public void onFocusChange(View view, boolean b) {
                            if (view.equals(gameNameView)) {
                                if (gameNameView.getText().toString().isEmpty()) {
                                    generatedName = true;
                                }
                            }
                            if (generatedName) {
                                long phaseLength = getPhaseLengthMinutes(phaseLengthView, phaseLengthUnitsSpinner);
                                String battle;
                                if (phaseLength < DAY_IN_MINUTES) {
                                    battle = getKeyedString(R.array.blitz);
                                } else if (phaseLength <= 2 * DAY_IN_MINUTES) {
                                    battle = getKeyedString(R.array.battle);
                                } else {
                                    battle = getKeyedString(R.array.war);
                                }
                                String adjective;
                                if (getDoubleValue(minRatingView, 0) > 1400) {
                                    adjective = getKeyedString(R.array.quality);
                                } else if (getDoubleValue(maxRatingView, 2000) < 1000) {
                                    adjective = getKeyedString(R.array.fun);
                                } else if (getDoubleValue(minReliabilityView, 0) > 10) {
                                    adjective = getKeyedString(R.array.reliable);
                                } else if (getDoubleValue(minQuicknessView, 0) > 10) {
                                    adjective = getKeyedString(R.array.fast);
                                } else if (getDoubleValue(maxHatedView, 100) < 10) {
                                    adjective = getKeyedString(R.array.pleasant);
                                } else if (getDoubleValue(maxHaterView, 100) < 10) {
                                    adjective = getKeyedString(R.array.patient);
                                } else {
                                    adjective = getKeyedString(R.array.other);
                                }
                                String prize = getKeyedString(R.array.prize);
                                String calculatedName = getResources().getString(R.string.game_name_template, battle, adjective, prize);
                                if (view.equals(gameNameView)) {
                                    String enteredName = gameNameView.getText().toString();
                                    generatedName = (enteredName.isEmpty() || enteredName.equals(calculatedName));
                                } else {
                                    gameNameView.setText(calculatedName);
                                }
                            }
                        }

                        private double getDoubleValue(EditText editText, int def) {
                            try {
                                return Double.parseDouble(editText.getText().toString());
                            } catch (NumberFormatException e) {
                                return def;
                            }
                        }

                        private String getKeyedString(int arrayId) {
                            return getResources().getStringArray(arrayId)[key % getResources().getStringArray(arrayId).length];
                        }
                    };
                    AdapterView.OnItemSelectedListener phaseLengthUnitsListener = new AdapterView.OnItemSelectedListener() {

                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            gameNameListener.onFocusChange(view, false);
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {
                            parent.setSelection(0);
                        }
                    };
                    setDefaultPhaseLength(phaseLengthView, phaseLengthUnitsSpinner);
                    setDefaultMinReliability(minReliabilityView, statsContainer.get(0));
                    setDefaultMinQuickness(minQuicknessView, statsContainer.get(0));
                    gameNameView.setOnFocusChangeListener(gameNameListener);
                    phaseLengthView.setOnFocusChangeListener(gameNameListener);
                    minRatingView.setOnFocusChangeListener(gameNameListener);
                    maxRatingView.setOnFocusChangeListener(gameNameListener);
                    minReliabilityView.setOnFocusChangeListener(gameNameListener);
                    minQuicknessView.setOnFocusChangeListener(gameNameListener);
                    maxHatedView.setOnFocusChangeListener(gameNameListener);
                    maxHaterView.setOnFocusChangeListener(gameNameListener);
                    phaseLengthUnitsSpinner.setOnItemSelectedListener(phaseLengthUnitsListener);
                    ((FloatingActionButton) dialog.findViewById(R.id.create_game_button)).setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View view) {
                            final Game game = new Game();
                            game.Desc = gameNameView.getText().toString();
                            game.Variant = variantNames.get(variants.getSelectedItemPosition()).name;
                            game.PhaseLengthMinutes = getPhaseLengthMinutes(phaseLengthView, phaseLengthUnitsSpinner);
                            try {
                                game.MinRating = Double.parseDouble(minRatingView.getText().toString());
                            } catch (NumberFormatException e) {
                            }
                            try {
                                game.MaxRating = Double.parseDouble(maxRatingView.getText().toString());
                            } catch (NumberFormatException e) {
                            }
                            try {
                                game.MinReliability = Double.parseDouble(minReliabilityView.getText().toString());
                            } catch (NumberFormatException e) {
                            }
                            try {
                                game.MinQuickness = Double.parseDouble(minQuicknessView.getText().toString());
                            } catch (NumberFormatException e) {
                            }
                            try {
                                game.MaxHated = Double.parseDouble(maxHatedView.getText().toString());
                            } catch (NumberFormatException e) {
                            }
                            try {
                                game.MaxHater = Double.parseDouble(maxHaterView.getText().toString());
                            } catch (NumberFormatException e) {
                            }
                            if (validateGame.Return(game)) {
                                handleReq(gameService.GameCreate(game), new Sendable<SingleContainer<Game>>() {

                                    @Override
                                    public void send(SingleContainer<Game> gameSingleContainer) {
                                        if (nextCursorContainer.get(0).length() == 0) {
                                            findViewById(R.id.empty_view).setVisibility(View.GONE);
                                            contentList.setVisibility(View.VISIBLE);
                                            gamesAdapter.items.add(gameSingleContainer);
                                            gamesAdapter.notifyDataSetChanged();
                                        }
                                        dialog.dismiss();
                                    }
                                }, new ErrorHandler(412, new Sendable<HttpException>() {

                                    @Override
                                    public void send(HttpException e) {
                                        handleReq(userStatsService.UserStatsLoad(getLoggedInUser().Id), new Sendable<SingleContainer<UserStats>>() {

                                            @Override
                                            public void send(SingleContainer<UserStats> userStatsSingleContainer) {
                                                statsContainer.set(0, userStatsSingleContainer.Properties);
                                                validateGame.Return(game);
                                            }
                                        }, getResources().getString(R.string.creating_game));
                                    }
                                }), getResources().getString(R.string.creating_game));
                            }
                        }
                    });
                }
            }, getResources().getString(R.string.loading_user_stats));
        }

        /**
         * Determine the current user entered phase length.
         *
         * @param phaseLengthView The view containing the selected quantity.
         * @param phaseLengthUnitsView The spiner containing the selected units.
         * @return The selected phase length in minutes.
         */
        private long getPhaseLengthMinutes(EditText phaseLengthView, Spinner phaseLengthUnitsView) {
            // Get the quantity entered
            long quantity;
            try {
                quantity = Long.valueOf(phaseLengthView.getText().toString());
            } catch (NumberFormatException e) {
                setDefaultPhaseLength(phaseLengthView, phaseLengthUnitsView);
                quantity = Long.valueOf(phaseLengthView.getText().toString());
            }
            // Use the quantity and the selected unit to find the phase length.
            long phaseLength;
            int selectedItem = phaseLengthUnitsView.getSelectedItemPosition();
            if (selectedItem == getIndexOfUnit(R.string._day_s)) {
                phaseLength = quantity * DAY_IN_MINUTES;
            } else if (selectedItem == getIndexOfUnit(R.string._hour_s)) {
                phaseLength = quantity * HOUR_IN_MINUTES;
            } else if (selectedItem == getIndexOfUnit(R.string._minute_s)) {
                phaseLength = quantity;
            } else {
                Log.e("Diplicity", "Programmer error: Unexpected phase length units selected");
                throw new IllegalStateException("Programmer error: Unexpected phase length units selected");
            }
            return phaseLength;
        }

        /**
         * Set the phase length to the default of one day.
         */
        private void setDefaultPhaseLength(EditText phaseLengthView, Spinner phaseLengthUnitsView) {
            phaseLengthView.setText("1");
            phaseLengthUnitsView.setSelection(getIndexOfUnit(R.string._day_s));
        }

        private void setDefaultMinReliability(EditText minReliabilityView, UserStats userStats) {
            if (userStats.Reliability > 10) {
                minReliabilityView.setText("10");
            } else {
                minReliabilityView.setText("" + userStats.Reliability.intValue());
            }
        }

        private void setDefaultMinQuickness(EditText minQuicknessView, UserStats userStats) {
            if (userStats.Quickness > 10) {
                minQuicknessView.setText("10");
            } else {
                minQuicknessView.setText("" + userStats.Quickness.intValue());
            }
        }

        /**
         * Get the index of the given unit string resource in the array list used by the units spinner.
         */
        private int getIndexOfUnit(int unitString) {
            List<String> unitLabels = asList(getResources().getStringArray(R.array.phaseLengthUnits));
            return unitLabels.indexOf(getResources().getString(unitString));
        }
    });
    setupNavigation();
    contentList = (RecyclerView) findViewById(R.id.content_list);
    LinearLayoutManager contentLayoutManager = new LinearLayoutManager(this);
    contentLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    contentList.setLayoutManager(contentLayoutManager);
    scrollListener = new EndlessRecyclerViewScrollListener(contentLayoutManager, nextCursor) {

        @Override
        public void onLoadMore(String cursor, int totalItemsCount, RecyclerView view) {
            if (cursor.length() > 0) {
                loadMoreProcContainer.get(0).send(cursor);
            }
        }
    };
    contentList.addOnScrollListener(scrollListener);
    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, contentLayoutManager.getOrientation());
    contentList.addItemDecoration(dividerItemDecoration);
    loadMoreProcContainer.add(null);
    if (!ACTION_VIEW_USER_GAMES.equals(getIntent().getAction()) && !Intent.ACTION_VIEW.equals(getIntent().getAction()))
        navigateTo(0, 0);
}
Also used : AlertDialog(android.support.v7.app.AlertDialog) Spinner(android.widget.Spinner) ActionBarDrawerToggle(android.support.v7.app.ActionBarDrawerToggle) ArrayList(java.util.ArrayList) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) FloatingActionButton(android.support.design.widget.FloatingActionButton) HttpException(retrofit2.adapter.rxjava.HttpException) Arrays.asList(java.util.Arrays.asList) List(java.util.List) ArrayList(java.util.ArrayList) DrawerLayout(android.support.v4.widget.DrawerLayout) Toolbar(android.support.v7.widget.Toolbar) EditText(android.widget.EditText) DividerItemDecoration(android.support.v7.widget.DividerItemDecoration) View(android.view.View) AdapterView(android.widget.AdapterView) TextView(android.widget.TextView) RecyclerView(android.support.v7.widget.RecyclerView) ExpandableListView(android.widget.ExpandableListView) SingleContainer(se.oort.diplicity.apigen.SingleContainer) UserStats(se.oort.diplicity.apigen.UserStats) Game(se.oort.diplicity.apigen.Game) AdapterView(android.widget.AdapterView) RecyclerView(android.support.v7.widget.RecyclerView) ArrayAdapter(android.widget.ArrayAdapter)

Example 55 with GET

use of retrofit2.http.GET in project android-diplicity by zond.

the class RetrofitActivity method onActivityResult.

@Override
protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == LOGIN_REQUEST) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result != null) {
            if (result.isSuccess()) {
                final GoogleSignInAccount acct = result.getSignInAccount();
                Observable.create(new Observable.OnSubscribe<String>() {

                    @Override
                    public void call(final Subscriber<? super String> subscriber) {
                        Response response = null;
                        try {
                            String url = getBaseURL() + "Auth/OAuth2Callback?code=" + URLEncoder.encode(acct.getServerAuthCode(), "UTF-8") + "&approve-redirect=true&state=" + URLEncoder.encode("https://android-diplicity", "UTF-8");
                            Request request = new Request.Builder().url(url).build();
                            response = new OkHttpClient.Builder().followRedirects(false).followSslRedirects(false).connectTimeout(10, TimeUnit.SECONDS).readTimeout(10, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS).build().newCall(request).execute();
                            if (response.code() != 307) {
                                throw new RuntimeException("Unsuccessful response " + response.body().string());
                            }
                            url = response.headers().get("Location");
                            if (url == null) {
                                throw new RuntimeException("No Location header in response " + response.body().string());
                            }
                            Uri parsedURI = Uri.parse(url);
                            if (parsedURI == null) {
                                throw new RuntimeException("Unparseable Location header " + url + " in response");
                            }
                            subscriber.onNext(parsedURI.getQueryParameter("token"));
                            subscriber.onCompleted();
                        } catch (RuntimeException e) {
                            throw e;
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {

                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        App.firebaseCrashReport("Unable to log in", e);
                        Toast.makeText(RetrofitActivity.this, R.string.login_failed, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(String token) {
                        PreferenceManager.getDefaultSharedPreferences(RetrofitActivity.this).edit().putString(AUTH_TOKEN_PREF_KEY, token).apply();
                        performLogin();
                    }
                });
            } else {
                App.firebaseCrashReport("Login failed: " + result.getStatus().getStatus());
                Toast.makeText(this, R.string.login_failed, Toast.LENGTH_SHORT).show();
            }
        } else {
            App.firebaseCrashReport("Login failed, null result");
            Toast.makeText(this, R.string.login_failed, Toast.LENGTH_SHORT).show();
        }
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) GsonBuilder(com.google.gson.GsonBuilder) Request(okhttp3.Request) Uri(android.net.Uri) GoogleSignInResult(com.google.android.gms.auth.api.signin.GoogleSignInResult) HttpException(retrofit2.adapter.rxjava.HttpException) JsonSyntaxException(com.google.gson.JsonSyntaxException) IOException(java.io.IOException) Response(okhttp3.Response) GoogleSignInAccount(com.google.android.gms.auth.api.signin.GoogleSignInAccount) Subscriber(rx.Subscriber)

Aggregations

ResponseBody (okhttp3.ResponseBody)61 Test (org.junit.Test)54 Request (okhttp3.Request)52 Response (retrofit2.Response)27 Retrofit (retrofit2.Retrofit)23 Query (retrofit2.http.Query)15 List (java.util.List)14 IOException (java.io.IOException)12 OkHttpClient (okhttp3.OkHttpClient)12 HttpUrl (okhttp3.HttpUrl)10 Path (retrofit2.http.Path)10 ArrayList (java.util.ArrayList)9 BrainSentences (com.gladysinc.gladys.Models.BrainSentences)8 RetrofitAPI (com.gladysinc.gladys.Utils.RetrofitAPI)8 SelfSigningClientBuilder (com.gladysinc.gladys.Utils.SelfSigningClientBuilder)8 ServiceResponse (com.microsoft.rest.ServiceResponse)8 Call (retrofit2.Call)8 Url (retrofit2.http.Url)8 Uri (android.net.Uri)6 View (android.view.View)6