Search in sources :

Example 1 with InternalServerErrorException

use of net.runelite.http.service.util.exception.InternalServerErrorException in project runelite by runelite.

the class TwitterService method getTweets.

private List<FeedItem> getTweets(boolean hasRetried) throws IOException {
    if (token == null) {
        updateToken();
    }
    HttpUrl url = LIST_STATUSES_URL.newBuilder().addQueryParameter("list_id", listId).addQueryParameter("count", "15").addQueryParameter("include_entities", "false").build();
    Request request = new Request.Builder().url(url).header("Authorization", "Bearer " + token).build();
    try (Response response = RuneLiteAPI.CLIENT.newCall(request).execute()) {
        if (!response.isSuccessful()) {
            switch(HttpStatus.valueOf(response.code())) {
                case BAD_REQUEST:
                case UNAUTHORIZED:
                    updateToken();
                    if (!hasRetried) {
                        return getTweets(true);
                    }
                    throw new InternalServerErrorException("Could not auth to Twitter after trying once: " + response.message());
                default:
                    throw new IOException("Error getting Twitter list: " + response.message());
            }
        }
        InputStream in = response.body().byteStream();
        Type listType = new TypeToken<List<TwitterStatusesResponseItem>>() {
        }.getType();
        List<TwitterStatusesResponseItem> statusesResponse = RuneLiteAPI.GSON.fromJson(new InputStreamReader(in), listType);
        List<FeedItem> items = new ArrayList<>();
        for (TwitterStatusesResponseItem i : statusesResponse) {
            items.add(new FeedItem(FeedItemType.TWEET, i.getUser().getProfileImageUrl(), i.getUser().getScreenName(), i.getText().replace("\n\n", " ").replaceAll("\n", " "), "https://twitter.com/statuses/" + i.getId(), getTimestampFromSnowflake(i.getId())));
        }
        return items;
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Request(okhttp3.Request) ArrayList(java.util.ArrayList) IOException(java.io.IOException) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) FeedItemType(net.runelite.http.api.feed.FeedItemType) Type(java.lang.reflect.Type) FeedItem(net.runelite.http.api.feed.FeedItem) InternalServerErrorException(net.runelite.http.service.util.exception.InternalServerErrorException) ArrayList(java.util.ArrayList) List(java.util.List)

Example 2 with InternalServerErrorException

use of net.runelite.http.service.util.exception.InternalServerErrorException in project runelite by runelite.

the class XteaService method submit.

@RequestMapping(method = POST)
public void submit(@RequestBody XteaRequest xteaRequest) {
    try (Connection con = sql2o.beginTransaction()) {
        CacheEntry cache = cacheService.findMostRecent();
        if (cache == null) {
            throw new InternalServerErrorException("No most recent cache");
        }
        Query query = con.createQuery("insert into xtea (region, rev, key1, key2, key3, key4) " + "values (:region, :rev, :key1, :key2, :key3, :key4)");
        for (XteaKey key : xteaRequest.getKeys()) {
            int region = key.getRegion();
            int[] keys = key.getKeys();
            XteaEntry xteaEntry = findLatestXtea(con, region);
            if (keys.length != 4) {
                throw new IllegalArgumentException("Key length must be 4");
            }
            // already have these?
            if (xteaEntry != null && xteaEntry.getKey1() == keys[0] && xteaEntry.getKey2() == keys[1] && xteaEntry.getKey3() == keys[2] && xteaEntry.getKey4() == keys[3]) {
                continue;
            }
            if (!checkKeys(cache, region, keys)) {
                continue;
            }
            query.addParameter("region", region).addParameter("rev", xteaRequest.getRevision()).addParameter("key1", keys[0]).addParameter("key2", keys[1]).addParameter("key3", keys[2]).addParameter("key4", keys[3]).addToBatch();
        }
        query.executeBatch();
        con.commit();
    }
}
Also used : Query(org.sql2o.Query) XteaKey(net.runelite.http.api.xtea.XteaKey) Connection(org.sql2o.Connection) InternalServerErrorException(net.runelite.http.service.util.exception.InternalServerErrorException) CacheEntry(net.runelite.http.service.cache.beans.CacheEntry) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 3 with InternalServerErrorException

use of net.runelite.http.service.util.exception.InternalServerErrorException in project runelite by runelite.

the class OSRSNewsService method getNews.

public List<FeedItem> getNews() throws IOException {
    Request request = new Request.Builder().url(RSS_URL).build();
    try (Response response = RuneLiteAPI.CLIENT.newCall(request).execute()) {
        if (!response.isSuccessful()) {
            throw new IOException("Error getting OSRS news: " + response.message());
        }
        try {
            InputStream in = response.body().byteStream();
            Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
            Element documentElement = document.getDocumentElement();
            NodeList documentItems = documentElement.getElementsByTagName("item");
            List<FeedItem> items = new ArrayList<>();
            for (int i = 0; i < documentItems.getLength(); i++) {
                Node item = documentItems.item(i);
                NodeList children = item.getChildNodes();
                String title = null;
                String description = null;
                String link = null;
                long timestamp = -1;
                for (int j = 0; j < children.getLength(); j++) {
                    Node childItem = children.item(j);
                    String nodeName = childItem.getNodeName();
                    switch(nodeName) {
                        case "title":
                            title = childItem.getTextContent();
                            break;
                        case "description":
                            description = childItem.getTextContent().replace("\n", "").trim();
                            break;
                        case "link":
                            link = childItem.getTextContent();
                            break;
                        case "pubDate":
                            timestamp = PUB_DATE_FORMAT.parse(childItem.getTextContent()).getTime();
                            break;
                    }
                }
                if (title == null || description == null || link == null || timestamp == -1) {
                    throw new InternalServerErrorException("Failed to find title, description, link and/or timestamp in the OSRS RSS feed");
                }
                items.add(new FeedItem(FeedItemType.OSRS_NEWS, title, description, link, timestamp));
            }
            return items;
        } catch (ParserConfigurationException | SAXException | ParseException e) {
            throw new InternalServerErrorException("Failed to parse OSRS news: " + e.getMessage());
        }
    }
}
Also used : InputStream(java.io.InputStream) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Request(okhttp3.Request) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) Response(okhttp3.Response) FeedItem(net.runelite.http.api.feed.FeedItem) InternalServerErrorException(net.runelite.http.service.util.exception.InternalServerErrorException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) ParseException(java.text.ParseException)

