I am trying to use restFB API to get events for several FB companies pages since now until number of days in the future. Somehow it returns nothing. Facebook Graph API returns the results:
https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=AmericanChemicalSociety%2Fevents%3Fsince%3Dnow%26until%3D%2B50%20day&version=v2.7
But it is not working when I am trying to implement it in Java:
private Map<String, ArrayList<JsonObject>> fetchEventsForPeriod(Integer daysAhead) {
Map<String, ArrayList<JsonObject>>mapOfEvents = new HashMap<String, ArrayList<JsonObject>>();
if (this.companiesNamesList.size() == 0) {
getCompanies();
}
for (String companyName : this.companiesNamesList) {
ArrayList<JsonObject>companyEventList = new ArrayList<JsonObject>();
Connection<JsonObject> eventListConnection = this.fbClient.fetchConnection(companyName + "/events",
JsonObject.class, Parameter.with("since", "now"), Parameter.with("until", "+ " + daysAhead + " day"));
while (eventListConnection.hasNext()) {
for (List<JsonObject> eventConnectionPage : eventListConnection) {
for (JsonObject event : eventConnectionPage) {
event.put("univNameId", companyName);
String imageURL = formImageURLFromId(event.get("id").toString());
event.put("imageURL", imageURL);
companyEventList.add(event);
}
}
eventListConnection = this.fbClient.fetchConnectionPage(eventListConnection.getNextPageUrl(), JsonObject.class);
}
mapOfEvents.put(companyName, companyEventList);
}
return mapOfEvents;
}
Basically giving me empty results
restFB is initialized correctly and working for other simpler requests:
private final String appAccessToken = "839761616150633|XMK9PSdojx6uCsOmoGccQC7XMTY";
private FacebookClient fbClient;
#SuppressWarnings("deprecation")
public FacebookRestFB() {
this.companiesList = new JsonArray();
this.companiesNamesList = new ArrayList<String>();
try {
this.fbClient = new DefaultFacebookClient(this.appAccessToken, Version.LATEST);
} catch (FacebookException ex) {
ex.printStackTrace(System.err);
}
}
Update #1
The issue is not yet solved. Any suggestion would be greatly appreciated
Related
I am very new to this concept, and I am trying to create a notification, which can be deleted or modified from server, by looking so I came across "apns-collapse-id". The problem is by setting this using the below code does not change the content of notification, it is just like an extra key added.
I'm trying to understand if i need to make any changes to make it work.
PushNotificationPayload payload = PushNotificationPayload.complex();
payload = new PushNotificationPayload(){
public int getMaximumPayloadSize()
{
return 2048;
}};
payload.addBadge(1);
payload.addSound("default"); //No I18N
payload.addCustomDictionary("rfid","testRfid");
payload.addAlert("test notification2");
JSONObject aps = payload.getPayload().getJSONObject("aps");
JSONObject apsAlert = null;
try
{
apsAlert = aps.getJSONObject("alert");
}
catch(JSONException jse)
{
apsAlert = new JSONObject();
try
{
String apsAlertMsg = aps.getString("alert");
if(apsAlertMsg!=null)
{
apsAlert.put("body",apsAlertMsg);
}
}
catch(JSONException jse1)
{
}
}
aps.put("content-available","1");
aps.put("apns-collapse-id", "12345");
I am working on a project where i am creating a java app for watering plants.The idea to get weather information from online and based on that output should be if we plants require water or not.For weather information,i found an API OpenWeatherMap and i tried to implement it using educational video from YouTube.I don't have past experience with API's. The video i am using is "https://www.youtube.com/watch?v=og5h5ppwXgU" .I tried to implement my program the same way that guy did,but i am not getting any output.It just prints what's in the print statements ,not the actual data.
public static Map<String,Object> jsonToMap(String str){
Map<String,Object> map = new Gson().fromJson(str,new
TypeToken<HashMap<String,Object>> () {}.getType());
return map;
}
public static void main(String[] args) {
String API_KEY = "16 digit Private Key";
String LOCATION = "Los Angeles,CA";
String urlString = "http://api.openweathermap.org/data/2.5/weather?
q=" + LOCATION + "&appid=" + API_KEY + "&units =imperial";
try{
StringBuilder result = new StringBuilder();
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader (conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null){
result.append(line);
}
rd.close();
System.out.println(result);
Map<String, Object > respMap = jsonToMap (result.toString());
Map<String, Object > mainMap = jsonToMap (respMap.get("main").toString());
Map<String, Object > windMap = jsonToMap (respMap.get("wind").toString());
System.out.println("Current Temperature: " + mainMap.get("temp") );
System.out.println("Current Humidity: " + mainMap.get("humidity") );
System.out.println("Wind Speed: " + windMap.get("speed") );
System.out.println("Wind Angle: " + windMap.get("deg") );
}catch (IOException e){
System.out.println(e.getMessage());
}
}
I received errors that gson library doesn't exist ,but after i cretaed my own library in net beans with javadoc,class path and soureces,the problem got resolved ,so i think that correct.Also the API key for openweathermap is also valid.I am just not able to get the code to get online information.
Output :
http://api.openweathermap.org/data/2.5/weatherq=Los Angeles,CA&appid="16 digit Private Key"&units =imperial
Expected Output : Current weather information of LA
Implementation of OpenWeatherMapApi with given latitude and longitude. For Network request Retrofit & Jsonschema2pojo to create model.
Hope this will help.
public void getWeatherDetails(double latitude, double longitude) {
String url = "http://api.openweathermap.org/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url) //This is the only mandatory call on Builder object.
.addConverterFactory(GsonConverterFactory.create()) // Convertor library used to convert response into POJO
.build();
WeatherApiService weatherApiService = retrofit.create(WeatherApiService.class);
weatherApiService.requestWeather(String.valueOf(latitude), String.valueOf(longitude), "metric", "10").enqueue(new UpasargaCallback<WeatherModel>() {
#Override
public void onResponse(Call<WeatherModel> call, Response<WeatherModel> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
if (getView() != null) {
getView().onWeatherApiSuccess(response.body());
}
}
}
}
#Override
public void onFailure(Call<WeatherModel> call, Throwable t) {
if (getView() != null) {
getView().onWeatherApiFailure(String.valueOf(t.getMessage()));
}
}
});
}
WeatherApiService
public interface WeatherApiService {
#Headers("x-api-key: " + AppConstants.WEATHER_API_KEY)
#GET("data/2.5/forecast")
Call<WeatherModel> requestWeather(#Query("lat") String lat,#Query("lon") String lon,#Query("units") String units,#Query("cnt") String count);
}
See WeatherModel.java
I tested the API with your app key in the browser. It was successful. Maybe you should encode your URL. It has a blank space which is a special character.
I am trying to perform a GET request to https://www.cryptocompare.com/api/data/coinlist/, I am grabbing the values "ImageUrl, "Name", and "CoinName". However, I am only receiving about ~230 values with an "ImageUrl". I should be receiving ~1470. This is the exception I receive. I am confused by this since I do a GET request using Postman and it has a value for every "ImageUrl".
org.json.JSONException: No value for ImageUrl
Here is the code for my GET request
#Override
public void GETCoins() {
String url = "https://www.cryptocompare.com/api/data/coinlist/";
Log.d("Debug ", "URL: " + url);
//Run async task to pull weather data. weatherTask.get... forces main thread to wait for this to finish
HTTPAsyncTask coinTask = new HTTPAsyncTask(this);
coinTask.execute(url, "GET");
try {
JSONObject jsonObject = new JSONObject(coinTask.get());
JSONObject obj = new JSONObject(jsonObject.getString("Data"));
Iterator<?> keys = obj.keys();
int i = 0;
while(keys.hasNext() ) {
String key = (String) keys.next();
if(obj.get(key) instanceof JSONObject) {
JSONObject val = new JSONObject(obj.get(key).toString());
String imageUrl = baseImageUrl + val.getString("ImageUrl");
String name = val.getString("Name");
String currency = val.getString("CoinName");
CryptoData data = new CryptoData(i, currency, 0,0, imageUrl, name);
allCurrencyList.add(data);
i++;
}
}
//updateData(jsonObject);
} catch (InterruptedException | JSONException | ExecutionException e) {
e.printStackTrace();
} finally {
Log.d("Debug ", "Coin API is null");
}
}
I want to use Java PayPal SDK to get account history. I tried this simple code:
public void randomDatabaseData() throws SQLException, FileNotFoundException, IOException, PayPalRESTException {
String clientID = "test";
String clientSecret = "test";
String accessToken = null;
try {
Map<String, String> map = new HashMap<String, String>();
map.put("mode", "live");
try {
accessToken = new OAuthTokenCredential(clientID, clientSecret, map).getAccessToken();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(accessToken);
transactionSearch(accessToken);
} catch (Exception e) {
e.printStackTrace();
}
}
public TransactionSearchResponseType transactionSearch(String accessToken) {
TransactionSearchReq transactionSearchReq = new TransactionSearchReq();
TransactionSearchRequestType transactionSearchRequest = new TransactionSearchRequestType(
"2012-12-25T00:00:00+0530");
transactionSearchReq.setTransactionSearchRequest(transactionSearchRequest);
PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();
service.setTokenSecret(accessToken);
TransactionSearchResponseType transactionSearchResponse = null;
try {
transactionSearchResponse = service.transactionSearch(transactionSearchReq);
} catch (Exception e) {
System.out.println("Error Message : " + e.getMessage());
}
if (transactionSearchResponse.getAck().getValue().equalsIgnoreCase("success")) {
Iterator<PaymentTransactionSearchResultType> iterator = transactionSearchResponse
.getPaymentTransactions().iterator();
while (iterator.hasNext()) {
PaymentTransactionSearchResultType searchResult = iterator.next();
System.out.println("Transaction ID : " + searchResult.getTransactionID());
}
} else {
List<ErrorType> errorList = transactionSearchResponse.getErrors();
System.out.println("API Error Message : " + errorList.get(0).getLongMessage());
}
return transactionSearchResponse;
}
But I get his error stack when I run the code:
Error Message : configurationMap cannot be null
java.lang.NullPointerException
at com.crm.web.tickets.GenearateTicketsTest.transactionSearch(GenearateTicketsTest.java:161)
at com.crm.web.tickets.GenearateTicketsTest.randomDatabaseData(GenearateTicketsTest.java:139)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
How I can fix this code? I configure client ID and secret key into PayPal web site but still I get error.
I recommend you using TransactionSearch API to get the payment history based on your search date range.
I wanted to harvest some data on specific apps in
Google play marketplace.
I have used this unofficial API:
https://code.google.com/p/android-market-api/
Here is my code, that basically gets list of apps' names
and try to fetch other data on each app:
public void printAllAppsData(ArrayList<AppHarvestedData> dataWithAppsNamesOnly)
{
MarketSession session = new MarketSession();
session.login("[myGamil]","[myPassword]");
session.getContext().setAndroidId("dead00beef");
final ArrayList<AppHarvestedData> finalResults = new ArrayList<AppHarvestedData>();
for (AppHarvestedData r : dataWithAppsNamesOnly)
{
String query = r.name;
AppsRequest appsRequest = AppsRequest.newBuilder()
.setQuery(query)
.setStartIndex(0).setEntriesCount(10)
//.setCategoryId("SOCIAL")
.setWithExtendedInfo(true)
.build();
session.append(appsRequest, new Callback<AppsResponse>() {
#Override
public void onResult(ResponseContext context, AppsResponse response) {
List<App> apps = response.getAppList();
for (App app : apps) {
AppHarvestedData r = new AppHarvestedData();
r.title = app.getTitle();
r.description = app.getExtendedInfo().getDescription();
String tmp = app.getExtendedInfo().getDownloadsCountText();
tmp = tmp.replace('<',' ').replace('>',' ');
int indexOf = tmp.indexOf("-");
tmp = (indexOf == -1) ? tmp : tmp.substring(0, indexOf);
r.downloads = tmp.trim();
r.rating = app.getRating();
r.version = app.getVersion();
r.userRatingCount = String.valueOf(app.getRatingsCount());
finalResults.add(r);
}
}
});
session.flush();
}
for(AppHarvestedData res : finalResults)
{
System.out.println(res.toString());
}
}
}
Should I realyy call session.flush(); at this point?
all my quesries return empty collection as a result,
even though I see there are some names as input.
It works fine when I send only one hard coded app name as a query.
session.flush() close you session
you should open session for each query. pay attention the user can be locked for few minutes so you should have many users to to those queries.
if you have the AppId you should use that query:
String query = r.name;
AppsRequest appsRequest = AppsRequest.newBuilder()
.setAppId("com.example.android")
.setWithExtendedInfo(true)
.build();
session.append(appsRequest, new Callback<AppsResponse>() {
#Override
public void onResult(ResponseContext context, AppsResponse response) {
List<App> apps = response.getAppList();
for (App app : apps) {
AppHarvestedData r = new AppHarvestedData();
r.title = app.getTitle();
r.description = app.getExtendedInfo().getDescription();
String tmp = app.getExtendedInfo().getDownloadsCountText();
tmp = tmp.replace('<',' ').replace('>',' ');
int indexOf = tmp.indexOf("-");
tmp = (indexOf == -1) ? tmp : tmp.substring(0, indexOf);
r.downloads = tmp.trim();
r.rating = app.getRating();
r.version = app.getVersion();
r.userRatingCount = String.valueOf(app.getRatingsCount());
finalResults.add(r);
}
}
});
session.flush();
}
if you want to download also screenshoot or images you should call this query:
GetImageRequest? imgReq; imgReq = GetImageRequest?.newBuilder().setAppId(appId).setImageUsage(AppImageUsage?.SCREENSHOT).setImageId("0").build();
session.append(imgReq, new Callback<GetImageResponse>() {
#Override public void onResult(ResponseContext? context, GetImageResponse? response) {
Log.d(tag, "------------------> Images response <----------------"); if(response != null) {
try {
//imageDownloader.download(image, holder.image, holder.imageLoader);
Log.d(tag, "Finished downloading screenshot 1...");
} catch(Exception ex) {
ex.printStackTrace();
}
} else {
Log.e(tag, "Response was null");
} Log.d(tag, "------------> End of Images response <------------");
}
});