33

The StackWrap4J 1.0.1 jar is now available! (See the changelog)

Sample Code / Screen Shot

The following code snippet was used to test the wrapper in the Android emulator:

TextView text = (TextView)findViewById(R.id.output);
StackWrapper stackWrap = new StackOverflow();

String displayText = null;

try {
    Stats stats = stackWrap.getStats();
    displayText = "Stack Overflow Statistics";
    displayText += "\nTotal Questions: " + stats.getTotalQuestions();
    displayText += "\nTotal Unanswered: " + stats.getTotalUnanswered();
    displayText += "\nTotal Answers: " + stats.getTotalAnswers();
    displayText += "\nTotal Comments: " + stats.getTotalComments();
    displayText += "\nTotal Votes: " + stats.getTotalVotes();
    displayText += "\nTotal Users: " + stats.getTotalUsers();
}
catch(Exception e){
    displayText = e.getMessage();
}

text.setText(displayText);

Android Example

About

StackWrap4J is a Java wrapper for the Stack Exchange API. It is designed to be easy to use, and intuitive to learn while providing the full functionality of the API.

License

StackWrap4J is available under the MIT license.

Download

StackWrap4J

Platform

StackWrap4J was built using Java 1.5 and tested on Sun's JVM. It should run on any implementation of the JVM (1.5 or later). It's also been tested on the Android emulator. It also runs under the Google App Engine.

Code

You can download the code from our SVN repository hosted on SourceForge.

Documentation for the code is also available on the SourceForge site.

Authors

Bill Cruise
Justin Nelson

Contact

Please feel free to leave feedback here in the Answers section or on the StackWrap4J project discussion forum.

Alternatively:

Bill is available at: lizard.bill (at) gmail.com
Justin can be reached at: jjnguy13 (at) gmail.com

Future

Currently we are focusing on adding more tests and fixing bugs. We are also working on adding serialization so that our objects can be easily persisted, and throttling so that users of our library don't have to worry about breaking the terms of use of the API.

Notes

The latest build was tested against version 1.0 of the API on July 28th.

