Upload image twitter4j - java

I introduced myself to Twitter4j yesterday, and are now testing out features for an upcoming program of mine. As the title suggests, I am trying to upload an image to twitter, without any luck. Here's my code:
import static java.awt.Toolkit.getDefaultToolkit;
import static javax.swing.JOptionPane.ERROR_MESSAGE;
import static javax.swing.JOptionPane.showMessageDialog;
import java.awt.Image;
import java.io.File;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.examples.tweets.UploadMultipleImages;
import twitter4j.media.ImageUpload;
import twitter4j.media.ImageUploadFactory;
public final class UpdateStatus {
static File file = new File("/images/Done.jpg");
public static void main(String[] args) {
for(int i=0;i<2;i++){
Twitter twitter = new TwitterFactory().getInstance();
Status status=null;
try {
ImageUpload.upload(file,"22");
} catch (TwitterException e) {
System.err.println("Shit...");
System.exit(3);
}
}
System.out.println("Done");
}
}
The image I'm trying to upload is Done.jpg, and is in a folder in the package. I've used this method for images in other programs, so I am pretty sure it works. Though, this gives me an error message before I run the code, saying "Cannot make a static reference to the non-static method upload(File, String) from the type ImageUpload". Any ideas that could help me? :D

You need to ensure following before testing your code -
Register your app at https://apps.twitter.com/ and get Oauth tokens to be able to connect your app to Twitter and perform desired action.
You will get a consumerKey,consumerAccessToken, accessKey and accessToken.
If you want to post updates, please ensure you configure your app
permissions to have a Read and Write access, deafult access is Read
Only.
After you have the required access tokens, you need to instantiate a Twitter instance using those tokens. This instance can then be used to perform requisite action. See sample code below to upload an image -
ConfigurationBuilder twitterConfigBuilder = new ConfigurationBuilder();
twitterConfigBuilder.setDebugEnabled(true);
twitterConfigBuilder.setOAuthConsumerKey("consumerkey");
twitterConfigBuilder.setOAuthConsumerSecret("consumersecret");
twitterConfigBuilder.setOAuthAccessToken("accesstoken");
twitterConfigBuilder.setOAuthAccessTokenSecret("accesstokensecret");
Twitter twitter = new TwitterFactory(twitterConfigBuilder.build()).getInstance();
String statusMessage = "Watch out this interesting offer I came across today";
File file = new File("/images/Done.jpg");
StatusUpdate status = new StatusUpdate(statusMessage);
status.setMedia(file); // set the image to be uploaded here.
twitter.updateStatus(status);
Hope this helps.

ImageUpload.upload is not a static method, but an instance method.
You need to create an instance of ImageUpload, and call the method from the instance.
Checking the documentation of ImageUpload, it is an interface. So you'll need to instantiate a class that implements ImageUpload.

Related

Google Cloud Trace Opentelemetry Java example code not showing up on Google Cloud Trace Dashboard

