how is jtwitter OAuth switching? - java

Here is my code:
import winterwell.jtwitter.Twitter;
import winterwell.jtwitter.*;
import java.util.List;
public class twitterbagla {
private static final String username="blabla";
private static final String password="xx";
public static void main(String[] args) {
Twitter twitter=new Twitter (username,password);
System.out.println(twitter.getStatus("hah"));
//System.out.println(twitter.getFollowers());
twitter.setStatus("hello world something");
List<User> followers=twitter.getFollowers();
for(User user : followers){
System.out.println(user.getName());
}
}
}
and here is console
It's amazing to me that the best things in life are steps forward that come with negative assumptions.
Exception in thread "main" winterwell.jtwitter.TwitterException$UpdateToOAuth: You need to switch to OAuth. Twitter no longer support basic authentication.
at winterwell.jtwitter.URLConnectionHttpClient.processError(URLConnectionHttpClient.java:369)
at winterwell.jtwitter.URLConnectionHttpClient.post2(URLConnectionHttpClient.java:303)
at winterwell.jtwitter.URLConnectionHttpClient.post(URLConnectionHttpClient.java:272)
at winterwell.jtwitter.Twitter.updateStatus(Twitter.java:2593)
at winterwell.jtwitter.Twitter.updateStatus(Twitter.java:2519)
at winterwell.jtwitter.Twitter.setStatus(Twitter.java:2291)
at twitterbagla.main(twitterbagla.java:16)

https://dev.twitter.com/docs/twitter-libraries#java You can find some libraries here..

See the documentation at http://www.winterwell.com/software/jtwitter.php
You want to create an OAuthSignpostClient. There's then an authorisation step with Twitter (you can store the resulting tokens to reuse later).
Then use new Twitter(name, oauthClient) to create your Twitter instance.

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();
}
}

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.

is it possible to make a system SMS Based Query in Java

is it possible to make a system SMS Based Query in Java?because im planning to try and make a System Based on java that has SMS Based query like when you send some sort of code to the system it replies also with a sms
Yes, check out twilio. Pretty great and can set up a cool chat bot type of thing either using some web server or amazon lambda. You can set a script so it will take certain inputs, do whatever code you want and send an output.
// 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();
}
}

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.

Using firebase Java library on server without authentication process

The server I am operating is being used to generate Firebase tokens and to read and write values from firebase, I use REST APIs with a different type of token which has different UID prefix.
However, since many features have been added to the server, I decided to use Firebase java library and now migrating the previous code that was written for REST APIs.
The question is, how can I use Firebase Java library with tokens omitting authentication process?
Authentication process runs asynchronously so it can be applied to client application but not to server.
What if it fails authentication? or what if it takes too much time?
The previous code just used auth token for every request like this:
https://abcd.firebaseio.com/ns/blahblah/event?auth=token
So it doesn't need any authentication process.
Hope you understand my poor English.
Thanks!
According to the Firebase documentation for authentication server-side processes, there are three ways to authenticate:
Using a Firebase app secret
Using a secure JWT with the optional admin claim set to true
Using a secure JWT designed to give access to only the pieces of data a server needs to touch
You are currently getting a secure JWT from your authentication server, so you are using option 2 or 3.
The alternative is to use the so-called app secret of you Firebase application. You can find this value in the Dashboard of the application and it can serve as a drop-in replacement for the current token.
However I highly recommend against this approach. Jenny wrote up a pretty exhaustive list of reasons against it here: https://stackoverflow.com/a/29240941
You can't replace the whole authentication process with just a secret using the Java Client Library. You need to generate a JWT. Authentication lasts for 24 hours, so you can save the generated JWT until it fails, or you just authenticate again prior to 24 hours, and keep that JWT again.
In order to handle the fact that authentication is an asynchronous process you'd also have to use a CountdownLatch or a Semaphore to prevent your program from exiting before the authentication process receives a response from Firebase.
CountdownLatch
A synchronisation aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
import com.firebase.client.AuthData;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.security.token.TokenGenerator;
import java.util.concurrent.CountDownLatch;
public class Main {
public static void main(String[] args) {
Map<String, Object> payload = new HashMap<String, Object>();
payload.put("uid", "uniqueId1");
payload.put("some", "arbitrary");
payload.put("data", "here");
TokenGenerator tokenGenerator = new TokenGenerator("<YOUR_FIREBASE_SECRET>");
String token = tokenGenerator.createToken(payload);
Firebase fb = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
CountDownLatch done = new CountDownLatch(1);
fb.authWithCustomToken(token, new Firebase.AuthResultHandler() {
#Override
public void onAuthenticationError(FirebaseError error) {
System.err.println("Login Failed! " + error.getMessage());
done.countDown();
}
#Override
public void onAuthenticated(AuthData authData) {
System.out.println("Login Succeeded!");
// Save your JWT to keep using it for 24 hours
done.countDown();
}
});
done.await();
}
}
Semaphore
It is used to control the number of concurrent threads that are using a resource. You could think of it as tickets to use a resource. You set the number of tickets available when you create it, and when acquire() is called with no tickets left, your process will wait for one to become available (on a release() call). On this code it is being created with zero "tickets" available:
import com.firebase.client.AuthData;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.security.token.TokenGenerator;
import java.util.concurrent.Semaphore;
public class Main {
public static void main(String[] args) {
Map<String, Object> payload = new HashMap<String, Object>();
payload.put("uid", "uniqueId1");
payload.put("some", "arbitrary");
payload.put("data", "here");
TokenGenerator tokenGenerator = new TokenGenerator("<YOUR_FIREBASE_SECRET>");
String token = tokenGenerator.createToken(payload);
Firebase fb = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
Semaphore semaphore = new Semaphore(0);
fb.authWithCustomToken(token, new Firebase.AuthResultHandler() {
#Override
public void onAuthenticationError(FirebaseError error) {
System.err.println("Login Failed! " + error.getMessage());
semaphore.release();
}
#Override
public void onAuthenticated(AuthData authData) {
System.out.println("Login Succeeded!");
// Save your JWT to keep using it for 24 hours
semaphore.release();
}
});
semaphore.acquire();
}
}

Categories