Search in sources :

Example 1 with StepikClientException

use of org.stepik.api.exceptions.StepikClientException in project intellij-plugins by StepicOrg.

the class StepikAuthManager method minorLogin.

@NotNull
private static StepikAuthState minorLogin() {
    if (isAuthenticated()) {
        return AUTH;
    }
    String refreshToken = stepikApiClient.getTokenInfo().getRefreshToken();
    if (refreshToken == null) {
        TokenInfo tokenInfo = getTokenInfo(getLastUser());
        refreshToken = tokenInfo.getRefreshToken();
    }
    if (refreshToken != null) {
        try {
            stepikApiClient.oauth2().userAuthenticationRefresh(CLIENT_ID, refreshToken).execute();
            logger.info("Refresh a token is successfully");
            return AUTH;
        } catch (StepikClientException re) {
            logger.info("Refresh a token failed: " + re.getMessage());
        }
    }
    return NOT_AUTH;
}
Also used : TokenInfo(org.stepik.api.objects.auth.TokenInfo) StepikClientException(org.stepik.api.exceptions.StepikClientException) NotNull(org.jetbrains.annotations.NotNull)

Example 2 with StepikClientException

use of org.stepik.api.exceptions.StepikClientException in project intellij-plugins by StepicOrg.

the class StepikAbstractGetQuery method execute.

@NotNull
@Override
public R execute() {
    StepikApiClient stepikApiClient = getStepikAction().getStepikApiClient();
    if (!isCacheEnabled() || !stepikApiClient.isCacheEnabled()) {
        return super.execute();
    }
    List<String> ids = getParam(IDS_KEY);
    if (ids.isEmpty()) {
        return super.execute();
    }
    Path cachePath = stepikApiClient.getCachePath();
    Path courseCache = cachePath.resolve(getCacheSubdirectory());
    R items;
    try {
        items = getResponseClass().newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        throw new StepikClientException("Can't create a new instance for a response class", e);
    }
    List<String> idsForQuery;
    if (Files.exists(courseCache)) {
        idsForQuery = new ArrayList<>();
        for (String id : ids) {
            Path file = courseCache.resolve(id + JSON_EXTENSION);
            if (Files.exists(file)) {
                long updateFileTime = file.toFile().lastModified();
                long currentTime = new Date().getTime();
                long diff = currentTime - updateFileTime;
                if (diff > 0 && diff <= getCacheLifeTime()) {
                    Object item = null;
                    try {
                        String text = Utils.readFile(file);
                        //noinspection unchecked
                        item = getJsonConverter().fromJson(text, items.getItemClass());
                    } catch (JsonSyntaxException ignored) {
                    }
                    if (item != null) {
                        //noinspection unchecked
                        items.getItems().add(item);
                        continue;
                    }
                }
            }
            idsForQuery.add(id);
        }
    } else {
        idsForQuery = ids;
    }
    if (!idsForQuery.isEmpty()) {
        id(idsForQuery);
        R loadedItems = super.execute();
        //            noinspection unchecked
        loadedItems.getItems().forEach((item) -> flushCourse(item, courseCache));
        //noinspection unchecked
        items.getItems().addAll(loadedItems.getItems());
    }
    return items;
}
Also used : Path(java.nio.file.Path) StepikApiClient(org.stepik.api.client.StepikApiClient) StepikClientException(org.stepik.api.exceptions.StepikClientException) Date(java.util.Date) JsonSyntaxException(com.google.gson.JsonSyntaxException) AbstractObject(org.stepik.api.objects.AbstractObject) NotNull(org.jetbrains.annotations.NotNull)

Example 3 with StepikClientException

use of org.stepik.api.exceptions.StepikClientException in project intellij-plugins by StepicOrg.

the class StepikFilesAction method get.

@NotNull
public String get(@NotNull String url, String contentType) {
    StepikApiClient stepikApi = getStepikApiClient();
    TransportClient transportClient = stepikApi.getTransportClient();
    Map<String, String> headers = new HashMap<>();
    TokenInfo tokenInfo = stepikApi.getTokenInfo();
    String accessToken = tokenInfo.getAccessToken();
    if (accessToken != null) {
        String tokenType = tokenInfo.getTokenType();
        headers.put(HttpHeaders.AUTHORIZATION, tokenType + " " + accessToken);
    }
    headers.put(HttpHeaders.CONTENT_TYPE, contentType);
    ClientResponse response = transportClient.get(stepikApi, url, headers);
    if (response.getStatusCode() / 100 != 2) {
        String message = "Failed query to " + url + " returned the status code " + response.getStatusCode();
        logger.warn(message);
        if (response.getStatusCode() == StatusCodes.SC_UNAUTHORIZED) {
            throw new StepikUnauthorizedException(message);
        } else {
            throw new StepikClientException(message);
        }
    }
    String result = response.getBody();
    if (result == null) {
        throw new StepikClientException("Request successfully but the response body is null: " + url);
    }
    return result;
}
Also used : ClientResponse(org.stepik.api.client.ClientResponse) StepikApiClient(org.stepik.api.client.StepikApiClient) StepikUnauthorizedException(org.stepik.api.exceptions.StepikUnauthorizedException) TransportClient(org.stepik.api.client.TransportClient) HashMap(java.util.HashMap) TokenInfo(org.stepik.api.objects.auth.TokenInfo) StepikClientException(org.stepik.api.exceptions.StepikClientException) NotNull(org.jetbrains.annotations.NotNull)