I followed the steps on Google Cloud's Java and OpenTelemetry site (https://cloud.google.com/trace/docs/setup/java-ot) and made a simple hello world Java application locally and am trying to get my traces to show up on Google Cloud Trace using their trace exporter.
All the setup code is the same, and the program compiles and runs successfully. However, I don't see anything on the Trace dashboard. I know it is not an issue with IAM or my service account key because I ran the Python example and it shows up in Cloud Trace dashboard just fine.
Anyone have any guidance on why the Java version could be silently failing?
Thanks
package hello;
import org.joda.time.LocalTime;
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Scope;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.StatusCode;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Scope;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.export.BatchSpanProcessor;
import io.opentelemetry.exporter.logging.LoggingSpanExporter;
import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.propagation.ContextPropagators;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.metrics.Meter;
import io.opentelemetry.sdk.metrics.SdkMeterProvider;
import io.opentelemetry.sdk.metrics.export.IntervalMetricReader;
import java.io.IOException;
import java.util.Random;
import com.google.cloud.opentelemetry.trace.TraceConfiguration;
import com.google.cloud.opentelemetry.trace.TraceExporter;
import java.util.Collections;
import static java.util.Collections.singleton;
import java.time.Duration;
public class HelloWorld {
private static final Random random = new Random();
private static OpenTelemetry setupTraceExporter() {
try {
TraceExporter traceExporter = TraceExporter.createWithConfiguration(
TraceConfiguration.builder().setProjectId("my-test-id").build());
// Register the TraceExporter with OpenTelemetry
return OpenTelemetrySdk.builder()
.setTracerProvider(
SdkTracerProvider.builder()
.addSpanProcessor(BatchSpanProcessor.builder(traceExporter).build())
.build())
.buildAndRegisterGlobal();
} catch (IOException e) {
System.out.println("Uncaught Exception");
System.out.println(e);
return null;
}
}
public static void main(String[] args) {
System.out.println("Starting the example application");
/* SET UP */
OpenTelemetry otel = setupTraceExporter();
/* Creating tracer */
Tracer tracer =
otel.getTracer("java foo");
Span span = tracer.spanBuilder("my span").startSpan();
// put the span into the current Context
try (Scope scope = span.makeCurrent()) {
System.out.println("Hello");
Thread.sleep(4000);
} catch (Throwable t) {
span.setStatus(StatusCode.ERROR, "error");
System.out.println(t);
} finally {
span.end();
}
System.out.println("Closing");
//otel.getSdkTracerProvider().shutdown();
}
}
After some debugging, I figured out the answer.
Seems like with this simple example, the BatchSpanProcessor is not a good idea because there is only one span that is getting traced.
SimpleSpanProcessor directly forwards the spans to Cloud Trace no matter what whereas BatchSpanProcessor waits until there is enough data before pushing to Cloud Trace. Hence why I was not seeing anything in Cloud Trace because BatchSpanProcessor hadn't registered enough spans for it to actually upload it to Google Cloud.
Span Processors Documentation
Change the following lines
return OpenTelemetrySdk.builder()
.setTracerProvider(
SdkTracerProvider.builder()
.addSpanProcessor(SimpleSpanProcessor.create(traceExporter))
.build())
.buildAndRegisterGlobal();
Hope this helps others!

How to enable Neural Text-to-Speech (NTTS) in Java using Amazon Polly

