403 : Daily Limit for Unauthenticated Use Exceeded youtube api v3 java - java

I Know this question has been asked multiple times, but I couldn't find one working for me.
Basically I am trying to get a youtube video basic info which I get the proper result for that but then when I trigger to get the comments of that video the error pops out saying:
There was a service error: 403 : Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.
My code:
public String getyoutubeitemfull_details(String URI) throws SQLException, IOException{
try {
YouTube youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("APP_ID").build();
String apiKey = "API Key";
YouTube.Videos.List listVideosRequest = youtube.videos().list("statistics");
listVideosRequest.setId("qUvPzjSWMSM");
listVideosRequest.setKey(apiKey);
VideoListResponse listResponse = listVideosRequest.execute();
Video video = listResponse.getItems().get(0);
BigInteger viewCount = video.getStatistics().getViewCount();
BigInteger Likes = video.getStatistics().getLikeCount();
BigInteger DisLikes = video.getStatistics().getDislikeCount();
BigInteger Comments = video.getStatistics().getCommentCount();
System.out.println("[View Count] " + viewCount);
System.out.println("[Likes] " + Likes);
System.out.println("[Dislikes] " + DisLikes);
System.out.println("[Comments] " + Comments);
CommentThreadListResponse videoCommentsListResponse = youtube.commentThreads()
.list("snippet").setVideoId("qUvPzjSWMSM").setMaxResults(50l).setTextFormat("plainText").execute();
List<CommentThread> videoComments = videoCommentsListResponse.getItems();
for (CommentThread videoComment : videoComments) {
CommentSnippet snippet = videoComment.getSnippet().getTopLevelComment().getSnippet();
System.out.println(" - Author: " + snippet.getAuthorDisplayName());
System.out.println(" - Comment: " + snippet.getTextDisplay());
System.out.println("\n-------------------------------------------------------------\n");
}
} catch (GoogleJsonResponseException e) {
System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
} catch (IOException e) {
System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
FYI: So much of question that I have been through so far talk about adding listVideosRequest.setKey(apiKey); which I have it done. I also Have enable OAuth 2.0 enabled in my google console.

Thanks to #DalmTo for throwing to its direction.
Basically Api Key doesn't have priviledges to retrieve comments and things like that. for deep priviledges I had to use Oauth, which basically is being created the same was as API Key but in Oauth you receive a client_secrets.json file containing: client secret, client ID and etc...
Then you call that in you code.
Note: Their is verious ways of calling you client_secrets.json file but it depends on your need.
My way: Reader clientSecretReader = new InputStreamReader(
new FileInputStream("/home/Downloads/src/client_secrets.json"));

Related

Softlayer - list of servers which are powered on

The following java code lists all the bare metal servers in softlayer for a specific SL account and filters for servers which are powered on (e.g. powerState='on'.
public void listServers(Account.Service service, ApiClient client) throws Exception {
service.withMask().hardware().fullyQualifiedDomainName().primaryIpAddress();
service.withMask().hardware().hardwareStatus();
service.withMask().hardware().id();
Account account = service.getObject();
//
// list of softlayer servers for the client account
//
for (Hardware hardware : account.getHardware()) {
String hostname = hardware.getFullyQualifiedDomainName();
String hardwareStatus = (hardware.getHardwareStatus() == null) ? null : hardware.getHardwareStatus().getStatus();
Long serverId = hardware.getId();
String powerState = null;
if (serverId != null) {
Hardware.Service hardwareService = Hardware.service(client, serverId);
hardwareService.setMask("mask[serverPowerState");
try {
powerState = hardwareService.getServerPowerState();
} catch (Exception ex) {
System.out.println("Error, cannot get powerState, hostname=" + hostname + ", msg=" + ex.getMessage());
}
}
System.out.println("Hostname=" + hostname + ", hwStatus=" + hardwareStatus + ", powerState=" + powerState);
}
}
Code seems to work, but for at least one of the servers, it fails on the call to hardwareService.getServerPowerState()
"Unable to establish IPMI v2 / RMCP+ session".
Any ideas why this is failing ?

How to fetch comments with most likes or replies on a YouTube video using YouTube Data API?

So far, I have managed to collect first 100 comments on a video using YouTube Data API in my Java program shown below.
public class CommentHandling {
/**
* Define a global instance of a YouTube object, which will be used to make
* YouTube Data API requests.
*/
private static YouTube youtube;
/**
* List, reply to comment threads; list, update, moderate, mark and delete
* replies.
*
* #param args command line args (not used).
*/
public static void main(String[] args) {
// This OAuth 2.0 access scope allows for full read/write access to the
// authenticated user's account and requires requests to use an SSL connection.
List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.force-ssl");
try {
// Authorize the request.
Credential credential = Auth.authorize(scopes, "commentthreads");
// This object is used to make YouTube Data API requests.
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
.setApplicationName("youtube-cmdline-commentthreads-sample").build();
// Prompt the user for the ID of a video to comment on.
// Retrieve the video ID that the user is commenting to.
String videoId = getVideoId();
System.out.println("You chose " + videoId + " to subscribe.");
// All the available methods are used in sequence just for the sake
// of an example.
// Call the YouTube Data API's commentThreads.list method to
// retrieve video comment threads.
CommentThreadListResponse videoCommentsListResponse = youtube.commentThreads()
.list("snippet, replies").setVideoId(videoId)
.setMaxResults(new Long(100)).setTextFormat("html").execute();
List<CommentThread> videoComments = videoCommentsListResponse.getItems();
if (videoComments.isEmpty()) {
System.out.println("Can't get video comments.");
} else {
// Print information from the API response.
System.out
.println("\n================== Returned Video Comments ==================\n");
for (CommentThread videoComment : videoComments) {
CommentSnippet snippet = videoComment.getSnippet().getTopLevelComment()
.getSnippet();
System.out.println(" - Author: " + snippet.getAuthorDisplayName());
System.out.println(" - Comment: " + snippet.getTextDisplay());
System.out
.println("\n-------------------------------------------------------------\n");
}
}
} catch (GoogleJsonResponseException e) {
System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode()
+ " : " + e.getDetails().getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
e.printStackTrace();
} catch (Throwable t) {
System.err.println("Throwable: " + t.getMessage());
t.printStackTrace();
}
}
/*
* Prompt the user to enter a video ID. Then return the ID.
*/
private static String getVideoId() throws IOException {
String videoId = "";
System.out.print("Please enter a video id: ");
BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
videoId = bReader.readLine();
return videoId;
}
But I am interested in collecting the top comments (either by likes or replies on a comment) on a video. These are the comments which are usually on the first page of the video when sorted by using "Top comments" filter.
Any help would be highly appreciated.

Why my code only get tweets in latest 1 or 2 minutes in Twitter4j

Said that Twitter API will give tweets in 7 days, but when i tried to implement my code using java, i just get the result of tweets less than enough. It just covered tweets in 1 until 2 minutes. The number of data or tweets is far from my need. Is that any error on my code?
here my code:
public class TweetPublic {
public static void main(String[] args) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true).setOAuthConsumerKey("key")
.setOAuthConsumerSecret("key")
.setOAuthAccessToken("key")
.setOAuthAccessTokenSecret("key");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
FileOutputStream fos;
DataOutputStream dos;
try {
File file = new File("C:/Users/Charlie Siagian/Desktop/data.doc");
fos = new FileOutputStream(file);
dos = new DataOutputStream(fos);
try {
Query query = new Query("(#hadoop) OR (#bigdata) OR (#data) OR (#datamining) "
+ "OR (#mapreduce) OR (#flume) OR (#semanticanalytic) OR (#dataset) OR (#rdbms)"
+ "OR (#database) OR (#mysql)");
QueryResult result;
result = twitter.search(query);
List<Status> tweets = result.getTweets();
for (Status tweet : tweets) {
System.out.println("#" + tweet.getUser().getScreenName() + " - " + tweet.getText() + "\n=======\n"
+ tweet.getCreatedAt());
dos.writeBytes("#" + tweet.getUser().getScreenName() + " - " + tweet.getText() + "\n"
+ tweet.getCreatedAt() + "\n=======\n");
}
System.exit(0);
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to search tweets: " + te.getMessage());
System.exit(-1);
}
} catch (IOException e) {
e.printStackTrace();
}
}
You have a popular query, so you are only getting the last 10 tweets. You can walk back in chunks of 100. Use "&max_id=ID&count=100"
So add an outer loop and remember the minimum id you have seen on previous iterations. For the first iteration, don't set max_id, and then keep updating max_id to the new minimum on subsequent iterations.
https://api.twitter.com/1.1/search/tweets.json?q=%23hadoop+OR+%23bigdata+OR+%23data+OR+%23datamining+OR+%23mapreduce+OR+%23flume+OR+%23semanticanalytic+OR+%23dataset+OR+%23rdbms+OR+%23database+OR+%23mysql&max_id=758939297495982100&count=100
Looks like that is available here http://twitter4j.org/javadoc/twitter4j/Query.html#setMaxId-long-
More general docs https://dev.twitter.com/rest/reference/get/search/tweets

Using facebook graph API 2.5 for batch request in Java

I was using facebook FQL query to fetch sharecount for multiple URLS using this code without needing any access token.
https://graph.facebook.com/fql?q=";
"SELECT url, total_count,share_count FROM link_stat WHERE url in (";
private void callFB(List validUrlList,Map> dataMap,long timeStamp,Double calibrationFactor){
try {
StringBuilder urlString = new StringBuilder();
System.out.println("List Size " + validUrlList.size());
for (int i = 0; i < (validUrlList.size() - 1); i++) {
urlString.append("\"" + validUrlList.get(i) + "\",");
}
urlString.append("\""
+ validUrlList.get(validUrlList.size() - 1) + "\"");
String out = getConnection(fbURL+URLEncoder.encode(
queryPrefix
+ urlString.toString() + ")", "utf-8"));
dataMap = getSocialPopularity(validUrlList.toArray(), dataMap);
getJSON(out, dataMap, timeStamp,calibrationFactor);
} catch (Exception e) {
e.printStackTrace();
}
}
But as now Facebook has depreciated it i am planning to use
https://graph.facebook.com/v2.5/?ids=http://timesofindia.indiatimes.com/life-style/relationships/soul-curry/An-NRI-bride-who-was-tortured-to-hell/articleshow/50012721.cms&access_token=abc
But i could not find any code to make batch request in the same also i am using pageaccesstoken so what could be the rate limit for same.
Could you please help me to find teh batch request using java for this new version.
You will always be subject to rate limiting... If you're using the /?ids= endpoint, there's already a "batch" functionality built-in.
See
https://developers.facebook.com/docs/graph-api/using-graph-api/v2.5#multirequests
https://developers.facebook.com/docs/graph-api/advanced/rate-limiting

How to delete a credit card using the USAEPAY Web service?

I am using the USAEPAY Web service for credit card services, including adding, updating and deleting credit cards. Adding/updating works fine, however the credit card deletion results in the error:
com.usaepay.api.jaxws.GeneralFault_Exception: 40030: Customer Not Found
It is quite strange because I check the customer number in all other operations and this number is the same and it works
Code example
Add credit card:
public void addPaymentMethodToCustomer(String customerNum, SavedCreditCardInfo savedCreditCardInfo, Address address) {
UeSecurityToken securityToken = getSecurityToken(null);
PaymentMethod paymentMethod = createUSAEPaymentMethod(savedCreditCardInfo, address);
BigInteger paymentMethodID = null;
if(securityToken != null) {
try {
UeSoapServerPortType client = getClient();
paymentMethodID = client.addCustomerPaymentMethod(securityToken, new BigInteger(customerNum), paymentMethod, false, false);
} catch (Exception e) {
LOG.error("Unable to add payment method for customer " + customerNum, e);
throw new AddPaymentMethodException("Unable to add payment method for USA E Pay customer num " + customerNum);
}
LOG.info("Succesfully added payment method for customer=" + customerNum + " with payment method=" + paymentMethodID );
}
}
Log:
INFO com.smartdestinations.service.payment.impl.USAEPayServiceImpl:288 - Succesfully added payment method for customer=25468380 with payment method=12184
Deletion:
public void deleteCustomerPaymentMethod(String paymentMethodId, String customerNum) {
UeSecurityToken securityToken = getSecurityToken(null);
if(securityToken != null) {
try {
UeSoapServerPortType client = getClient();
client.deleteCustomerPaymentMethod(securityToken, new BigInteger(customerNum), new BigInteger(paymentMethodId));
} catch (Exception e) {
LOG.error("Unable to delete payment method with customerNumber=" + customerNum + " and paymentID=" + paymentMethodId, e);
throw new DeletePaymentMethodException("Unable to delete payment with id " + paymentMethodId + " for customer " + customerNum);
}
}
}
Log:
com.smartdestinations.service.payment.impl.USAEPayServiceImpl:388 - Unable to delete payment method with customerNumber=25468380 and paymentID=12184
com.usaepay.api.jaxws.GeneralFault_Exception: 40030: Customer Not Found
It appeared to be a bug in USAEPAY. They promised to fix this bug

Categories