17
  • 3
    Please let us know what you think of the API. We want to know what rocks, and what sucks.
    – jjnguy
    Commented Jun 21, 2010 at 3:28
  • Also, any feedback on the code would be greatly appreciated. However, we would prefer that you bash us through email rather than this public place.
    – jjnguy
    Commented Jun 21, 2010 at 4:24
  • Sorry guys. Wish I used Java so I could try this out :( Commented Jun 25, 2010 at 4:51
  • @George, no problem. If you hear of anyone in need of a Java wrapper for the Stack Exchange API, send em our way.
    – jjnguy
    Commented Jun 25, 2010 at 5:05
  • @jjnguy: Sure will - and if someone you know needs a good PHP wrapper... please send 'em to me :) Commented Jun 25, 2010 at 5:22
  • @George, it's a deal.
    – jjnguy
    Commented Jun 25, 2010 at 13:19
  • I realise that this an unreasonable request, but is there any chance of hosting this on GitHub instead of/as well as SourceForge? The fork/pull model makes it easier for external people to submit proposed contributions.
    – Dan Dyer
    Commented Jan 10, 2011 at 18:30
  • 2
    is there any way to have StackWrap4J available as a maven artifact in a known repository (one known by jarvana, as an example) ? This way, it would be really handy to use it anywhere ...
    – Riduidel
    Commented Mar 15, 2011 at 16:36
  • Does this work with superuser and serverfault?
    – user6662
    Commented May 20, 2011 at 12:58
  • @Mat: Yeah, I've tested it with all the Trilogy sites, including Meta. It should work with any of the sites that have an active API route. Commented May 20, 2011 at 13:03
  • Are there any plans for the SE 2.0 API?
    – Jack
    Commented Apr 25, 2012 at 2:05
  • @Jack If I can find the time I'll update it, but I don't have any immediate plans to, so I don't know when that will be. Commented Apr 25, 2012 at 15:57
  • Ok - I'm about to graduate in May with my CS degree so maybe I'll have some time to look at it (after finals).
    – Jack
    Commented Apr 26, 2012 at 5:15
  • @BilltheLizard, is this still maintained?
    – aioobe
    Commented Apr 9, 2015 at 15:37
  • @aioobe No, not as far as I know. Commented Apr 9, 2015 at 15:43

8 Answers 8

5

The following is a quickly thrown together method that will return the accepted answer percentage of the user with the given ID.

Note: This is using some code that will be available in the next release. Notice how it dramatically reduces complexity, and the length of code.

public static double getAcceptedAnswerPercentage(StackWrapper sw, int userId)
        throws JSONException, IOException, ParameterNotSetException {
    int acceptedCount = 0;
    int answerCount = 0;
    List<Answer> answers = new AnswerFromUserList(sw, (AnswerQuery) new AnswerQuery()
            .setIds(userId));
    for (Answer a : answers) {
        answerCount++;
        if (a.isIsAccepted())
            acceptedCount++;
    }
    return acceptedCount / (double) answerCount;
}

Are you tired of manually paging queries? We were too. Introducing the AutoFetchList!!

The class AutoFetchList will automatically pull the next pages as needed. Looks like a list, acts like a list...must be a list. Just throw it a Query and it will take care of the paging for you.

There is a partial implementation of this in the datastructures package of the latest release. It is partially functional. But, the code above will run and work.

5

Search Examples

Questions

You can search for questions with StackWrap4J by instantiating a StackWrapper then calling the search method. Before calling search, you have to create a SearchQuery, which is a simple parameter object.

StackWrapper so = new StackOverflow();

SearchQuery query = new SearchQuery();
query.setTags("swing");
query.setNotTagged("java");
query.setPageSize(10);

List<Question> questions = so.search(query);
System.out.println("Questions: " + questions.size());

for(Question q : questions) {
    System.out.println("Id " + q.getPostId() + ":\t" + q.getTitle());
    System.out.println("Tags: " + q.getTags());
}

If you don't set the tags, nottagged, or intitle parameter in the SearchQuery, the search method will throw an exception.

If you need to modify your search, you can reuse the same query. If I decide I want to add the [scala] tag to the search I did above, I could just add the tag and call search again.

query.addTag("scala");
questions = so.search(query);
...

Users

You can do a search for users with similar names using the listUsers method and a UserQuery object. You just have to set the filter in the query.

UserQuery uquery = new UserQuery();
uquery.setFilter("Bill");
uquery.setPageSize(10);
List<User> bills = so.listUsers(uquery);

for(User u : bills) {
    System.out.println("Username: " + u.getDisplayName());
}
2
  • Question about "users": how can I get the other metadata returned in a users API call: like "total", "pagesize", etc? (did I just totally miss this getter in the javadoc?)
    – rascher
    Commented Feb 6, 2011 at 0:40
  • 1
    @rascher: Those will be in the MetadataList returned by the methods in StackWrapper. It looks like we made a mistake and didn't expose that data, because those methods return List, which you'll have to cast. Commented Feb 6, 2011 at 1:01
4

Proxy Example

Sometimes you need to use a Proxy to access the internet. At my company we need to. StackWrap4J provides the ability to specify a Proxy server to rout connections through.

Below is a short code sample that configures the proxy, and then pulls every answer that I (2598) have given.

Proxy prox = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
            "proxy.my.company.com", 80));
HttpClient.proxyServer = prox;
StackWrapper sw = new StackOverflow();
AnswerQuery query = new AnswerQuery();
query.setPageSize(PageQuery.MAX_PAGE_SIZE).setIds(2598);
List<Answer> allAnswers = new AnswerFromUserList(sw, query);

It is as simple as setting the public proxyServer property of the HttpClient class. That proxy will be used continually unless you set proxyServer to null.

3

Timeout Example

If you find that a response is taking too long for your app, you can set a timeout on the request.

If a timeout occurs, a java.net.SocketTimeoutException is thrown. The default timeout is 0 which means infinite, so you don't have to worry about the exception if you never set a timeout.

