com.github.thebigs.nzbmatrixapi.NZBMatrixApi.java Source code

Java tutorial

Introduction

Here is the source code for com.github.thebigs.nzbmatrixapi.NZBMatrixApi.java

Source

/**
 * NZBMatrixLib provides an intuitive java interface library to interact with the API provided by (http://www.nzbmatrix.com)
 *
 * The author(s) of NZBMatrixLib are in NO WAY associated with (http://nzbmatrix.com) or its affiliates
 *
 * If you  would like to contribute to this library, find us at (https://github.com/TheBigS/NZBMatrixLib)
 *
 *   Copyright (C) 2010  Steven King
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.github.thebigs.nzbmatrixapi;

import java.io.IOException;
import java.net.URLEncoder;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import com.github.thebigs.nzbmatrixapi.parser.AccountDetailsParser;
import com.github.thebigs.nzbmatrixapi.parser.BookmarkParser;
import com.github.thebigs.nzbmatrixapi.parser.DirectDownloadParser;
import com.github.thebigs.nzbmatrixapi.parser.Parser;
import com.github.thebigs.nzbmatrixapi.parser.PostDetailsParser;
import com.github.thebigs.nzbmatrixapi.parser.SearchResultsParser;
import com.github.thebigs.nzbmatrixapi.response.AccountDetailsResponse;
import com.github.thebigs.nzbmatrixapi.response.BookmarkResponse;
import com.github.thebigs.nzbmatrixapi.response.DirectDownloadResponse;
import com.github.thebigs.nzbmatrixapi.response.PostDetailsResponse;
import com.github.thebigs.nzbmatrixapi.response.Response;
import com.github.thebigs.nzbmatrixapi.response.SearchResultsResponse;
import com.google.common.base.Preconditions;

/**
 * This is the client-facing API class. You should be interacting with this class directly.
 * See the 'examples' directory for an example for each functionality supported here.
 *
 * The following text about the NzbMatrix.com API is from (http://nzbmatrix.com/api-info.php):
 *
 * API KEY INFORMATION:
 * Generating your own unique API Key is very simple, simply visit "Your Account" and click [Generate New API Key].
 * An API Key will then be generated and displayed in the API area under Current API Key:
 * Your unique API Key is locked to your username, no one else will have access to it.
 * If for some reason you think its been used elsewhere, stolen, lost or you just want it changed then simply generate a new key.
 * Generating a new API Key will render the old one useless.
 * The API key is a 32 character string containing letters and numbers only.
 * It is an algorithm of several aspects of your account details and random generated keys. It is impossible to replicate.
 *
 *
 * API RATE LIMITS:
 * For several reasons we have a "Total API Requests" limitation and a "Daily Download Limitation".
 * These couters are updated every 15 minutes.
 * Details on your useage can be found in the HTTP Headers, or using a request to the ACCOUNT API (This will use a API request).
 *
 * The current rate limits are as follows:
 * TOTAL API REQUEST PER HOUR: 100
 * DAILY DOWNLOAD LIMITATION: 150
 *
 * Also note there is a 15 minute delay in data becoming on the API system from the main site,
 * so the latest postings will be delayed slightly. This is due to database mirroring.
 */
public class NZBMatrixApi {

    // credentials needed for every request
    ApiCredentials credentials;
    // indicates whether or not request should be made over ssl
    boolean useHttps = true;

    /**
     * Initializes this api object with the credentials needed for every call to nzbmatrix.com's API
     *
     * @param userName  user's name (e.g. 'foobarUser')
     * @param apiKey    user's unique api key (e.g. '838d43ef5cb5346d83520f6886adf935')
     */
    public NZBMatrixApi(final ApiCredentials credentials) {
        Preconditions.checkNotNull(credentials);
        this.credentials = credentials;
    }

    /**
     * Initializes this api object with the credentials needed for every call to nzbmatrix.com's API
     *
     * @param userName  user's name (e.g. 'foobarUser')
     * @param apiKey    user's unique api key (e.g. '838d43ef5cb5346d83520f6886adf935')
     */
    public NZBMatrixApi(final String userName, final String apiKey) {
        Preconditions.checkNotNull(userName, "User Name cannot be null");
        Preconditions.checkNotNull(apiKey, "API Key cannot be null");
        credentials = new ApiCredentials(userName, apiKey);
    }

    /**
     * @return  Returns true if this api interface will use ssl connections for queries, false if it wont. Default is true.
     */
    public boolean isUseHttps() {
        return useHttps;
    }

    /**
     * @param useHttps  Indicates whether or not we should use ssl for requests to the NzbMatrix API.
     */
    public void setUseHttps(final boolean useHttps) {
        this.useHttps = useHttps;
    }

    /**
     * Returns the post details for a given postId. postId numbers are generally found by first performing a search.
     *
     * @see http://nzbmatrix.com/api-info.php  [Section: Post Details API]
     *
     * @param postId
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     * @throws NZBMatrixApiException
     */
    public PostDetailsResponse getPostDetails(final int postId)
            throws ClientProtocolException, IOException, NZBMatrixApiException {
        /*
         * http://api.nzbmatrix.com/v1.1/details.php?username={USERNAME}&apikey={APIKEY}&id={NZBID}
         */
        final StringBuilder uri = new StringBuilder(65);
        uri.append(useHttps ? "https://" : "http://");
        uri.append("api.nzbmatrix.com/v1.1/details.php");
        uri.append("?").append("username").append("=").append(credentials.userName);
        uri.append("&").append("apikey").append("=").append(credentials.apiKey);
        uri.append("&").append("id").append("=").append(postId);

        return (PostDetailsResponse) doApiCall(uri.toString(), new PostDetailsParser());
    }

    /**
     * Returns details about your user account. Including your accountId, Api Usage and account level
     *
     * @see http://nzbmatrix.com/api-info.php  [Section: Account API]
     *
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     * @throws NZBMatrixApiException
     */
    public AccountDetailsResponse getAccountInfo()
            throws ClientProtocolException, IOException, NZBMatrixApiException {
        /*
         * http://api.nzbmatrix.com/v1.1/account.php?username={USERNAME}&apikey={APIKEY}
         */
        final StringBuilder uri = new StringBuilder(65);
        uri.append(useHttps ? "https://" : "http://");
        uri.append("api.nzbmatrix.com/v1.1/account.php");
        uri.append("?").append("username").append("=").append(credentials.userName);
        uri.append("&").append("apikey").append("=").append(credentials.apiKey);

        return (AccountDetailsResponse) doApiCall(uri.toString(), new AccountDetailsParser());
    }

    /**
     * Performs a search against the nzbmatrix database for the given search term.
     * Currently this will only return at most 15 results and there is no way to 'page' through results. Hopefully they will
     * add this functionality in the future.
     *
     * There is no need to url encode the query, that will be done automatically.
     *
     * @see http://nzbmatrix.com/api-info.php  [Section: Search API]
     *
     * @param searchQuery
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     * @throws NZBMatrixApiException
     */
    public SearchResultsResponse getSearchResults(final String searchQuery)
            throws ClientProtocolException, IOException, NZBMatrixApiException {
        Preconditions.checkNotNull(searchQuery);

        /*
         * http://api.nzbmatrix.com/v1.1/search.php?&username={USERNAME}&apikey={APIKEY}&search={TERM}
         */
        final StringBuilder uri = new StringBuilder(65);
        uri.append(useHttps ? "https://" : "http://");
        uri.append("api.nzbmatrix.com/v1.1/search.php");
        uri.append("?").append("username").append("=").append(credentials.userName);
        uri.append("&").append("apikey").append("=").append(credentials.apiKey);
        uri.append("&").append("search").append("=").append(URLEncoder.encode(searchQuery, "UTF-8"));

        return (SearchResultsResponse) doApiCall(uri.toString(), new SearchResultsParser());
    }

    /**
     * Downloads the nzbFile contents for a given postId.
     *
     * @see 'example/GetDirectDownload.java' for an example on how to save the nzb file.
     * @see http://nzbmatrix.com/api-info.php  [Section: Direct Download API]
     *
     * @param postId
     * @return  Response containing the file contents of the nzbFile
     * @throws ClientProtocolException
     * @throws IOException
     * @throws NZBMatrixApiException
     */
    public DirectDownloadResponse getDirectDownload(final int postId)
            throws ClientProtocolException, IOException, NZBMatrixApiException {
        Preconditions.checkArgument(postId >= 0);

        /*
         * http://api.nzbmatrix.com/v1.1/download.php?&username={USERNAME}&apikey={APIKEY}&id={postId}
         */
        final StringBuilder uri = new StringBuilder(65);
        uri.append(useHttps ? "https://" : "http://");
        uri.append("api.nzbmatrix.com/v1.1/download.php");
        uri.append("?").append("username").append("=").append(credentials.userName);
        uri.append("&").append("apikey").append("=").append(credentials.apiKey);
        uri.append("&").append("id").append("=").append(postId);

        // get the post details so we can suggest a file name (@see DirectDownloadResponse.getSuggestedFileName())
        final PostDetailsResponse postDetails = getPostDetails(postId);

        // do the api call and retrun the response
        return (DirectDownloadResponse) doApiCall(uri.toString(), new DirectDownloadParser(postDetails));
    }