I am trying to use Amazon Polly to convert text to speech using Java API. As described by Amazon there are several US english voices which support Neural. https://docs.aws.amazon.com/polly/latest/dg/voicelist.html
The code I am following to run in Java application is as following:
package com.amazonaws.demos.polly;
import java.io.IOException;
import java.io.InputStream;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.polly.AmazonPollyClient;
import com.amazonaws.services.polly.model.DescribeVoicesRequest;
import com.amazonaws.services.polly.model.DescribeVoicesResult;
import com.amazonaws.services.polly.model.OutputFormat;
import com.amazonaws.services.polly.model.SynthesizeSpeechRequest;
import com.amazonaws.services.polly.model.SynthesizeSpeechResult;
import com.amazonaws.services.polly.model.Voice;
import javazoom.jl.player.advanced.AdvancedPlayer;
import javazoom.jl.player.advanced.PlaybackEvent;
import javazoom.jl.player.advanced.PlaybackListener;
public class PollyDemo {
private final AmazonPollyClient polly;
private final Voice voice;
private static final String JOANNA="Joanna";
private static final String KENDRA="Kendra";
private static final String MATTHEW="Matthew";
private static final String SAMPLE = "Congratulations. You have successfully built this working demo of Amazon Polly in Java. Have fun building voice enabled apps with Amazon Polly (that's me!), and always look at the AWS website for tips and tricks on using Amazon Polly and other great services from AWS";
public PollyDemo(Region region) {
// create an Amazon Polly client in a specific region
polly = new AmazonPollyClient(new DefaultAWSCredentialsProviderChain(),
new ClientConfiguration());
polly.setRegion(region);
// Create describe voices request.
DescribeVoicesRequest describeVoicesRequest = new DescribeVoicesRequest();
// Synchronously ask Amazon Polly to describe available TTS voices.
DescribeVoicesResult describeVoicesResult = polly.describeVoices(describeVoicesRequest);
//voice = describeVoicesResult.getVoices().get(0);
voice = describeVoicesResult.getVoices().stream().filter(p -> p.getName().equals(MATTHEW)).findFirst().get();
}
public InputStream synthesize(String text, OutputFormat format) throws IOException {
SynthesizeSpeechRequest synthReq =
new SynthesizeSpeechRequest().withText(text).withVoiceId(voice.getId())
.withOutputFormat(format);
SynthesizeSpeechResult synthRes = polly.synthesizeSpeech(synthReq);
return synthRes.getAudioStream();
}
public static void main(String args[]) throws Exception {
//create the test class
PollyDemo helloWorld = new PollyDemo(Region.getRegion(Regions.US_WEST_1));
//get the audio stream
InputStream speechStream = helloWorld.synthesize(SAMPLE, OutputFormat.Mp3);
//create an MP3 player
AdvancedPlayer player = new AdvancedPlayer(speechStream,
javazoom.jl.player.FactoryRegistry.systemRegistry().createAudioDevice());
player.setPlayBackListener(new PlaybackListener() {
#Override
public void playbackStarted(PlaybackEvent evt) {
System.out.println("Playback started");
System.out.println(SAMPLE);
}
#Override
public void playbackFinished(PlaybackEvent evt) {
System.out.println("Playback finished");
}
});
// play it!
player.play();
}
}
By default its taking the Standard of the voice of Matthew. Please suggest what needs to be changed to make the speech Neural for the voice of Matthew.
Thanks
Thanks #ASR for your feedback.
I was able to find the engine parameter as you suggested.
The way I had to solve this is:
Update the aws-java-sdk-polly version from 1.11.77 (as they have in their documentation) to the latest 1.11.762 in the pom.xml and build the Maven project. This brings the latest class definition for SynthesizeSpeechRequest Class. With 1.11.77 I was unable to see withEngine function in its definition.
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-polly</artifactId>
<version>1.11.762</version>
</dependency>
Updated the withEngine("neural") as below:
SynthesizeSpeechRequest synthReq =
new SynthesizeSpeechRequest().withText(text).withVoiceId(voice.getId())
.withOutputFormat(format).withEngine("neural");
As defined in https://docs.aws.amazon.com/polly/latest/dg/NTTS-main.html Neural voice is only available in specific regions. So I had to chose as following:
PollyDemo helloWorld = new PollyDemo(Region.getRegion(Regions.US_WEST_2));
After this Neural voice worked perfectly.
I am assuming you are using AWS Java SDK 1.11
AWS documentation here states that you need to set the engine parameter in the speech sysnthesis request to neural. AWS Java SDK documentation here describes the withEngine method to set it to neural.
PS: the documentation page doesn't seem to provide the method URLs, so you will have to search for it.

IBM Watson TextToSpeech examples do not accept AUDIO_WAV as contentType

Trying to run RecognizeUsingWebSocketsExample provided with IBM Watson SpeechToText Java SDK, but it's failing to create a valid RecognizeOptions object for the sample .wav file provided with the distribution:
Exception in thread "main" java.lang.IllegalArgumentException: When using PCM the audio rate should be specified.
at com.ibm.watson.developer_cloud.util.Validator.isTrue(Validator.java:38)
at com.ibm.watson.developer_cloud.speech_to_text.v1.RecognizeOptions$Builder.contentType(RecognizeOptions.java:95)
at com.ibm.watson.developer_cloud.speech_to_text.v1.RecognizeUsingWebSocketsExample.main(RecognizeUsingWebSocketsExample.java:30)
It appears that the contentType(HttpMediaType.AUDIO_WAV) is being misinterpreted as RAW. Here's the actual (unmodified from distro) code:
package com.ibm.watson.developer_cloud.speech_to_text.v1;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import com.ibm.watson.developer_cloud.http.HttpMediaType;
import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechResults;
import com.ibm.watson.developer_cloud.speech_to_text.v1.websocket.BaseRecognizeCallback;
/**
* Recognize using WebSockets a sample wav file and print the transcript into the console output.
*/
public class RecognizeUsingWebSocketsExample {
private static CountDownLatch lock = new CountDownLatch(1);
public static void main(String[] args) throws FileNotFoundException, InterruptedException {
SpeechToText service = new SpeechToText();
service.setUsernameAndPassword("<username>", "<password>");
FileInputStream audio = new FileInputStream("src/test/resources/speech_to_text/sample1.wav");
RecognizeOptions options = new RecognizeOptions.Builder()
.continuous(true)
.interimResults(true)
.contentType(HttpMediaType.AUDIO_WAV)
.build();
service.recognizeUsingWebSocket(audio, options, new BaseRecognizeCallback() {
#Override
public void onTranscription(SpeechResults speechResults) {
System.out.println(speechResults);
if (speechResults.isFinal())
lock.countDown();
}
});
lock.await(1, TimeUnit.MINUTES);
}
}
I'm using 3.0.0-RC2 snapshot. No problems running examples which do not use RecognizeOptions, like SpeechToTextExample. Thx.
-rg
Sorry, false alarm. I recreated the example project from scratch and it compiled and ran without a hitch. Must have been some weirdness with my Eclipse setup.

