Twitter/Spring - post tweet in a #Scheduled job - spring

I have already got some "Spring-scheduled" tasks up and running successfully.
What I would like now is to post some specific tweets to a known Twitter account (and already configured on Twitter side) based on some event recurrence.
However, all I see in the OAuth process, esp. in order to get an access token, is that it requires some callback URL before being able to do anything.
I might be mistaken but this seems hard to integrate in the context of a scheduled task.
Isn't there any other way to achieve tweeting?

In conjunction with Spring Scheduling features, I would use Twitter4j to post a tweet in a scheduled job.
Here is a sample:
#Componet
public class TwitterSender {
#Scheduled(fixedRate = 10000)
public void sendTweet() {
Twitter twitter = TwitterFactory.getSingleton();
Status status = twitter.updateStatus(latestStatus);
System.out.println("Status updated to: " + status.getText() + ".");
}
}
If you need more information you can check the test case for sending update status with Twitter4j. Or you can just dive and see the source.

It may be a bit of a leap in terms of learning curve, but have you looked at spring-integration's twitter:outbound-channel-adapter ?
<twitter:outbound-channel-adapter twitter-template="twitterTemplate"
channel="twitterChannel"/>
http://static.springsource.org/spring-integration/docs/latest-ga/reference/html/twitter.html

Related

Google Tasks API does not give update about Task completion when New Gmail Theme used

First I created a Task using below link:
https://mail.google.com/tasks/canvas
Then I marked it as Completed. When I checked the API Response for the same using:
Services > Tasks API v1 > tasks.tasks.list [Returns all tasks in the specified task list.]
I was able to view the updates & found the task i marked as complete.
However when I did the same using New interface (theme) from GMail, I found that the task I updated with completion was not at all there in above API Response.
Thus Google Tasks API does not give update about Task completion when New Gmail Theme used. Is there anything I missed or is it bug from Google Task API with Newly introduced theme?
I was held up by this same thing this week. but I just figured it out using the "Try this API" feature on https://developers.google.com/tasks/v1/reference/tasks/list which I got to show me my completed tasks. After looking at how their code told tasks.tasks.list that they wanted to be given the completed and hidden items (both flags were needed) I played around with my code and learned from error messages that after giving the tasklist ID, I could add a JavaScript object literal, so I copied part of object literal from the code of the "Try this API" and the following worked.
var tasks = Tasks.Tasks.list( taskListId, { showCompleted: true, showHidden: true } );
if (tasks.items) {
for (var i = 0; i < tasks.items.length; i++) {
var task = tasks.items[i];
Logger.log('Task with title "%s" and notes "%s" and status "%s" was found ' ,
task.title, task.notes, task.status );
}
}

JGiven show acceptance test running line by line

Is it possible to use JGiven (with or without Spring support) to retrieve the statements before / during execution? For example, if we had a fairly typical login acceptance test i.e.
public class LoginFeatureTest extends SpringScenarioTest<GivenIAmAtTheLoginPage, WhenILogin, ThenTheLoginActionWillBeSuccessful> {
#Test
public void my_login_test() {
given().I_am_a_new_user()
.and().I_am_at_the_login_page();
when().I_login_with_username_$_and_password_$("dave", "dave123");
then().the_home_page_is_visible();
}
}
Is it possible to get something access to the following information?
My Login Test (start)
Given I am a new user
and I am at the login page
When I login with username dave and password dave123
Then the home page is visible
My Login Test (end)
i.e. what i'm looking for is: -
The name of a scenario method + all it's given, when, then and and statement calls _(formatted via JGiven formatting).
When each scenario method starts at run-time.
When each given, when, then and and executes at run-time.
When the scenario method ends.
This will give me the ability to visually show in a UI (a) exactly what is going to execute and (2) it's current position during execution (with durations).
12:00:01.012 [ My Login Test (start) ]
12:00:02.035 23ms Given I am a new user
12:00:02.051 16ms and I am at the login page
----> When I login with username dave and password dave123
Then the home page is visible
[ end ]
I'm thinking Spring AOP might come to the rescue here? Or does JGiven provide anything useful buried in it's code?
At the moment there is no possibility to do that. I have created an issue for that: https://github.com/TNG/JGiven/issues/328.
It should not be too difficult to implement this as there is internally already a listener concept. If you are still interested you could propose an API and integrate the mechanism in JGiven.

Aws integration spring: Extend Visibility Timeout