StackWrapper sw = new StackOverflow();
// Set the timeout globally (1ms is way too short)
// But you will get to see the exception generated
HttpClient.setTimeout(1); // You shouldn't use 1, it will always timeout
sw.getUserById(2598);

So, instead of waiting for the response forever, you can time it out, and ask the user to try again later.

(This is very similar to how you would set the proxy server like in the proxy example)

2

Version Updates:

Version 1.0.1 [download]

  • Added serialization to StackWrapper, all entities, and all queries
  • Url encoded user entered String parameters (i.e. " " => "%20")
  • Set followRedirect on each connection instance instead of JVM-wide. (This was causing problems with Google App Engine)
1

Thanks for this, I was able to get an Android proof-of-concept working very quickly.

I wanted to build the latest version from SVN because it has some changes that aren't in the most recent binary but there doesn't appear to be a build script in the repository. The structure seems straightforward, so I could write my own build.xml, but maybe you have something already that you use?

One minor suggestion I have is that it would be more convenient if the API docs were on the web somewhere rather, particularly for people who just want to browse to get an idea of the structure and capabilities of the library.

2
  • Thanks for your interest! To build the project, I just put it in Eclipse. And I know Bill uses Netbeans. I will look into putting the documentation in a more accessible place.
    – jjnguy
    Commented Dec 27, 2010 at 19:52
  • @jjnguy I use IntelliJ but I just created a quick-and-dirty Ant script to build it, seemed to do the job fine. I just wanted the badge count stuff that has been added in SVN.
    – Dan Dyer
    Commented Dec 28, 2010 at 19:01
0

Are there any plans to support the use of your library in GWT? I'm getting some security-related errors trying to get it to work. See http://pastebin.com/SJTAHP0B

11
  • Is it GWT or Google App Engine that's throwing the exception? I've not used either, but it looks like the security permission error is coming from GAE. Is there somewhere that you can configure permissions? Commented Jul 25, 2010 at 13:23
  • @Catchwa, I think I found the error. It looks like an easy fix. Stand by for confirmation.
    – jjnguy
    Commented Jul 26, 2010 at 1:02
  • 1
    @Catchwa: It does look there was a fix that we could apply on our end. Can you try version 1.0.1 and let us know how that works for you? We appreciate the feedback. Commented Jul 26, 2010 at 2:49
  • Also, check out our change log answer to see what else is new.
    – jjnguy
    Commented Jul 26, 2010 at 3:00
  • Thanks guys for the prompt response! Yes, it's not GWT-related, more AppEngine related I think. Unfortunately, I've got another (different) exception trace. I won't have any time to look at it for another 24 hours, but I've put the stack trace at pastebin.com/DmARfX3L
    – Catchwa
    Commented Jul 26, 2010 at 12:40
  • @Catchwa, I think I know what is causing this... I may have to set up an environment like this to test in now. We would like to support the Google AppEngine.
    – jjnguy
    Commented Jul 26, 2010 at 12:58
  • @Catchwa I believe I fixed the error, but I have no way of testing it right now. If you could let us know if the newest version on SourceForge is working that would be awesome. I didn't update the version number, but I did upload a new file. Just re-download v1.0.1.
    – jjnguy
    Commented Jul 26, 2010 at 13:06
  • @jjnguy We're getting there! Here's the next stack trace. pastebin.com/3uKfjnJ6
    – Catchwa
    Commented Jul 27, 2010 at 8:28
  • @Catchwa, this one has me stumped. I will be installing the GAE tonight if I have time. My goal is to get you up and running before the contest. I will see if I can find the root cause of the error.
    – jjnguy
    Commented Jul 27, 2010 at 12:09
  • @Bill, check out the newest stack trace.
    – jjnguy
    Commented Jul 27, 2010 at 12:09
  • Hi i am making an android app.i read some documentation and the function and URLs to call to access data. but i dont know how to login a user in stackoverflow.please help provide some guideline how to login a user using stackauth in my app
    – user7074
    Commented Jul 2, 2011 at 18:09
0

Can I authenticate my android app via your library? If not, please add that if you can.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .