Example usage for com.google.gson JsonObject getAsJsonPrimitive

List of usage examples for com.google.gson JsonObject getAsJsonPrimitive

Introduction

In this page you can find the example usage for com.google.gson JsonObject getAsJsonPrimitive.

Prototype

public JsonPrimitive getAsJsonPrimitive(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonPrimitive element.

Usage

From source file:com.zaubersoftware.mule.module.github.GithubUnmarshalerImpl.java

License:Apache License

/** @see GithubUnmarshaller#unmarshallCommit(InputStream) */
public final Push unmarshallCommit(final InputStream jsonStream) {
    final JsonObject json = unmarshall(jsonStream);
    Validate.notNull(json);/*from   w  w  w . ja va2  s .  c  o  m*/
    List<Commit> commits = unmarshall(new TypeToken<List<Commit>>() {
    }, json.get("commits"));
    User pusher = unmarshall(new TypeToken<User>() {
    }, json.get("pusher"));
    Repository repository = unmarshall(new TypeToken<Repository>() {
    }, json.get("repository"));
    return new Push(pusher, repository, commits, json.getAsJsonPrimitive("ref").getAsString());
}

From source file:controllers.Rdio.java

License:Open Source License

public static Album retrieveAlbumByRdioId(User user, String album_key) {

    //Logger.info("Retrieving album by ID:" + album_key);
    Album album = Album.find("byRdio_Key", album_key).first();

    if (album != null && album.tracksLoaded == true && album.albumTracks != null
            && album.albumTracks.size() > 1) {
        return album;
    }/*from   w  w  w  .j  a v  a  2  s . c  o  m*/

    // Logger.info("Album not (fully) loaded, loading...");
    WSRequest sign = null;

    String url = endpoint + "/albums/" + album_key + "?include=tracks,images";

    boolean rerequest = false;

    try {
        sign = getConnector(user).sign(user.rdioCreds, WS.url(url), "GET");
    } catch (Exception ex) {

        Logger.error("User " + user.firstName + " had error with credentials");
        Logger.error(ex.toString());
        ex.printStackTrace();
        rerequest = true;
    }

    if (rerequest) {
        setupTokens(user, null, 0);
        try {
            sign = getConnector(user).sign(user.rdioCreds, WS.url(url), "GET");
        } catch (Exception ex) {
            Logger.error(ex.toString());
            ex.printStackTrace();
            return null;
        }
    }

    JsonElement json = sign.get().getJson();

    if (json.toString().equalsIgnoreCase("{\"code\":\"UnauthorizedError\",\"message\":\"Unauthorized\"}")) {
        json = reasssignCatalogAPIAccessToken(user, url, null);
    }

    if (json == null) {
        Logger.error("XZK:001 Null search result for " + user.firstName + " for album key" + album_key);
        return null;
    }

    JsonArray searchArray = json.getAsJsonObject().getAsJsonArray("albums");

    JsonObject searchResult;

    if (searchArray == null) {
        Logger.error("Null searchArray in Rdio.java");
        Logger.info(json.toString());
        return null;
    }
    // Logger.info(searchArray.toString());
    if (searchArray.size() < 1) {
        // @TODO Add flag to album to ignore in future
        Logger.error("Album " + album_key + " is missing from Napster catalog");
        return null;
    }
    searchResult = searchArray.get(0).getAsJsonObject();

    if (album == null) {
        Logger.info("No album at all, creating..0");
        album = new Album();
    }
    if (searchResult.get("name") == null) {
        Logger.error("Strange error:" + searchResult.toString());
        return null;
    }
    album.rdio_key = album_key;
    album.name = searchResult.get("name").getAsString();
    album.artist = searchResult.getAsJsonPrimitive("artistName").getAsString();
    String dateString = searchResult.getAsJsonPrimitive("released").getAsString();
    album.releaseDate = new DateTime(dateString).toDate();
    JsonObject linked = searchResult.getAsJsonObject("linked");
    JsonArray imagesArray = linked.getAsJsonArray("images");
    JsonElement imageElement = imagesArray.get(0);
    album.icon = imageElement.getAsJsonObject().get("url").getAsString();
    album.baseIcon = album.icon;
    album.bigIcon = album.icon;
    JsonArray tracks = linked.getAsJsonArray("tracks");
    Iterator<JsonElement> iterator = tracks.iterator();
    int trackNum = 1;
    album.albumTracks = new ArrayList<Track>();

    int tracksAdded = 0;
    while (iterator.hasNext()) {
        JsonObject trackObj = iterator.next().getAsJsonObject();
        Track track = Track.find("byRdio_Id", trackObj.get("id").getAsString()).first();

        if (track == null) {
            track = new Track();
            RdioHelper.parseNewTrack(user, track, trackObj, true);

        }

        // Make sure track is not already present
        boolean trackPresent = false;

        Iterator iter = album.albumTracks.iterator();
        while (iter.hasNext()) {
            Track albumTrack = (Track) iter.next();
            if (albumTrack.rdio_id == track.rdio_id) {
                trackPresent = true;
                break;
            }
        }

        if (trackPresent) {
            Logger.error("Trying to add a track to an album but it already exists in album!");
        } else {
            tracksAdded++;
            track.album = album;
            album.albumTracks.add(track);
        }
    }

    album.tracksLoaded = true;
    album.save();
    //Logger.info("Saved album " + album.rdio_key + " and added " + tracksAdded + " tracks.");
    return album;

}

From source file:controllers.Rdio.java

License:Open Source License

public static List retrieveAlbumsForArtist(User user, String artist_key) {
    Logger.info("Rdio.retrieveAlbumsForArtist" + artist_key);

    // Now load discography

    ArrayList<Album> albumResults = new ArrayList();
    WSRequest sign;//from  www  .  j av a2  s. co  m

    String url = endpoint + "artists/" + artist_key + "/albums" + "?apikey="
            + Play.configuration.getProperty("rdio.key") + "&limit=200";

    //Logger.info(url);

    try {
        sign = getConnector(user).sign(user.rdioCreds, WS.url(url), "GET");
    } catch (Exception ex) {
        Logger.error(ex.toString());
        ex.printStackTrace();
        return albumResults;
    }

    JsonElement searchResult = sign.get().getJson();
    JsonElement albumsJsonElem = searchResult.getAsJsonObject().get("albums");
    JsonArray albumsArray = albumsJsonElem.getAsJsonArray();

    //Logger.info(searchResult.toString());

    JsonArray discs = albumsArray;

    //Logger.info(discs.toString());

    Iterator<JsonElement> iterator = discs.iterator();

    while (iterator.hasNext()) {
        JsonElement elem = iterator.next();
        JsonObject jsonAlbum = elem.getAsJsonObject();
        String aKey = jsonAlbum.get("id").getAsString();

        Album album = Album.find("byRdio_key", aKey).first();

        if (album != null) {
            //Logger.info("Found album " + album.rdio_key);
            Album foundAlbum = album;

            AlbumRating albumRating = AlbumRating.find("byUserAndRdio_key", user, foundAlbum.rdio_key).first();

            if (albumRating == null) {
                albumRating = new AlbumRating();
                albumRating.rdio_key = foundAlbum.rdio_key;
                albumRating.user = user;
                albumRating.rating = -1L;
                albumRating.artist_name = foundAlbum.artist;
                albumRating.album_name = foundAlbum.name;
                albumRating.numOfRatingStars = LibraryItem.getStarCount(albumRating.rating);
            }

            foundAlbum.album_rating = albumRating;

            albumRating.save();
            albumResults.add(foundAlbum);
            //Logger.info(foundAlbum.name);
            continue;
        } else {
            // Logger.info("No matches for album, so loading album " +artist_key);
            album = new Album();
            album.albumTracks = new ArrayList();
        }

        album.rdio_key = aKey;

        //Logger.info(jsonAlbum.toString());
        album.name = jsonAlbum.get("name").getAsString();

        album.artist = jsonAlbum.getAsJsonPrimitive("artistName").getAsString();
        if (jsonAlbum.get("duration") != null) {
            album.duration = jsonAlbum.get("duration").getAsInt();
        }

        // Grab album detail

        url = endpoint + "albums/" + album.rdio_key + "?include=tracks,images";
        try {
            sign = getConnector(user).sign(user.rdioCreds, WS.url(url), "GET");
            sign.setParameter("apikey", Play.configuration.getProperty("rdio.key"));
            sign.setParameter("limit", "100");
        } catch (Exception ex) {
            Logger.error(ex.toString());
            ex.printStackTrace();
            return albumResults;
        }

        //Logger.info(url + "&apiKey=");
        elem = sign.get().getJson();
        // Logger.info(elem.toString());
        JsonArray albums = elem.getAsJsonObject().getAsJsonArray("albums");

        JsonObject thisAlbum = albums.get(0).getAsJsonObject();
        JsonObject linked = thisAlbum.get("linked").getAsJsonObject();
        JsonArray images = linked.getAsJsonArray("images");
        // Logger.info(thisAlbum.toString());
        album.icon = images.get(0).getAsJsonObject().get("url").getAsString();
        album.bigIcon = album.icon;
        album.baseIcon = album.icon;
        String dateString = thisAlbum.getAsJsonPrimitive("released").getAsString();
        album.releaseDate = new DateTime(dateString).toDate();
        album.duration = new Integer(0);

        JsonArray tracks = linked.getAsJsonArray("tracks").getAsJsonArray();
        Iterator<JsonElement> trackIter = tracks.iterator();
        while (trackIter.hasNext()) {
            JsonObject trackObj = trackIter.next().getAsJsonObject();

            String trackId = trackObj.get("id").getAsString();

            List AXtracks = Track.find("byRdio_id", trackId).fetch();

            Track track = null;
            if (AXtracks.size() > 0) {
                track = (Track) AXtracks.get(0);
            }

            if (track == null) {
                track = new Track();
                //                    track.rdio_id = trackObj.get("id").getAsString(); // the object key of the track
                //                    track.save();

                RdioHelper.parseNewTrack(user, track, trackObj, true);
                track.coverArt = album.icon;

            }
            album.duration += (int) track.duration;

        }

        AlbumRating albumRating = AlbumRating.find("byUserAndRdio_key", user, album.rdio_key).first();

        if (albumRating == null) {
            albumRating = new AlbumRating();
            albumRating.rdio_key = album.rdio_key;
            albumRating.user = user;
            albumRating.rating = -1L;
            albumRating.artist_name = album.artist;
            albumRating.album_name = album.name;
            albumRating.numOfRatingStars = LibraryItem.getStarCount(albumRating.rating);
        }

        // Logger.info("Duration:" + album.duration);

        album = album.save();
        album.album_rating = albumRating;

        albumRating.save();

        albumResults.add(album);
    }
    return albumResults;
}

From source file:de.behrfried.wikianalyzer.wawebapp.server.service.JsonWikiAccess.java

License:Apache License

@Override
public ArticleInfo getArticleInfo(String title) throws ArticleNotExistException {
    try {//from   w ww . jav  a2 s . c o  m
        final int pageid = this.getPageId(title);

        if (pageid == -1) {
            /* article does not exist */
            throw new ArticleNotExistException("Artikel \"" + title + "\" existiert nicht!");
        }

        final List<ArticleInfo.AuthorAndCommits> authorsAndCommits = new ArrayList<ArticleInfo.AuthorAndCommits>();
        final List<ArticleInfo.Revision> revisions = new ArrayList<ArticleInfo.Revision>();
        final List<ArticleInfo.RevsPerDate> revsPerDates = new ArrayList<ArticleInfo.RevsPerDate>();

        int lastRev = 0;

        Date creationDate = null;
        String initialAuthor = null;

        /* get revisions of an article (max 500 are allowed) */
        // http://de.wikipedia.org/w/api.php?action=query&format=xml&prop=revisions&pageids=88112&rvprop=user|ids|timestamp|sha1&rvlimit=10000&rvdiffto=next&rvdir=older
        final Map<String, Integer> authorsAndCommitsTmp = new HashMap<String, Integer>();
        final Map<Long, Integer> revsPerDatesTmp = new HashMap<Long, Integer>();
        while (lastRev != -1) {
            final String response1 = this.requester
                    .getResult(this.convertRequest("action=query&format=json&prop=revisions&rvprop=user|ids"
                            + "|timestamp|comment|size&rvlimit=500&rvdir=newer&rvexcludeuser=127.0.0.1&pageids="
                            + pageid + "&rvstartid=" + lastRev + "&continue="));

            final JsonObject root = this.parser.parse(response1).getAsJsonObject();
            final JsonObject page = root.getAsJsonObject("query").getAsJsonObject("pages")
                    .getAsJsonObject(pageid + "");

            if (!page.has("revisions")) {
                break;
            }

            final JsonArray w = page.getAsJsonArray("revisions");

            /*
             * iterate the revisions
             */
            for (JsonElement obj : w) {

                final JsonObject jsonObj = obj.getAsJsonObject();
                final String author = jsonObj.getAsJsonPrimitive("user").getAsString();
                if (!authorsAndCommitsTmp.containsKey(author)) {
                    authorsAndCommitsTmp.put(author, 1);
                } else {
                    authorsAndCommitsTmp.put(author, authorsAndCommitsTmp.get(author) + 1);
                }

                try {
                    revisions.add(new ArticleInfo.Revision(jsonObj.getAsJsonPrimitive("revid").getAsInt(),
                            jsonObj.getAsJsonPrimitive("parentid").getAsInt(),
                            this.formatter.parse(
                                    jsonObj.getAsJsonPrimitive("timestamp").getAsString().replace('T', '_')),
                            author, jsonObj.getAsJsonPrimitive("comment").getAsString(),
                            jsonObj.getAsJsonPrimitive("size").getAsInt(), 0, false));
                } catch (ParseException e) {
                    this.logger.error(e.getMessage(), e);
                }
            }
            if (lastRev == 0) {
                try {
                    creationDate = this.formatter.parse(w.get(0).getAsJsonObject()
                            .getAsJsonPrimitive("timestamp").getAsString().replace('T', '_'));
                } catch (ParseException e) {
                    this.logger.error(e.getMessage(), e);
                }
                initialAuthor = w.get(0).getAsJsonObject().getAsJsonPrimitive("user").getAsString();
            }
            // lastRev = w.get(w.size() -
            // 1).getAsJsonObject().getAsJsonPrimitive("revid").getAsInt() +
            // 1;
            lastRev = root.has("continue")
                    ? root.getAsJsonObject("continue").getAsJsonPrimitive("rvcontinue").getAsInt()

                    :

                    -1;
        }

        for (Map.Entry<String, Integer> entry : authorsAndCommitsTmp.entrySet()) {
            authorsAndCommits.add(new ArticleInfo.AuthorAndCommits(entry.getKey(), entry.getValue()));
        }
        Collections.sort(authorsAndCommits, new Comparator<ArticleInfo.AuthorAndCommits>() {

            @Override
            public int compare(ArticleInfo.AuthorAndCommits authorAndCommits,
                    ArticleInfo.AuthorAndCommits authorAndCommits2) {
                return authorAndCommits2.getNumOfCommits() - authorAndCommits.getNumOfCommits();
            }
        });

        /* set diffs in revisions and look for edit wars */
        for (int i = 1; i < revisions.size(); i++) {
            revisions.get(i).setDiff(revisions.get(i).getBytes() - revisions.get(i - 1).getBytes());
        }

        Date currentDate = new Date(creationDate.getYear(), creationDate.getMonth(), creationDate.getDate());
        while (currentDate.before(revisions.get(revisions.size() - 1).getTimestamp())) {
            revsPerDatesTmp.put(currentDate.getTime(), 0);
            currentDate = new Date(currentDate.getTime() + 86400000);
        }
        for (final ArticleInfo.Revision revision : revisions) {
            final Date key = new Date(revision.getTimestamp().getYear(), revision.getTimestamp().getMonth(),
                    revision.getTimestamp().getDate());
            long time = key.getTime();
            try {
                if (!revsPerDatesTmp.containsKey(time)) {
                    time -= 3600000;
                }
                if (!revsPerDatesTmp.containsKey(time)) {
                    time += 7200000;
                }
                revsPerDatesTmp.put(time, revsPerDatesTmp.get(time) + 1);
            } catch (Exception e) {
                this.logger.error(e.getMessage());
            }

        }
        for (Map.Entry<Long, Integer> entry : revsPerDatesTmp.entrySet()) {
            revsPerDates.add(new ArticleInfo.RevsPerDate(new Date(entry.getKey()), entry.getValue()));
        }
        Collections.sort(revsPerDates, new Comparator<ArticleInfo.RevsPerDate>() {

            @Override
            public int compare(ArticleInfo.RevsPerDate revsPerDate, ArticleInfo.RevsPerDate revsPerDate2) {
                return revsPerDate.getDate().compareTo(revsPerDate2.getDate());
            }
        });

        /*
         * find edit wars
         */
        final List<ArticleInfo.EditWar> editWars = new ArrayList<ArticleInfo.EditWar>();
        final List<ArticleInfo.Revision> revertedRevs = this.getRevertedRevisions(revisions);
        for (int i = 0; i < revertedRevs.size() - 4; i++) {
            final ArticleInfo.Revision revision = revertedRevs.get(i);
            int startI = i;
            while (i < revertedRevs.size() - 4 && revertedRevs.get(i + 4).getTimestamp().getTime()
                    - revertedRevs.get(i).getTimestamp().getTime() < 100000000) {
                i += 4;
            }
            if (i != startI) {
                final StringBuilder usersStrBldr = new StringBuilder();
                final Map<String, Integer> usersMap = new HashMap<String, Integer>();
                for (int j = startI; j <= i; j++) {
                    final String author = revertedRevs.get(j).getAuthor();
                    if (!usersMap.containsKey(author)) {
                        usersMap.put(author, 0);
                    }
                    usersMap.put(author, usersMap.get(author) + 1);

                }
                for (final Map.Entry<String, Integer> entry : usersMap.entrySet()) {
                    usersStrBldr.append(entry.getKey());
                    usersStrBldr.append(" (");
                    usersStrBldr.append(entry.getValue());
                    usersStrBldr.append("); ");
                }
                editWars.add(new ArticleInfo.EditWar(revertedRevs.get(startI).getTimestamp(),
                        revertedRevs.get(i).getTimestamp(),
                        usersStrBldr.toString().substring(0, usersStrBldr.length() - 2)));
            }
        }

        /* get similiar articles */
        // http://de.wikipedia.org/w/api.php?action=query&format=xml&list=search&srsearch=Maus&srlimit=500
        final String similar = this.requester.getResult(
                this.convertRequest("action=query&format=json&list=search&srlimit=500&srsearch=" + title));
        final JsonArray search = this.parser.parse(similar).getAsJsonObject().getAsJsonObject("query")
                .getAsJsonArray("search");

        final List<ArticleInfo.SimilarArticle> similarArticles = new ArrayList<ArticleInfo.SimilarArticle>(
                search.size());

        for (final JsonElement obj : search) {
            final JsonObject jsonObj = obj.getAsJsonObject();
            final String simTitle = jsonObj.getAsJsonPrimitive("title").getAsString();
            final int simPageid = this.getPageId(simTitle);

            if (simPageid == pageid) {
                continue;
            }

            /* get categories */
            final String categories = this.getCategories(simPageid);

            /* get creation date */
            Date simCreationDate = null;
            final String creationDateStr = this.requester.getResult(this.convertRequest(
                    "action=query&format=json&prop=revisions&rvprop=timestamp&rvlimit=1&rvdir=newer&pageids="
                            + simPageid));
            try {
                simCreationDate = this.formatter.parse(this.parser.parse(creationDateStr).getAsJsonObject()
                        .getAsJsonObject("query").getAsJsonObject("pages").getAsJsonObject(simPageid + "")
                        .getAsJsonArray("revisions").get(0).getAsJsonObject().getAsJsonPrimitive("timestamp")
                        .getAsString().replace('T', '_'));
            } catch (ParseException e) {
                this.logger.error(e.getMessage(), e);
            }

            similarArticles.add(new ArticleInfo.SimilarArticle(simTitle, categories, simCreationDate));

        }

        /* get number of images */
        final String imageStr = this.requester
                .getResult(this.convertRequest("action=query&format=json&prop=images&pageids=" + pageid));
        final JsonObject images = this.parser.parse(imageStr).getAsJsonObject().getAsJsonObject("query")
                .getAsJsonObject("pages").getAsJsonObject(pageid + "");
        int numOfImages = 0;
        if (images.has("images")) {
            numOfImages = images.getAsJsonArray("images").size();
        }

        /*
         * get categories
         */
        final String categoriesStr = this.requester.getResult(this.convertRequest(
                "action=query&format=json&prop=categories&clprop=timestamp&cllimit=500&pageids=" + pageid));
        final JsonObject categoriesJsonObj = this.parser.parse(categoriesStr).getAsJsonObject()
                .getAsJsonObject("query").getAsJsonObject("pages").getAsJsonObject(pageid + "");

        final List<ArticleInfo.Category> categoryList = new ArrayList<ArticleInfo.Category>();
        if (categoriesJsonObj.has("categories")) {
            final JsonArray categoriesJsonArr = categoriesJsonObj.getAsJsonArray("categories");

            for (final JsonElement catElem : categoriesJsonArr) {
                final JsonObject catJson = catElem.getAsJsonObject();
                try {

                    categoryList.add(new ArticleInfo.Category(
                            catJson.getAsJsonPrimitive("title").getAsString().replaceAll("Kategorie:", "")
                                    .replaceAll("Wikipedia:", ""),
                            this.formatter.parse(
                                    catJson.getAsJsonPrimitive("timestamp").getAsString().replace('T', '_'))));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }

        return new ArticleInfo(pageid, title, initialAuthor, creationDate,
                "http://de.wikipedia.org/wiki/" + title.replaceAll(" ", "_"),
                "http://de.wikipedia.org/wiki/Benutzer:" + initialAuthor, numOfImages,
                this.getCategories(pageid), revisions.get(revisions.size() - 1).getBytes(), authorsAndCommits,
                revisions, revsPerDates, editWars, similarArticles, categoryList);

    } catch (Exception e) {
        this.logger.error(e.getMessage(), e);
    }
    return null;
}

From source file:de.behrfried.wikianalyzer.wawebapp.server.service.JsonWikiAccess.java

License:Apache License

@Override
public UserInfo getUserInfo(String userName) throws UserNotExistException {
    try {/*from ww  w  .  ja  v a 2 s .  c  o m*/
        final int userid = this.getUserID(userName);

        if (userid == -1) {
            /* article does not exist */
            throw new UserNotExistException("Nutzer \"" + userid + "\" existiert nicht!");
        }

        final List<UserInfo.ArticleEdited> categoryEdited = new ArrayList<UserInfo.ArticleEdited>();

        boolean isBot = false;
        Date signInDate = null;
        int lastUserCommits = 0;

        final String response1 = this.requester
                .getResult(this.convertRequest("action=query&format=json&list=users&ususers=" + userName
                        + "&usprop=editcount|registration|blockinfo|groups"));

        final JsonObject root = this.parser.parse(response1).getAsJsonObject();
        final JsonObject user = root.getAsJsonObject("query").getAsJsonArray("users").get(0).getAsJsonObject();

        if (user.has("groups")) {
            final JsonArray groupsJsonArr = user.getAsJsonArray("groups");
            for (JsonElement jsonElement : groupsJsonArr) {
                if ("bot".equals(jsonElement.getAsJsonPrimitive().getAsString())) {
                    isBot = true;
                    break;
                }
            }
        }

        final int editcount = user.getAsJsonPrimitive("editcount").getAsInt();

        final boolean blocked = user.has("blockid");

        Map<Tuple2<Integer, String>, Tuple2<Integer, Integer>> comparableRevisions = new HashMap<Tuple2<Integer, String>, Tuple2<Integer, Integer>>();
        final Map<String, Integer> commitsPerCategory = new HashMap<String, Integer>();
        final List<ArticleEdited> articleEditeds = new ArrayList<UserInfo.ArticleEdited>();
        int numOfComments = 0;
        int numOfReverts = 0;
        int numOfUserDiscussion = 0;
        int numofSelfDiscussion = 0;

        final String userArticles = this.requester
                .getResult(this.convertRequest("action=query&format=json&list=usercontribs&ucdir=older&ucuser="
                        + userName + "&uclimit=500&ucprop=ids|sizediff|title|flags|comment|timestamp"));
        final JsonObject rootObj = this.parser.parse(userArticles).getAsJsonObject();

        final JsonArray articlesArticle = rootObj.getAsJsonObject("query").getAsJsonArray("usercontribs");
        lastUserCommits += articlesArticle.size();

        for (JsonElement elm : articlesArticle) {
            final JsonObject tmpObj = elm.getAsJsonObject();

            final Tuple2<Integer, String> key = Tuple.create(tmpObj.getAsJsonPrimitive("pageid").getAsInt(),
                    tmpObj.getAsJsonPrimitive("title").getAsString());

            if (key.getItem2().startsWith("Benutzer Diskussion:")) {
                if (key.getItem2().endsWith(userName)) {
                    numofSelfDiscussion++;
                } else {
                    numOfUserDiscussion++;
                }
            }

            final int sizediff = tmpObj.has("sizediff") ? tmpObj.getAsJsonPrimitive("sizediff").getAsInt() : 0;
            final String comment = tmpObj.has("comment") ? tmpObj.getAsJsonPrimitive("comment").getAsString()
                    : "";
            if (!comment.isEmpty()) {
                numOfComments++;
                if (this.isRevert(comment)) {
                    numOfReverts++;
                }
            }

            if (!comparableRevisions.containsKey(key)) {
                comparableRevisions.put(key, Tuple.create(0, 0));
            }
            comparableRevisions.put(key, Tuple.create(comparableRevisions.get(key).getItem1() + 1,
                    comparableRevisions.get(key).getItem2() + sizediff));
        }

        final Set<String> categorySet = new HashSet<String>();
        for (final Map.Entry<Tuple2<Integer, String>, Tuple2<Integer, Integer>> entry : comparableRevisions
                .entrySet()) {

            final String categories = this.getCategories(entry.getKey().getItem1());
            categoryEdited.add(new ArticleEdited(entry.getKey().getItem2(), entry.getValue().getItem1(),
                    entry.getValue().getItem2(), categories));

            final String[] catArr = categories.split(";");
            for (final String cat : catArr) {
                categorySet.add(cat.trim());

                if (!commitsPerCategory.containsKey(cat.trim())) {
                    commitsPerCategory.put(cat.trim(), entry.getValue().getItem1());
                } else {
                    commitsPerCategory.put(cat.trim(),
                            (commitsPerCategory.get(cat.trim()) + entry.getValue().getItem1()));
                }
            }
        }

        try {
            signInDate = this.formatter
                    .parse(user.getAsJsonPrimitive("registration").getAsString().replace('T', '_'));

        } catch (Exception e) {
            this.logger.warn(userName + " has no sign in date!");
            final String signInRsp = this.requester.getResult(
                    this.convertRequest("action=query&format=json&list=usercontribs&ucdir=newer&ucuser="
                            + userName + "&uclimit=1&ucprop=timestamp"));
            final JsonObject aa = this.parser.parse(userArticles).getAsJsonObject();
            final JsonArray aaa = aa.getAsJsonObject("query").getAsJsonArray("usercontribs");
            if (aaa.size() > 0) {
                // get the date of the first user contrib
                signInDate = this.formatter.parse(aaa.get(aaa.size() - 1).getAsJsonObject()
                        .getAsJsonPrimitive("timestamp").getAsString().replace('T', '_'));
            }
        }

        final StringBuilder categoriesStrBuilder = new StringBuilder();
        categoriesStrBuilder.append("(");
        categoriesStrBuilder.append(categorySet.size());
        categoriesStrBuilder.append(") = ");
        for (final String cat : categorySet) {
            categoriesStrBuilder.append(cat);
            categoriesStrBuilder.append("; ");
        }

        /*
         * get categories
         */
        final String categoryCommits = categoriesStrBuilder.toString().substring(0,
                categoriesStrBuilder.length() - 2);

        /*
         * get reputation
         */
        final Object[] reps = this.calcReputation(userName, lastUserCommits, blocked);
        final double reputation = (Double) reps[0];
        final String abuses = (String) reps[1];
        final int abuseCount = (Integer) reps[2];

        /*
         * user classes
         */
        String userclassNumOfCommits = "Gott";
        if (lastUserCommits < 100) {
            userclassNumOfCommits = "Rookie";
        } else if (lastUserCommits < 1000) {
            userclassNumOfCommits = "Fortgeschrittener";
        } else if (lastUserCommits < 10000) {
            userclassNumOfCommits = "Profi";
        } else if (lastUserCommits < 100000) {
            userclassNumOfCommits = "Master";
        }

        String userclassAvgCommits = "\"nicht bewertbar\"";
        double avgCommits = 0;
        if (signInDate != null) {
            avgCommits = editcount / ((System.currentTimeMillis() - signInDate.getTime()) / 86400000);
            if (avgCommits == 0.0) {
                userclassAvgCommits = "Schlafmtze";
            } else if (avgCommits < 1.0d) {
                userclassAvgCommits = "Gelegenheitssurfer";
            } else if (avgCommits < 5.0d) {
                userclassAvgCommits = "Durchschnittsuser";
            } else if (avgCommits < 15.0d) {
                userclassAvgCommits = "Vielschreiber";
            } else {
                userclassAvgCommits = "Dauergast";
            }
        }

        String userclassRevert = "\"nicht bewertbar\"";
        String userclassComment = "\"nicht bewertbar\"";

        if (lastUserCommits > 0) {
            final double revertCommitRelation = (double) numOfReverts / lastUserCommits;
            userclassRevert = "Spielverderber";
            if (revertCommitRelation < 0.01) {
                userclassRevert = "Ein-Auge-Zudrcker";
            } else if (revertCommitRelation < 0.1) {
                userclassRevert = "Gelegenheitsspieer";
            } else if (revertCommitRelation < 0.2) {
                userclassRevert = "Sturrkopf";
            } else if (revertCommitRelation < 0.5) {
                userclassRevert = "Kontrolleur";
            }

            final double commentCommitRelation = (double) numOfComments / lastUserCommits;
            userclassComment = "Saubermann";
            if (commentCommitRelation < 0.1) {
                userclassComment = "Dokuhasser";
            } else if (commentCommitRelation < 0.5) {
                userclassComment = "Ab und zu vergesslich";
            } else if (commentCommitRelation < 0.8) {
                userclassComment = "Ordnungshter";
            }
        }

        String userDiscussion = "Sehr oft";
        if (numOfUserDiscussion == 0) {
            userDiscussion = "Nie";
        } else if (numOfUserDiscussion < 3) {
            userDiscussion = "Selten";
        } else if (numOfUserDiscussion < 10) {
            userDiscussion = "Gelegentlich";
        } else if (numOfUserDiscussion < 20) {
            userDiscussion = "Oft";
        }

        String selfDiscussion = "Sehr oft";
        if (numofSelfDiscussion == 0) {
            selfDiscussion = "Nie";
        } else if (numofSelfDiscussion < 10) {
            selfDiscussion = "Selten";
        } else if (numofSelfDiscussion < 30) {
            selfDiscussion = "Gelegentlich";
        } else if (numofSelfDiscussion < 100) {
            selfDiscussion = "Oft";
        }

        return new UserInfo(userid, userName, editcount, categoryCommits, avgCommits, signInDate, reputation,
                categoryEdited, blocked, userclassNumOfCommits, userclassAvgCommits, userclassRevert,
                userclassComment, userDiscussion, selfDiscussion, commitsPerCategory, abuses, abuseCount,
                numOfReverts, numOfComments, numOfUserDiscussion, numofSelfDiscussion, isBot);
    } catch (Exception e) {
        this.logger.error(e.getMessage(), e);
    }
    return null;
}

From source file:de.behrfried.wikianalyzer.wawebapp.server.service.JsonWikiAccess.java

License:Apache License

private Object[] calcReputation(String userName, int lastUserCommits, boolean blocked) {
    int abuseCnt = 0;
    String abuses = "";
    int abuseCount = 0;
    double abuseCntFactor = 1.0d;
    String tmpDate = "";

    do {//from w w  w .ja v a  2  s  .c o  m
        final String abuselogStr = this.requester
                .getResult(this.convertRequest("action=query&format=json&list=abuselog&afllimit=500&afluser="
                        + userName + "&aflstart=" + tmpDate));

        final JsonObject abuseRoot = this.parser.parse(abuselogStr).getAsJsonObject();
        final JsonArray abuseJsnonArr = abuseRoot.getAsJsonObject("query").getAsJsonArray("abuselog");
        int warnCount = 0, disallowCount = 0, blockCount = 0;
        for (final JsonElement jElem : abuseJsnonArr) {
            final JsonObject jObj = jElem.getAsJsonObject();
            final String abuseResult = jObj.getAsJsonPrimitive("result").getAsString();

            abuseCnt += 1;
            if (abuseResult.contains("warn")) {
                warnCount += 5;
                abuseCntFactor = (abuseCntFactor + 5.0d) / abuseCnt;
            }
            if (abuseResult.contains("disallow")) {
                disallowCount += 10;
                ;
                abuseCntFactor = (abuseCntFactor + 10.0d) / abuseCnt;
            }
            if (abuseResult.contains("block")) {
                blockCount += 15;
                abuseCntFactor = (abuseCntFactor + 15.0d) / abuseCnt;
            }
        }
        abuseCount = warnCount + disallowCount + blockCount;
        abuses = "(" + abuseCount + "): " + "warn(" + warnCount + "); disallow(" + disallowCount + "); block("
                + blockCount + ");";
        tmpDate = "";
        if (abuseRoot.has("query-continue")) {
            tmpDate = abuseRoot.getAsJsonObject("query-continue").getAsJsonObject("abuselog")
                    .getAsJsonPrimitive("aflstart").getAsString();
        }

    } while (!tmpDate.isEmpty());

    this.logger.info("AbuseCntfactor: " + abuseCntFactor);
    double reputation = 1.0d - (1.0d / ((1.0d + lastUserCommits) / (1.0d + abuseCnt))) / (1 / abuseCntFactor);
    if (blocked) {
        reputation = 0;
    }
    if (reputation > 1) {
        reputation = 1;
    } else if (reputation < 0) {
        reputation = 0;
    }
    return new Object[] { new Double(reputation), abuses, abuseCnt };
}

From source file:de.behrfried.wikianalyzer.wawebapp.server.service.JsonWikiAccess.java

License:Apache License

private int getUserID(final String userName) {
    final String response = this.requester
            .getResult(this.convertRequest("action=query&format=json&list=users&ususers=" + userName));
    this.logger.debug("Response: " + response);
    JsonObject obj = this.parser.parse(response).getAsJsonObject().getAsJsonObject("query")
            .getAsJsonArray("users").get(0).getAsJsonObject();
    if (obj.has("userid")) {
        return obj.getAsJsonPrimitive("userid").getAsInt();
    }//from  w  w  w .j a va 2 s  . c o  m
    return -1;
}

From source file:de.fabianonline.telegram_backup.Utils.java

License:Open Source License

static Version getNewestVersion() {
    try {/*from  ww w .  ja v  a2  s.com*/
        String data_url = "https://api.github.com/repos/fabianonline/telegram_backup/releases";
        logger.debug("Requesting current release info from {}", data_url);
        String json = IOUtils.toString(new URL(data_url));
        JsonParser parser = new JsonParser();
        JsonElement root_elm = parser.parse(json);
        if (root_elm.isJsonArray()) {
            JsonArray root = root_elm.getAsJsonArray();
            JsonObject newest_version = null;
            for (JsonElement e : root)
                if (e.isJsonObject()) {
                    JsonObject version = e.getAsJsonObject();
                    if (version.getAsJsonPrimitive("prerelease").getAsBoolean() == false) {
                        newest_version = version;
                        break;
                    }
                }
            if (newest_version == null)
                return null;
            String new_v = newest_version.getAsJsonPrimitive("tag_name").getAsString();
            logger.debug("Found current release version {}", new_v);
            String cur_v = Config.APP_APPVER;

            int result = compareVersions(cur_v, new_v);

            return new Version(new_v, newest_version.getAsJsonPrimitive("html_url").getAsString(),
                    newest_version.getAsJsonPrimitive("body").getAsString(), result == VERSION_2_NEWER);
        }
        return null;
    } catch (Exception e) {
        return null;
    }
}

From source file:edu.illinois.cs.cogcomp.core.utilities.JsonSerializer.java

License:Open Source License

private static String readString(String name, JsonObject obj) {
    return obj.getAsJsonPrimitive(name).getAsString();
}

From source file:edu.washington.iam.tools.netact.NetactDNSVerifier.java

License:Apache License

/**
 * Test if a user has ownership of a domain
 *
 * @param id user's uwnetid//from w  w w  .j  a v  a2  s.co  m
 * @param domain to test
 * @param return list of owners (can be null)
 */

public boolean isOwner(String dns, String id, List<String> owners) throws DNSVerifyException {

    boolean isOwner = false;
    if (id == null)
        id = "";
    log.debug("looking for owner (" + id + ") in " + dns);

    try {
        String[] urls = { hostUrl, domainUrl };
        for (String url : urls) {
            String respString = webClient.simpleRestGet(url + dns);
            // log.debug("got: " + respString);

            JsonParser parser = new JsonParser();
            JsonElement ele = parser.parse(respString);
            if (ele.isJsonObject()) {
                JsonObject resp = ele.getAsJsonObject();
                if (resp.get("table").isJsonObject()) {
                    JsonObject tbl = resp.getAsJsonObject("table");
                    if (tbl.get("row").isJsonArray()) {
                        JsonArray ids = tbl.getAsJsonArray("row");
                        for (int i = 0; i < ids.size(); i++) {
                            JsonObject idi = ids.get(i).getAsJsonObject();
                            JsonPrimitive oidu = idi.getAsJsonPrimitive("uwnetid");
                            if (oidu == null)
                                continue;
                            String oid = oidu.getAsString();
                            if (oid.equals(id)) {
                                if (owners == null)
                                    return true; // done
                                isOwner = true;
                            }
                            if (owners != null && !owners.contains(oid))
                                owners.add(oid);
                        }
                    } else {
                        String oid = tbl.getAsJsonObject("row").getAsJsonPrimitive("uwnetid").getAsString();
                        if (oid.equals(id)) {
                            if (owners == null)
                                return true; // done
                            isOwner = true;
                        }
                        if (owners != null && !owners.contains(oid))
                            owners.add(oid);
                    }
                }
            }
        }

    } catch (Exception e) {
        log.debug("netact dns lookup error: " + e);
        throw new DNSVerifyException(e.getMessage() + " : " + e.getCause());
    }

    // do substrings too
    dns = dns.replaceFirst("[^\\.]+\\.", "");
    // log.debug("do substrings: " + dns);
    int p = dns.indexOf(".");
    if (p > 0) {
        if (isOwner(dns, id, owners)) {
            if (owners == null)
                return true; // done
            isOwner = true;
        }
    }
    return isOwner;
}