Skip to content
87 changes: 82 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,84 @@
# News API SDK for Java
Coming soon... this is where our officially supported SDK for Java is going to live.
# NewsAPI SDK for Java

***

## Developers... we need you!
We need some help fleshing out this repo. If you're a Java dev with experience building Maven-compatible libraries and web API wrappers, we're offering a reward of $250 to help us get started. For more info please email support@newsapi.org, or dive right in and send us a pull request.
**How to use**

**0**.Download the latest release here : https://github.com/VIad/News-API-java/releases and add the jar to your build path



**1**.Create the client object
```java
NewsApiClient client = new NewsApiClient("YOUR_API_KEY_HERE");
```
**2**.Create the service you require (sources / everything / top headlines)

*Example: get the top headlines from the united states using an asynchronous service*

```java
client.newTopHeadlinesServiceAsync()
.country("us")
.send(result -> {
List<Article> articles = result.viewAsArticles().orElseGet(Collections::emptyList);
//Do some processing on the articles
},
//Error occured, print it
error -> System.err.println(error.getMessage()));
```

**You can also use a non-async flow and store the response in an ```APIResponse``` object**

*Example: get the news sources using a keyword and sort them by popularity*
```java
APIResponse response = client.newSourcesService()
.withKeyword("bulgaria")
.sortBy(SortBy.POPULARITY)
.send();

/*
* viewAs methods return an optional, since it's uncertain what the data type inside APIResponse.getData is
*/
List<NewsSource> newsSources = response.viewAsNewsSources().orElseGet(Collections::emptyList);
//Do some processing on the news sources
```

**Creating your own service**

**1**.Create a class and implement either ```IService``` or ```IAsyncService``` if you want either synchronous or asynchronous execution

*Example:*
```java
public class MyCustomAsyncService implements IAsyncService{
Remainder omitted...
}
```

**2**.Create the service using the ```NewsApiClient``` object

*Example: query all the headlines in english with keyword 'Youtube' from the last 7 days*

```java
client.newCustomAsyncService(new MyCustomAsyncService(), /*Specify an endpoint for your service*/ Endpoint.EVERYTHING)
.withKeyword("Youtube")
.language("en")
.dateRange(DateRange::LAST_7_DAYS)
.send(result -> {
List<Article> articles = result.viewAsArticles().orElseGet(Collections::emptyList);
//Do some processing on the articles
},
//Something went wrong, print the stack trace
Throwable::printStackTrace);
```

Some request methods ```IService``` and ```IAsyncService``` provide

```java
withSources(String... sources) //Sets the lookup sources, such as bbc, abc-news, cnn
withDomains(String... domains) //Sets the lookup domains, such as techcrunch.com, bbc.co.uk
from(Date date) //Filters news from the specified date
to(Date date) //Filters news to the specified date
withKeyword(String keyword) //sets the searched keyword
withCategory(Category category) //Filters the news given a category
```

If you are unsure as to what a function does, you can always refer to the javadoc provided with the binary
49 changes: 49 additions & 0 deletions examples/Asynchronous.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.vlad.newsapi4j.examples;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.vlad.newsapi4j.client.NewsApiClient;
import com.vlad.newsapi4j.model.Article;
import com.vlad.newsapi4j.service.SortBy;

public class Asynchronous {

public static void main(String[] args) {
NewsApiClient client = new NewsApiClient("99827975269246bc91c1780b77e7e008");
/**
* Create the asynchronous request and supply with information
* Get the top headlines in the us today, sort them by date, show the first page(optional it's 1 by default)
*/
client.newTopHeadlinesServiceAsync()
.country("us")
.from(new Date())
.sortBy(SortBy.DATE)
.page(1)
/**
* send method gets called either with the result callback or with the error one
*/
.send(result -> {
/**
* We are here, everything is fine
*/
List<Article> articles = result.viewAsArticles().orElseGet(Collections::emptyList);
/**
* Get all articles whose author starts with the letter 'a', coz why not :D
*/
articles.stream()
// .filter(article -> article.getAuthor().startsWith("A"))
.forEach(System.out::println);

}, /**
* We are here, something went wrong, just print the cause
*/
Throwable::printStackTrace);
/**
* Program flow continues freely
*/
System.out.println("Yay, running concurrently");
}

}
192 changes: 192 additions & 0 deletions examples/Custom.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
package com.vlad.newsapi4j.examples;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.function.Supplier;

import org.json.JSONException;
import org.json.JSONObject;

import com.vlad.newsapi4j.access.APIConnection;
import com.vlad.newsapi4j.client.NewsApiClient;
import com.vlad.newsapi4j.client.ResponseImpl;
import com.vlad.newsapi4j.model.Article;
import com.vlad.newsapi4j.response.APIResponse;
import com.vlad.newsapi4j.service.Endpoint;
import com.vlad.newsapi4j.service.IAsyncService;
import com.vlad.newsapi4j.service.SortBy;
import com.vlad.newsapi4j.utils.Callback;
import com.vlad.newsapi4j.utils.Category;
import com.vlad.newsapi4j.utils.DateRange;
import com.vlad.newsapi4j.utils.LinkBuilder;
import com.vlad.newsapi4j.utils.NewsAPIException;
import com.vlad.newsapi4j.utils.ResponseStatus;

public class Custom {

public static void main(String[] args) {
NewsApiClient client = new NewsApiClient("99827975269246bc91c1780b77e7e008");
client.newCustomAsyncService(new MyCustomAsyncService(), Endpoint.EVERYTHING)
.withKeyword("Youtube")
.language("en")
.pageSize(100)
/**
* I HAD to break convention (All caps methods and all that), just look at how beautiful this looks
*/
.dateRange(DateRange::LAST_7_DAYS)
.send(result -> {
System.out.println("Result matches : " + result.totalResults());

List<Article> articles = result.viewAsArticles().orElseGet(Collections::emptyList);

//Print the articles
articles.forEach(System.out::println);
}, Throwable::printStackTrace);

}

private static class MyCustomAsyncService implements IAsyncService {

private String apiKey;

private Endpoint endpoint;

private LinkBuilder link;

public MyCustomAsyncService() {

}

@Override
public IAsyncService withSources(String... sources) {
link.sources(sources);
return this;
}

@Override
public IAsyncService withDomains(String... domains) {
link.domains(domains);
return this;
}

@Override
public IAsyncService withKeyword(String keyword) {
link.keyword(keyword);
return this;
}

@Override
public IAsyncService withCategory(Category category) {
link.category(category.toLink());
return this;
}

@Override
public IAsyncService language(String lang) {
link.language(lang);
return this;
}

@Override
public IAsyncService sortBy(SortBy sortBy) {
link.sortBy(sortBy);
return this;
}

@Override
public IAsyncService country(String country) {
link.country(country);
return this;
}

@Override
public IAsyncService page(int page) {
link.page(page);
return this;
}

@Override
public IAsyncService to(Date to) {
link.to(to);
return this;
}

@Override
public IAsyncService from(Date date) {
link.from(date);
return this;
}

@Override
public IAsyncService prepare(String apiKey, Endpoint endpoint) {
this.apiKey = apiKey;
this.endpoint = endpoint;
this.link = new LinkBuilder(endpoint);
return this;
}



@Override
public void send(Callback<APIResponse> result, Callback<Throwable> onError) {
new Thread(() -> {
link.finish(apiKey);
String content = new APIConnection(link).getContents();
int totalRes = APIResponse.INFORMATION_UNAVAILABLE;
JSONObject obj = null;
try {
obj = new JSONObject(content);
// System.out.println(obj);
} catch (JSONException e1) {
// throw new NewsAPIException("Something went wrong while parsing json");
e1.printStackTrace();
}

System.out.println(link);
ResponseStatus status = ResponseStatus.OK;
/**
* Returns at least an empty string, not null
*/
try {
if (obj.getString("status").equals("error") || content.equals("")) {
status = ResponseStatus.ERROR;
String message = "";
try {
message = obj.getString("message");
} catch (JSONException e) {
onError.invoke(new NewsAPIException("Something went wrong while parsing json"));
}
onError.invoke(new NewsAPIException(message));
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

if (endpoint != Endpoint.SOURCES)
try {
totalRes = obj.getInt("totalResults");
} catch (JSONException e) {
onError.invoke(new NewsAPIException("Something went wrong while parsing json"));
}
result.invoke(new ResponseImpl(endpoint, content, status, totalRes));
}).start();
}

@Override
public IAsyncService dateRange(Supplier<DateRange> range) {
this.link.from(range.get().getFrom());
this.link.to(range.get().getTo());
return this;
}

@Override
public IAsyncService pageSize(int pageSize) {
this.link.pageSize(pageSize);
return this;
}

}

}
44 changes: 44 additions & 0 deletions examples/Standart.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.vlad.newsapi4j.examples;

import java.util.Collections;
import java.util.List;

import com.vlad.newsapi4j.client.NewsApiClient;
import com.vlad.newsapi4j.model.NewsSource;
import com.vlad.newsapi4j.response.APIResponse;
import com.vlad.newsapi4j.service.SortBy;
import com.vlad.newsapi4j.utils.Category;
import com.vlad.newsapi4j.utils.NewsAPIException;

public class Standart {

public static void main(String[] args) throws NewsAPIException {
NewsApiClient client = new NewsApiClient("99827975269246bc91c1780b77e7e008");
/**
* Wait and receive response from server
*/
APIResponse response = client.newSourcesService()
.withKeyword("bulgaria")
.sortBy(SortBy.POPULARITY)
.send();

System.out.println("Response type : "+response.getResponseType());
System.out.println("Response total results : "+response.totalResults());

/**
* viewAs methods return an optional, since it's uncertain what the data type inside APIResponse.getData is
*/
List<NewsSource> newsSources = response.viewAsNewsSources().orElseGet(Collections::emptyList);

/**
* Let's say we wanted to be extra cool and printed only the news sources that specialize in sports
*/
newsSources.stream()
.filter(nSource -> nSource.getCategory() == Category.Sports)
.forEach(System.out::println);


}


}
Loading