    /**
     * Adds a bookmark on the given postId. This bookmark will show up in your Account's rss feed.
     *
     * @see http://nzbmatrix.com/api-info.php  [Section: Bookmarks API]
     *
     * @param postId
     * @return  response to the operation. Will be one of ('bookmark_not_found' or 'bookmark_added' or 'bookmark_added_already')
     * @throws ClientProtocolException
     * @throws IOException
     * @throws NZBMatrixApiException
     */
    public BookmarkResponse addBookmark(final int postId)
            throws ClientProtocolException, IOException, NZBMatrixApiException {
        /*
         * http://api.nzbmatrix.com/v1.1/bookmarks.php?&username={USERNAME}&apikey={APIKEY}id={NZBID}&action={ACTION}
         */
        final StringBuilder uri = new StringBuilder(65);
        uri.append(useHttps ? "https://" : "http://");
        uri.append("api.nzbmatrix.com/v1.1/bookmarks.php");
        uri.append("?").append("username").append("=").append(credentials.userName);
        uri.append("&").append("apikey").append("=").append(credentials.apiKey);
        uri.append("&").append("id").append("=").append(postId);
        uri.append("&").append("action").append("=").append("add");

        return (BookmarkResponse) doApiCall(uri.toString(), new BookmarkParser());
    }

    /**
     * Removes a bookmark on the given postId. This bookmark will be removed in your Account's rss feed.
     *
     * @see http://nzbmatrix.com/api-info.php  [Section: Bookmarks API]
     *
     * @param postId    postId to remove a bookmark for.
     * @return  response to the operation. Will be one of ('bookmark_not_found' or 'bookmark_removed')
     * @throws ClientProtocolException
     * @throws IOException
     * @throws NZBMatrixApiException
     */
    public BookmarkResponse removeBookmark(final int postId)
            throws ClientProtocolException, IOException, NZBMatrixApiException {
        /*
         * http://api.nzbmatrix.com/v1.1/bookmarks.php?&username={USERNAME}&apikey={APIKEY}id={NZBID}&action={ACTION}
         */
        final StringBuilder uri = new StringBuilder(65);
        uri.append(useHttps ? "https://" : "http://");
        uri.append("api.nzbmatrix.com/v1.1/bookmarks.php");
        uri.append("?").append("username").append("=").append(credentials.userName);
        uri.append("&").append("apikey").append("=").append(credentials.apiKey);
        uri.append("&").append("id").append("=").append(postId);
        uri.append("&").append("action").append("=").append("remove");

        return (BookmarkResponse) doApiCall(uri.toString(), new BookmarkParser());
    }

    /**
     * Does the hevy lifting of making the http GET request to the nzbmatrix api using apache's http client libraries
     *
     * @param uri       web address to access (including params)
     * @param parser    parser to call when a response is received
     *
     * @return  returns a subclass of Response, this should be casted to the type of response returned by the ResponseParser given
     *
     * @throws ClientProtocolException
     * @throws IOException
     * @throws NZBMatrixApiException
     */
    private Response doApiCall(final String uri, final Parser parser)
            throws ClientProtocolException, IOException, NZBMatrixApiException {
        final HttpClient httpclient = new DefaultHttpClient();

        final HttpGet httpget = new HttpGet(uri);

        // uncomment this to see all of the request queries as they are submitted.
        //        System.out.println("executing request " + httpget.getURI());

        // Create a response handler
        final ResponseHandler<String> responseHandler = new BasicResponseHandler();
        final String responseBody = httpclient.execute(httpget, responseHandler);

        httpclient.getConnectionManager().shutdown();
        return parser.parseResponse(responseBody);
    }
}