How to access YouTube view count with Java API - java

I found this answer that shows how to get a video's view count with the Java YouTube API but clearly some things must have changed over the last 7 years or so because I can't figure out the code.
This line
YouTube.Videos.List list = youtube.videos().list("statistics");
produces an error in Eclipse because the list method from the class Videos(at least in the current API version) has a parameter of type List<String>not String...so can someone show me how to achieve my goal using the current API seeing as the code linked above is invalid due to changes to the API?
EDIT: Here is how I have defined my dependency for the YouTube API in my pom.xml file
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-youtube</artifactId>
<version>v3-rev20201202-1.31.0</version>
</dependency>

Thanks to a little help from stvar and of course the old question I linked to in my question I figured out what I needed to do. Here is the working code:
import java.io.IOException;
import java.util.Arrays;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.services.youtube.*;
import com.google.api.services.youtube.model.Video;
public class Main {
public static void main(String[] args) throws IOException
{
YouTube youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("youtube-view-count-test").build();
YouTube.Videos.List list = youtube.videos().list(Arrays.asList("statistics"));
list.setId(Arrays.asList("kffacxfA7G4"));
String apiKey = "[redacted]";
list.setKey(apiKey);
Video v = list.execute().getItems().get(0);
System.out.println("The view count is: "+v.getStatistics().getViewCount());
}
}
The Auth class that is used in my code is taken from here, part of Google's API samples

Related

Geolocalization with Bing and Java

Can I use the Bing Maps API with Java for geolocation? I have the API key but I can't find anything on the net.
I've found a method with an Excel Macro that works but isn't enough, I need a java console script to do it.
Cheers, Damiano.
There doesn't appear to be any official way to make use of the Maps API in Java.
However, there is an unofficial Java wrapper for the API located here. This hasn't been updated in a while, so there's no guarantee it will still work, but it should be a good starting point for implementing geocoding requests.
There is also a method for implementing reverse-geocoding requests in the same wrapper at client.reverseGeocode().
import net.virtualearth.dev.webservices.v1.common.GeocodeResult;
import net.virtualearth.dev.webservices.v1.geocode.GeocodeRequest;
import net.virtualearth.dev.webservices.v1.geocode.GeocodeResponse;
import com.google.code.bing.webservices.client.BingMapsWebServicesClientFactory;
import com.google.code.bing.webservices.client.geocode.BingMapsGeocodeServiceClient;
import com.google.code.bing.webservices.client.geocode.BingMapsGeocodeServiceClient.GeocodeRequestBuilder;
public class BingMapsGeocodeServiceSample {
public static void main(String[] args) throws Exception {
BingMapsWebServicesClientFactory factory = BingMapsWebServicesClientFactory.newInstance();
BingMapsGeocodeServiceClient client = factory.createGeocodeServiceClient();
GeocodeResponse response = client.geocode(createGeocodeRequest(client));
printResponse(response);
}
private static void printResponse(GeocodeResponse response) {
for (GeocodeResult result : response.getResults().getGeocodeResult()) {
System.out.println(result.getDisplayName());
}
}
private static GeocodeRequest createGeocodeRequest(BingMapsGeocodeServiceClient client) {
GeocodeRequestBuilder builder = client.newGeocodeRequestBuilder();
builder.withCredentials("xxxxxx", null);
builder.withQuery("1 Microsoft Way, Redmond, WA");
// builder.withOptionsFilter(Confidence.HIGH);
return builder.getResult();
}
}

How to use a CustomScoreQuery in Lucene 7.x

I'm relativly new to Lucene and want to implement my own CustomScoreQuery since I need it for my University.
I used the Lucene demo as my starting point to index all documents in a Folder and want to score them using my own algorithm.
Here are the links to the source code of the demo.
https://lucene.apache.org/core/7_1_0/demo/src-html/org/apache/lucene/demo/IndexFiles.html
https://lucene.apache.org/core/7_1_0/demo/src-html/org/apache/lucene/demo/SearchFiles.html
I'm checking with Luke: Lucene Toolbox Project to see my Index which is as expected. My problem occurs accessing it.
package CustomModul;
import java.io.IOException;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Terms;
import org.apache.lucene.queries.CustomScoreProvider;
import org.apache.lucene.queries.CustomScoreQuery;
import org.apache.lucene.search.Query;
public class CountingQuery extends CustomScoreQuery {
public CountingQuery(Query subQuery) {
super(subQuery);
}
public class CountingQueryScoreProvider extends CustomScoreProvider {
String _field;
public CountingQueryScoreProvider(String field, LeafReaderContext context) {
super(context);
_field = field;
}
public float customScore(int doc, float subQueryScore, float valSrcScores[]) throws IOException {
IndexReader r = context.reader();
//getTermVector returns Null
Terms vec = r.getTermVector(doc, _field);
//*TO-DO* Algorithm
return (float)(1.0f);
}
}
protected CustomScoreProvider getCustomScoreProvider(
LeafReaderContext context) throws IOException {
return new CountingQueryScoreProvider("contents", context);
}
}
In my customScore function I access the Index like described in most Tutorials. I should get access to the Index using getTermVector but it returns NULL.
In other posts I read that this could be caused by contents being a TextField which is declared in the Lucene Demo IndexFiles.
After trying a lot of different approaches I came to the conclusion that I need help and here I am.
My Question now is if I need to adjust the Index Process (how?) or is there another way to access the Index in the ScoreProvider other then getTermVector?
I was able to solve the Problem myself and wanted to share my solution if someone finds this Question looking for answers.
The Problem was indeed caused by the contents being a TextField in
https://lucene.apache.org/core/7_1_0/demo/src-html/org/apache/lucene/demo/IndexFiles.html
To solve this Problem one has to construct his own Field which I did replacing line 193 in said IndexFile with
FieldType myFieldType = new FieldType(TextField.TYPE_STORED);
myFieldType.setOmitNorms(true);
myFieldType.setIndexOptions(IndexOptions.DOCS_AND_FREQS);
myFieldType.setStored(false);
myFieldType.setStoreTermVectors(true);
myFieldType.setTokenized(true);
myFieldType.freeze();
Field myField = new Field("contents",
new BufferedReader(new InputStreamReader(stream,
StandardCharsets.UTF_8)),
myFieldType);
doc.add(myField);
this allows the use of getTermVector in the customScore Function. Hope this will help someone in the future.