Example 4 with InternalServerErrorException

use of net.runelite.http.service.util.exception.InternalServerErrorException in project runelite by runelite.

the class TwitterService method updateToken.

private void updateToken() throws IOException {
    String encodedCredentials = Base64.getEncoder().encodeToString(credentials.getBytes());
    Request request = new Request.Builder().url(AUTH_URL).header("Authorization", "Basic " + encodedCredentials).post(new FormBody.Builder().add("grant_type", "client_credentials").build()).build();
    try (Response response = RuneLiteAPI.CLIENT.newCall(request).execute()) {
        if (!response.isSuccessful()) {
            throw new IOException("Error authing to Twitter: " + response.message());
        }
        InputStream in = response.body().byteStream();
        TwitterOAuth2TokenResponse tokenResponse = RuneLiteAPI.GSON.fromJson(new InputStreamReader(in), TwitterOAuth2TokenResponse.class);
        if (!tokenResponse.getTokenType().equals("bearer")) {
            throw new InternalServerErrorException("Returned token was not a bearer token");
        }
        if (tokenResponse.getToken() == null) {
            throw new InternalServerErrorException("Returned token was null");
        }
        token = tokenResponse.getToken();
    }
}
Also used : Response(okhttp3.Response) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Request(okhttp3.Request) InternalServerErrorException(net.runelite.http.service.util.exception.InternalServerErrorException) IOException(java.io.IOException)

Example 5 with InternalServerErrorException

use of net.runelite.http.service.util.exception.InternalServerErrorException in project runelite by runelite.

the class HiscoreService method lookupUsername.

public HiscoreResultBuilder lookupUsername(String username, HttpUrl hiscoreUrl) throws IOException {
    HttpUrl url = hiscoreUrl.newBuilder().addQueryParameter("player", username).build();
    log.debug("Built URL {}", url);
    Request okrequest = new Request.Builder().url(url).build();
    String responseStr;
    try (Response okresponse = RuneLiteAPI.CLIENT.newCall(okrequest).execute()) {
        if (!okresponse.isSuccessful()) {
            switch(HttpStatus.valueOf(okresponse.code())) {
                case NOT_FOUND:
                    throw new NotFoundException();
                default:
                    throw new InternalServerErrorException("Error retrieving data from Jagex Hiscores: " + okresponse.message());
            }
        }
        responseStr = okresponse.body().string();
    }
    CSVParser parser = CSVParser.parse(responseStr, CSVFormat.DEFAULT);
    HiscoreResultBuilder hiscoreBuilder = new HiscoreResultBuilder();
    hiscoreBuilder.setPlayer(username);
    int count = 0;
    for (CSVRecord record : parser.getRecords()) {
        if (count++ >= HiscoreSkill.values().length) {
            log.warn("Jagex Hiscore API returned unexpected data");
            // rest is other things?
            break;
        }
        // rank, level, experience
        int rank = Integer.parseInt(record.get(0));
        int level = Integer.parseInt(record.get(1));
        // items that are not skills do not have an experience parameter
        long experience = -1;
        if (record.size() == 3) {
            experience = Long.parseLong(record.get(2));
        }
        Skill skill = new Skill(rank, level, experience);
        hiscoreBuilder.setNextSkill(skill);
    }
    return hiscoreBuilder;
}
Also used : Request(okhttp3.Request) NotFoundException(net.runelite.http.service.util.exception.NotFoundException) HttpUrl(okhttp3.HttpUrl) HiscoreEndpoint(net.runelite.http.api.hiscore.HiscoreEndpoint) Response(okhttp3.Response) Skill(net.runelite.http.api.hiscore.Skill) HiscoreSkill(net.runelite.http.api.hiscore.HiscoreSkill) CSVParser(org.apache.commons.csv.CSVParser) InternalServerErrorException(net.runelite.http.service.util.exception.InternalServerErrorException) CSVRecord(org.apache.commons.csv.CSVRecord)

Aggregations

InternalServerErrorException (net.runelite.http.service.util.exception.InternalServerErrorException)7 IOException (java.io.IOException)5 Request (okhttp3.Request)5 Response (okhttp3.Response)5 InputStream (java.io.InputStream)4 ArrayList (java.util.ArrayList)3 FeedItem (net.runelite.http.api.feed.FeedItem)3 InputStreamReader (java.io.InputStreamReader)2 ParseException (java.text.ParseException)2 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)2 HttpUrl (okhttp3.HttpUrl)2 Document (org.w3c.dom.Document)2 Element (org.w3c.dom.Element)2 Node (org.w3c.dom.Node)2 NodeList (org.w3c.dom.NodeList)2 SAXException (org.xml.sax.SAXException)2 Type (java.lang.reflect.Type)1 List (java.util.List)1 FeedItemType (net.runelite.http.api.feed.FeedItemType)1 HiscoreEndpoint (net.runelite.http.api.hiscore.HiscoreEndpoint)1