Is it possible to extend the visibility time out of a message that is in flight.
See:
http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AboutVT.html.
Section: Changing a Message's Visibility Timeout.
http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/sqs/AmazonSQSClient.html#changeMessageVisibility-com.amazonaws.services.sqs.model.ChangeMessageVisibilityRequest-
In summary I want to be able to extend the first set visibility timeout for a given message that is in flight.
Example if 15secs have passed I then want to extend the timeout by another 20secs. Better example in java docs above.
From my understanding in the links above you can do this on the amazon side.
Below are my current settings;
SqsMessageDrivenChannelAdapter adapter =
new SqsMessageDrivenChannelAdapter(queue);
adapter.setMessageDeletionPolicy(SqsMessageDeletionPolicy.ON_SUCCESS);
adapter.setMaxNumberOfMessages(1);
adapter.setSendTimeout(2000);
adapter.setVisibilityTimeout(200);
adapter.setWaitTimeOut(20);
Is it possible to extend this timeout?
Spring Cloud AWS supports this starting with Version 2.0. Injecting a Visiblity parameter in your SQS listener method does the trick:
#SqsListener(value = "my-sqs-queue")
void onMessageReceived(#Payload String payload, Visibility visibility) {
...
var extension = visibility.extend(20);
...
}
Note, that extend will work asynchronously and will return a Future. So if you want to be sure further down the processing, that the visibility of the message is really extended at the AWS side of things, either block on the Future using extension.get() or query the Future with extension.isDone()
OK. Looks like I see your point.
We can change visibility for particular message using API:
AmazonSQS.changeMessageVisibility(String queueUrl, String receiptHandle, Integer visibilityTimeout)
For this purpose in downstream flow you have to get access to (inject) AmazonSQS bean and extract special headers from the Message:
#Autowired
AmazonSQS amazonSqs;
#Autowired
ResourceIdResolver resourceIdResolver;
...
MessageHeaders headers = message.getHeaders();
DestinationResolver destinationResolver = new DynamicQueueUrlDestinationResolver(this.amazonSqs, this.resourceIdResolver);
String queueUrl = destinationResolver.resolveDestination(headers.get(AwsHeaders.QUEUE));
String receiptHandle = headers.get(AwsHeaders.RECEIPT_HANDLE);
amazonSqs.changeMessageVisibility(queueUrl, receiptHandle, YOUR_DESIRED_VISIBILITY_TIMEOUT);
But eh, I agree that we should provide something on the matter as out-of-the-box feature. That may be even something similar to QueueMessageAcknowledgment as a new header. Or even just one more changeMessageVisibility method to this one.
Please, raise a GH issue for Spring Cloud AWS project on the matter with link to this SO topic.

YouTube Data API - Number of Results - Maven

I am trying to get videos from youtube in two different ways
a) First using youtube-google-api client library following the guidelines and sample code from here https://developers.google.com/youtube/v3/code_samples/java#search_by_keyword
Nevertheless, since I am implementing in a mavenized project Ihave difficulty in finding the dependency for 'com.google.api.services.samples.youtube.cmdline.Auth" which is required for the following block of code:
try {
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("youtube-cmdline-search-sample").build();
b)Second I simply send a GET request to YouTube like this:
https://www.googleapis.com/youtube/v3/search?part=snippet&q=madonna&type=video&key={API_KEY}
but I am able to receive only 5 results, although I've read in several Stackoverflow related questions that I can receive up to 50 videos.This is not feasible even if I set the "max-results" parameter.
Could anyone help me to deal with these issues? Thank you in advance.
In your second way Write maxResults=50 as a parameter instead of max-results=50.
Use YouTube Data Api v3 api explorer to understand parameters very well.
https://developers.google.com/apis-explorer/#s/youtube/v3/
https://www.googleapis.com/youtube/v3/search?part=snippet&q=madonna&maxResults=50&type=video&key={API_KEY}

Bing translator HTTP API throws bad request error, how to solve this?

Whenever I call Bing Translation API [HTTP] to translate some text, first time it works fine, and second time onwards it gives me 'bad request' [status code 400] error. If I wait for 10 or so minutes and then try again, then first request is successful, but second one onwards same story. I have a free account [2million chars translation] with Bing Translation APIs, are there any other limitations calling this API?
Thanks, Madhu
Answer:
hi, i missed to subscribing to Microsoft Translator DATA set subscription. Once i get the same, then things have solved. i.e; once i have signed up for https://datamarket.azure.com/dataset/bing/microsofttranslator then things are working.
i was generating the access_token correctly, so that is not an issue.
thanks, madhu
i missed to subscribing to Microsoft Translator DATA set subscription. Once i get the same, then things have solved. i.e; once i have signed up for https://datamarket.azure.com/dataset/bing/microsofttranslator then things are working.
i was
thanks, madhu
As a note to anyone else having problems, I figured out that the service only allows the token to be used once when using the free subscription. You have to have a paid subscription to call the Translate service more than once with each token. This limitation is, of course, undocumented.
I don't know if you can simply keep getting new tokens -- I suspect not.
And regardless of subscription, the tokens do expire every 10 minutes, so ensure you track when you receive a token and get a new one if needed, e.g. (not thread-safe):
private string _headerValue;
private DateTime _headerValueCreated = DateTime.MinValue;
public string headerValue {
get {
if(_headerValueCreated < DateTime.Now.AddMinutes(-9)) {
var admAuth = new AdmAuthentication("myclientid", "mysecret");
_headerValue = "Bearer " + admAuth.GetAccessToken();
_headerValueCreated = DateTime.Now;
}
return _headerValue;
}
}

Resources