Google Translate from Java Application

I am trying to do a simple translator by NetBeans. Firstly, I tried to implement the code below from a forum page:(https://www.java-forums.org/java-applets/38563-language-translation.html)
import com.google.api.translate.Language;
import com.google.api.translate.Translate;
public class Main {
public static void main(String[] args) throws Exception {
// Set the HTTP referrer to your website address.
Translate.setHttpReferrer("http://code.google.com/p/google-api-translate-java");
String translatedText = Translate.execute("Bonjour monde le",
Language.FRENCH, Language.ENGLISH);
System.out.println(translatedText);
}
}
I cannot compile the code. I got cannot resolve symbol for setHttpReferrer() although I added related jar.
Secondly, I tried to implement another solution from the page (https://www.java-forums.org/java-applets/61655-language-translation-using-google-api.html). I got my API key and set it.
import com.google.api.GoogleAPI;
import com.google.api.translate.Language;
import com.google.api.translate.Translate;
public class Translation
{
public static void main(String[] args) throws Exception {
GoogleAPI.setHttpReferrer("http://code.google.com/p/google-api-translate-java");
GoogleAPI.setKey("i have set my Api key");
String translatedText = Translate.DEFAULT.execute("Bonjour le monde", Language.FRENCH, Language.ENGLISH);
System.out.println(translatedText);
}
}
When I try to run this I got 403 error as null. Is there a simple way to call Google Translator from Java application?
403 error is documented on the faq as "exceeding your quota". https://cloud.google.com/translate/faq
I suspect however, you get the error because you haven't initialised the API properly, i.e authenticated, ...
Have a look at the setup in this code. Also search for hello welt.
https://github.com/GoogleCloudPlatform/google-cloud-java/blob/master/google-cloud-translate/src/test/java/com/google/cloud/translate/TranslateImplTest.java
Hope this helps.

Sending SMS with java application

Good evening my colleagues I hope you are well please I need to integrate an api that will help me to send SMS and CALL from my java application I have to find one called Ozeki Java SMS SDK but I can not integrate it to my app please if someone can help me find a solution and thanks in advance :)
You can check this one: https://www.twilio.com/docs/quickstart/java/sms
It's not really difficult to use.
Here's the official example given to create a class SmsSender:
// Install the Java helper library from twilio.com/docs/java/install
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.type.PhoneNumber;
import java.net.URISyntaxException;
public class SmsSender {
// Find your Account Sid and Auth Token at twilio.com/console
public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static final String AUTH_TOKEN = "your_auth_token";
public static void main(String[] args) throws URISyntaxException {
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
Message message = Message
.creator(new PhoneNumber("+14159352345"), // to
new PhoneNumber("+14158141829"), // from
"Where's Wallace?")
.create();
}
}
Please note that you need to register in order to have an account token.

Apache Camel - not moving file

I cannot figure out what I am doing wrong here. I have tried all sorts of things, including absolute paths, relative, enabling logging (which also doesnt seem to be working, using Main, using DefaultCamelContext, adding threadsleep, but I cannot get camel to move a file from one folder to another.
Here is my code:
package scratchpad;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.dataformat.beanio.BeanIODataFormat;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.main.Main;
import org.apache.camel.spi.DataFormat;
public class CamelMain {
private static Main main;
public static void main(String[] args) throws Exception {
main = new Main();
main.addRouteBuilder( new RouteBuilder() {
#Override
public void configure() throws Exception {
// DataFormat format = new BeanIODataFormat(
// "org/apache/camel/dataformat/beanio/mappings.xml",
// "orderFile");
System.out.println("starting route");
// a route which uses the bean io data format to format a CSV data
// to java objects
from("file://input?noop=true&startingDirectoryMustExist=true")
.to("file://output");
}
});
//main.run();
main.start();
Thread.sleep(5000);
main.stop();
}
}
Can someone spot anything wrong with the above?
Thanks
You can for example read from the free chapter 1 for the Camel in Action book, as it has a file copied example it covers from top to bottom.
The pdf can be downloaded here: http://manning.com/ibsen/

Categories