Example 4 with StepikClientException

use of org.stepik.api.exceptions.StepikClientException in project intellij-plugins by StepicOrg.

the class HttpTransportClient method call.

@NotNull
private ClientResponse call(@NotNull StepikApiClient stepikApiClient, @NotNull HttpUriRequest request) {
    int statusCode;
    StringBuilder result;
    Map<String, String> headers;
    try (CloseableHttpResponse response = httpClient.execute(request)) {
        statusCode = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        result = new StringBuilder();
        if (entity != null) {
            try (BufferedReader content = new BufferedReader(new InputStreamReader(entity.getContent(), ENCODING))) {
                String line;
                while ((line = content.readLine()) != null) {
                    result.append("\n").append(line);
                }
                if (result.length() > 0) {
                    // Delete first break line
                    result.deleteCharAt(0);
                }
            } catch (IOException | UnsupportedOperationException e) {
                throw new StepikClientException("Failed getting a content", e);
            }
        }
        headers = getHeaders(response.getAllHeaders());
    } catch (IOException e) {
        throw new StepikClientException("Failed a request", e);
    }
    return new ClientResponse(stepikApiClient, statusCode, result.toString(), headers);
}
Also used : HttpEntity(org.apache.http.HttpEntity) InputStreamReader(java.io.InputStreamReader) IOException(java.io.IOException) StepikClientException(org.stepik.api.exceptions.StepikClientException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) BufferedReader(java.io.BufferedReader) NotNull(org.jetbrains.annotations.NotNull)

Example 5 with StepikClientException

use of org.stepik.api.exceptions.StepikClientException in project intellij-plugins by StepicOrg.

the class StepikAbstractQuery method execute.

@NotNull
public T execute() {
    StepikApiClient stepikApi = stepikAction.getStepikApiClient();
    TransportClient transportClient = stepikApi.getTransportClient();
    String url = getUrl();
    Map<String, String> headers = new HashMap<>();
    TokenInfo tokenInfo = stepikApi.getTokenInfo();
    String accessToken = tokenInfo.getAccessToken();
    if (accessToken != null) {
        String tokenType = tokenInfo.getTokenType();
        headers.put(HttpHeaders.AUTHORIZATION, tokenType + " " + accessToken);
    }
    headers.put(HttpHeaders.CONTENT_TYPE, getContentType());
    ClientResponse response = null;
    switch(method) {
        case GET:
            url += "?" + mapToGetString();
            response = transportClient.get(stepikApi, url, headers);
            break;
        case POST:
            response = transportClient.post(stepikApi, url, getBody(), headers);
            break;
    }
    if (response.getStatusCode() / 100 != 2) {
        String message = "Failed query to " + getUrl() + " returned the status code " + response.getStatusCode();
        logger.warn(message);
        if (response.getStatusCode() == StatusCodes.SC_UNAUTHORIZED) {
            throw new StepikUnauthorizedException(message);
        } else {
            throw new StepikClientException(message);
        }
    }
    T result = response.getBody(responseClass);
    if (responseClass == VoidResult.class) {
        //noinspection unchecked
        return (T) new VoidResult();
    }
    if (result == null) {
        throw new StepikClientException("Request successfully but the response body is null: " + url);
    }
    return result;
}
Also used : ClientResponse(org.stepik.api.client.ClientResponse) StepikApiClient(org.stepik.api.client.StepikApiClient) StepikUnauthorizedException(org.stepik.api.exceptions.StepikUnauthorizedException) TransportClient(org.stepik.api.client.TransportClient) HashMap(java.util.HashMap) TokenInfo(org.stepik.api.objects.auth.TokenInfo) StepikClientException(org.stepik.api.exceptions.StepikClientException) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

StepikClientException (org.stepik.api.exceptions.StepikClientException)28 StepikApiClient (org.stepik.api.client.StepikApiClient)12 NotNull (org.jetbrains.annotations.NotNull)10 StepikAuthManager.authAndGetStepikApiClient (org.stepik.core.stepik.StepikAuthManager.authAndGetStepikApiClient)9 CompoundUnitLesson (org.stepik.api.objects.lessons.CompoundUnitLesson)6 Submissions (org.stepik.api.objects.submissions.Submissions)5 HashMap (java.util.HashMap)4 Nullable (org.jetbrains.annotations.Nullable)4 Step (org.stepik.api.objects.steps.Step)4 ArrayList (java.util.ArrayList)3 StudyObject (org.stepik.api.objects.StudyObject)3 TokenInfo (org.stepik.api.objects.auth.TokenInfo)3 Course (org.stepik.api.objects.courses.Course)3 Sections (org.stepik.api.objects.sections.Sections)3 Steps (org.stepik.api.objects.steps.Steps)3 User (org.stepik.api.objects.users.User)3 StepikAuthManager.getCurrentUser (org.stepik.core.stepik.StepikAuthManager.getCurrentUser)3 IOException (java.io.IOException)2 ClientResponse (org.stepik.api.client.ClientResponse)2 TransportClient (org.stepik.api.client.TransportClient)2