Java application for Bing API

I have to make an application which is able to use Bing Search API ( SOAP Services) with java.It must do a specific search for a word.Here is my code :
import com.google.code.bing.search.client.BingSearchClient;
import com.google.code.bing.search.client.BingSearchServiceClientFactory;
import com.google.code.bing.search.client.BingSearchClient.SearchRequestBuilder;
import com.google.code.bing.search.schema.AdultOption;
import com.google.code.bing.search.schema.SearchOption;
import com.google.code.bing.search.schema.SearchRequest;
import com.google.code.bing.search.schema.SearchResponse;
import com.google.code.bing.search.schema.SourceType;
import com.google.code.bing.search.schema.web.WebResult;
import com.google.code.bing.search.schema.web.WebSearchOption;
public class MyApp {
String apikey = "****************";
String searchword="google";
public static void main(String[] args){
BingSearchServiceClientFactory factory = BingSearchServiceClientFactory.newInstance();
BingSearchClient client = factory.createBingSearchClient();
SearchRequestBuilder builder = client.newSearchRequestBuilder();
builder.withAppId(apikey);
builder.withQuery(searchword);
builder.withSourceType(SourceType.WEB);
builder.withVersion("2.0");
builder.withMarket("en-us");
builder.withAdultOption(AdultOption.MODERATE);
builder.withSearchOption(SearchOption.ENABLE_HIGHLIGHTING);
builder.withWebRequestCount(10L);
builder.withWebRequestOffset(0L);
builder.withWebRequestSearchOption(WebSearchOption.DISABLE_HOST_COLLAPSING);
builder.withWebRequestSearchOption(WebSearchOption.DISABLE_QUERY_ALTERATIONS);
SearchResponse response = client.search(builder.getResult());
for (WebResult result : response.getWeb().getResults()) {
System.out.println(result.getTitle());
System.out.println(result.getDescription());
System.out.println(result.getUrl());
System.out.println(result.getDateTime());
}
}
}
I found this http://code.google.com/p/bing-search-java-sdk/ site.
I get my appkey from Azure MarketPlace. I get an error : java.lang.NullPointerException at the line for loop that will show response. That means response is null.
I don't understand what I am missing .
bing is changing their license system at the moment. this API was created using the "old" version 2 license. MS had done some changes when migrating to Azzure market place:
https://datamarket.azure.com/dataset/5BA839F1-12CE-4CCE-BF57-A49D98D29A44
migration guide:
http://go.microsoft.com/fwlink/?LinkID=248077
I don't think that this is covered by this Java-API wrapper you use already.

Internet on android, causing twitter4j exception?

I'm experimenting with twitter4j on android (new to both) coded up a simple process in java just to test it out. It downloads a users timeline and prints to screen.
I modify the code for android, but I get a TwitterException when i try to download the user timeline. I checked out the debugger and the exception is null; no information given. I've also added the Internet permission to the android manifest on previous advice. Heres the code:
package com.test;
import java.util.List;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import android.app.Activity;
import android.os.Bundle;
public class Test2 extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
List<Status> statuses = null;
Twitter api = new TwitterFactory().getInstance("USERNAME","PASSWORD");
try{
statuses = api.getUserTimeline();
}
catch(TwitterException e){
System.out.println("ERROR");
System.exit(-1);
}
for(Status s: statuses){
System.out.println(s.getText());
}
}
}
I realise this only prints to the console, just to keep it simple.
Thanks for any and all help.
Make sure you have the INTERNET permission in your AndroidManifest.xml file.
Also System.out.println() is not recommended on Android. Please use the android.util.Log class and send your debugging output to LogCat (available via adb logcat, DDMS, or the DDMS perspective in Eclipse).
Please check your timestamp. Each HttpRequest contain current timestamp, if the timestamp is wrong then it throw exception.

Categories

Resources