Unable to like a tweet using twitter4j but everything else is working fine - spring-boot

Here is the code which is working fine for other methods of twitter variable but only createfavorite is giving this error :
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
public class TwitterAutoLikerPart1 {
private static Logger logger = LoggerFactory.getLogger(TwitterAutoLikerPart1.class);
public static void main(String[] args) throws Exception {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("E")
.setOAuthConsumerSecret("F")
.setOAuthAccessToken("G")
.setOAuthAccessTokenSecret("H");
TwitterFactory tf = new TwitterFactory(cb.build());
var twitter = tf.getInstance();
long tweetid=tweetid;
logger.info("Tweet id is "+tweetid);
logger.info(twitter.createFavorite(tweetid).getText());
/*
Whereas this is working
for(var x:twitter.getFavorites())
logger.info(x.toString());*/
}
}
Here's the logs for your referrence :
Exception in thread "main" 401:Authentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
{"request":"\/1.1\/favorites\/create.json","error":"Read-only application cannot POST."}
Relevant discussions can be found on the Internet at:
http://www.google.co.jp/search?q=038fb9e8 or
http://www.google.co.jp/search?q=480cbeca
TwitterException{exceptionCode=[038fb9e8-480cbeca], statusCode=401, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=4.0.7}
at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:170)
at twitter4j.HttpClientBase.request(HttpClientBase.java:57)
at twitter4j.HttpClientBase.post(HttpClientBase.java:86)
at twitter4j.TwitterImpl.post(TwitterImpl.java:2102)
at twitter4j.TwitterImpl.createFavorite(TwitterImpl.java:1241)
at com.twiiterapi.mt.twitterapi.TwitterAutoLikerPart1.main(TwitterAutoLikerPart1.java:30)
Process finished with exit code 1
Kindly let me know where am I faultering.
Edit: So, the issue was app permission as pointed by the kind person Mr Andy Piper . I changed the permission and it started working like a charm .

Related

Getting 404 Not Found for basic spring rest api tutorial - 'hello world'

I am trying to create a rest api web application that can be eventually deployed into a container environment. I downloaded quite a few tutorials from spring.io to other websites as well but each time I use the exact repos I get a 404 error for the simple request.
To simplify it further I reduced it to 2 classes in one package:
project hierarchy
Main class:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
Controller Class:
#RestController
#RequestMapping("/")
public class RESTController {
private final AtomicLong counter = new AtomicLong();
private static final String template = "Hello, %s!";
/*
* REST API Test Methods
*/
#RequestMapping( "/greeting" )
public String greeting() {
return "It's working...!";
}
And of course the actual request:
http://localhost:8080/test_rest_api/greeting
HTTP Status 404 – Not Found
Type Status Report
Message /test_rest_api/greeting
Description The origin server did not find a current representation for the target resource or is not
willing to disclose that one exists.
Apache Tomcat/8.5.43
That is running on server by Run As - ; if I select Run as java application and select springboot the following error occurs:
java.lang.IllegalArgumentException: Sources must not be empty at
org.springframework.util.Assert.notEmpty(Assert.java:467)
I finally figured it out and it was a stupid mistake. I added the name of the project as part of the domain of the request url.
http://localhost:8080/test_rest_api/greeting
vs
http://localhost:8080/greeting

throw not found exception if pubsub topic is not available

I am using spring boot to interact with pubsub topic.
My config class for this connection look like this:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gcp.pubsub.core.PubSubTemplate;
import org.springframework.cloud.gcp.pubsub.core.publisher.PubSubPublisherTemplate;
import org.springframework.cloud.gcp.pubsub.support.PublisherFactory;
import org.springframework.cloud.gcp.pubsub.support.converter.SimplePubSubMessageConverter;
import org.springframework.util.Assert;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.SettableListenableFuture;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutureCallback;
import com.google.api.core.ApiFutures;
import com.google.pubsub.v1.PubsubMessage;
public abstract class PubSubPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(PubSubPublisher.class);
private final PubSubTemplate pubSubTemplate;
protected PubSubPublisher(PubSubTemplate pubSubTemplate) {
this.pubSubTemplate = pubSubTemplate;
}
protected abstract String topic(String topicName);
public ListenableFuture<String> publish(String topicName, String message) {
LOGGER.info("Publishing to topic [{}]. Message: [{}]", topicName, message);
return pubSubTemplate.publish(topicName, message);
}
}
And I am calling this at my service, like this:
publisher.publish(topic-name, payload);
This publish method is async one, which always pass on did not wait for acknowldgrment. I make add get after publish for wait until it get the response from pubsub.
But I wanted to know if in case my topic is not already present and i try to push some message, it should throw some error like resource not found, considering using default async method only.
Might be implementing the callback would help but i am unable to do that in my code. And the current override publish method which use callback is just throwing the WARN not exception i wanted that to be exception. that is the reason i wanted to implement the callback.
You can check if Topic already present
from google.cloud import pubsub_v1
project_id = "projectname"
topic_name = "unknowTopic"
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project_id, topic_name)
try:
response = publisher.get_topic(topic_path)
except Exception as e:
print(e)
This returns the error as
404 Resource not found (resource=unknowTopic).

Google OAuth 2 is generating redirect_uri instead of using one defined in client_secret.json

I would like to use the Google Calendar API, but in order to do that, I need to be authorized using Googles OAuth 2.0 API. I am running into trouble with the redirect_uri. The following is a sample of my client_secret.json.
{
"web": {
"client_id": "deleted",
"client_secret": "deleted",
"redirect_uris": ["http://localhost:8080/CommunityUmcPasadena/Callback"],
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token"
}
}
When I run my Quickstart application, I get the following error:
Apr 20, 2017 10:45:42 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for everybody: C:\Users\Gary\.credentials\calendar-java-quickstart
Apr 20, 2017 10:45:42 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for owner: C:\Users\Gary\.credentials\calendar-java-quickstart
2017-04-20 22:45:42.485:INFO::Logging to STDERR via org.mortbay.log.StdErrLog
2017-04-20 22:45:42.485:INFO::jetty-6.1.26
2017-04-20 22:45:42.498:INFO::Started SocketConnector#localhost:34940
Please open the following address in your browser:
https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=deleted&redirect_uri=http://localhost:34940/Callback&response_type=code&scope=https://www.googleapis.com/auth/calendar.readonly
Attempting to open that address in the default browser now...
As you can see, it has the redirect_uri as http://localhost:34940/Callback. This is not what is defined in client_secret.json though. It is using the correct client_id and secret though. Therefore, I'm not sure why the api is generating a random callback. I would also like to note that the redirect_uri listed in the client_secret.json is the same as the API Manager.
Does anyone know why the redirect_uri is being generated by the API instead of using the one defined in the client_secret.json?
Any help is greatly appreciated.
Also, here is the code for the quick start application...
package sample;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.client.util.DateTime;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.calendar.model.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
public class Quickstart {
private static final String APPLICATION_NAME = "Google Calendar API Java Quickstart";
private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"), ".credentials/calendar-java-quickstart");
private static FileDataStoreFactory DATA_STORE_FACTORY;
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static HttpTransport HTTP_TRANSPORT;
private static final List<String> SCOPES = Arrays.asList(CalendarScopes.CALENDAR_READONLY);
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
}
catch(Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
public static Credential authorize() throws IOException {
InputStream in = Quickstart.class.getResourceAsStream("/client_secret.json");
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY).setAccessType("offline").build();
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
return credential;
}
public static com.google.api.services.calendar.Calendar getCalendarService() throws IOException {
Credential credential = authorize();
return new com.google.api.services.calendar.Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
public static void main(String[] args) throws IOException {
com.google.api.services.calendar.Calendar service = getCalendarService();
}
}
Your code doesn't specify a redirect_url. I suspect that the Java library is making the assumption that if you don't specify a redirect_url, it's because you don't have one, so it defaults to a fake URL. It looks like you've copy/pasted the Quickstart code which says at the top of the page "a simple Java command-line application", whereas I think you're building a web server application.
Sooo, dig into the Java OAuth library docs (good luck - try https://developers.google.com/api-client-library/java/google-oauth-java-client/reference/1.20.0/com/google/api/client/auth/oauth2/AuthorizationCodeFlow) and see where to set the redirect URL to your ttp://localhost:8080/CommunityUmcPasadena/Callback
I have been looking an answer for quite some time...
You need to use
LocalServerReceiver
Example usage:
LocalServerReceiver localServerReceiver = new LocalServerReceiver.Builder().setHost("localhost").setPort(8181).build();
Credential credential = new AuthorizationCodeInstalledApp(flow, localServerReceiver).authorize("user");

jar file not up updating values in file

I have a javafx project that I am preparing for distributions. The project works perfectly from the debugger inside NetBeans. I am working on Linux.
But when I run the project from the jar file, there is one function in all the others that does not work. This function is supposed to open the settings file on a button click and alter some values from true to false.
I have changed the settings file's location and tried around google, but all to no avail.
I am still quite a newbie to java, fx, netbeans and java (not so much programming) and making my first experiences.
Any idea why this happens?
#FXML
private void openSettingsFile(ActionEvent event) throws IOException {
// this test works ....
ProcessBuilder processBuilder = new ProcessBuilder("terminal");
processBuilder.start();
// this part only replaces the values when I use the debugger ..
Path path = Paths.get("src/desktop_launcher/Settings.java");
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path));
content = content.replaceAll(" \"true\"" , " \"false\"");
Files.write(path, content.getBytes(charset));
Your approach (which, as far as I understand it, is to try to programmatically change the source file that generates the properties file) will not work at deployment time for a number of reasons.
The first is that the source files are generally not available at runtime: your jar file contains the class files and other resources required to run the application, but typically not the source code (and it's not desirable to include it in the application, in general).
Secondly, you are trying to locate this file from a relative path passed to Paths.get(..). This will resolve relative to the working directory, which is essentially arbitrary (basically "where the application was run from"). So even if the source code were available at runtime, this would not be a reliable way to find it. (My guess is that your debugger runs with the working directory fortuitously set to the parent directory of src, but when you run the jar file the most likely location of the working directory is the directory in which the jar file is located. But that is just a guess: it really depends on the configuration of your IDE, debugger, etc etc.)
Thirdly, and probably most importantly, even if the code does find the source file and rewrite it, that's all it will do. Next time you execute the application from the jar file, it won't magically know there is a new version of the source code that has to be compiled and then the resulting class file(s) incorporated into the jar file. So you would have to also include code to compile the new version of your source code (where will you get a compiler? AFAIK not all Java runtimes will include a compiler) and then programmatically insert the new class file(s) into the jar file (how do you even figure out where the jar file is: that is certainly non-trivial and I don't think it can be done in a reliable manner). What if the current user doesn't have permissions to write the directory containing the jar (which is a pretty common scenario..)?
The usual way to load and save startup configuration values is to use the java.util.Properties API. You need an external location to store the properties file, that you can be certain exists on the user's computer: a convenient way to do this is to create an application-specific directory in the user's home directory. The user's home directory can be accessed via System.getProperty("user.home"); (The system property user.home is one of those that is guaranteed to exist.).
I would recommend using a separate class to manage the configuration properties. For example:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.Properties;
public class PropertiesAccessor {
private static final Path USER_HOME = Paths.get(System.getProperty("user.home"));
private Properties props ;
private Path path ;
public PropertiesAccessor(String relativePath) {
path = USER_HOME.resolve(relativePath);
props = new Properties();
if (Files.exists(path)) {
try {
props.load(Files.newBufferedReader(path));
} catch (IOException exc) {
System.err.println("Warning: could not load properties file. Using defaults.");
exc.printStackTrace(System.err);
loadDefaults();
}
} else {
loadDefaults();
}
}
public Boolean getBooleanValue(String key) {
String value = props.getProperty(key);
return value == null ? null : Boolean.valueOf(value) ;
}
public void updateBooleanValue(String key, boolean value) {
props.setProperty(key, Boolean.toString(value));
}
public void writeProperties() throws IOException {
if (! Files.exists(path)) {
Files.createDirectories(path.getParent());
Files.createFile(path);
}
props.store(Files.newBufferedWriter(path), "Properties updated "+LocalDateTime.now());
}
private final void loadDefaults() {
// in real life, you might keep a default properties file bundled with
// the application and read that here, e.g.
// props.load(getClass().getResourceAsStream("/default-startup.properties"));
props.setProperty("config.value1", "true");
props.setProperty("config.value2", "false");
}
}
And now you can use this in your application. Just load the properties in the init() method and save them back in the stop() method. Note that executing this will create a directory called .myApp in your home directory, and a file called startup.properties inside it.
import java.io.IOException;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class StartupPropertiesExample extends Application {
private PropertiesAccessor config ;
private CheckBox value1 ;
private CheckBox value2 ;
#Override
public void init() {
config = new PropertiesAccessor(".myApp/startup.properties");
}
#Override
public void start(Stage primaryStage) {
value1 = new CheckBox("Value 1");
value2 = new CheckBox("Value 2");
value1.setSelected(config.getBooleanValue("config.value1"));
value2.setSelected(config.getBooleanValue("config.value2"));
Button exit = new Button("Exit");
exit.setOnAction(e -> Platform.exit());
VBox root = new VBox(10, value1, value2, exit);
root.setPadding(new Insets(10));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
#Override
public void stop() {
config.updateBooleanValue("config.value1", value1.isSelected());
config.updateBooleanValue("config.value2", value2.isSelected());
try {
config.writeProperties();
} catch (IOException exc) {
System.err.println("Warning: could not save properties");
exc.printStackTrace(System.err);
}
}
public static void main(String[] args) {
launch(args);
}
}

Posting on wall using Facebook4j

im new to Facebook4j and im looking for a way to post message using it. i just learned few of the coding in the internet. Please someone help me.
This are what i have done :
import facebook4j.Facebook;
import facebook4j.FacebookException;
import facebook4j.FacebookFactory;
import facebook4j.conf.Configuration;
import facebook4j.conf.ConfigurationBuilder;
public class post {
public static void main(String[] args)
throws FacebookException
{
// Create conf builder and set authorization and access keys
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setDebugEnabled(true);
configurationBuilder.setOAuthAppId("xxxx");
configurationBuilder.setOAuthAppSecret("xxxx");
configurationBuilder.setOAuthAccessToken("xxxx");
configurationBuilder .setOAuthPermissions("email, publish_stream, id, name, first_name, last_name, read_stream , generic");
configurationBuilder.setUseSSL(true);
// Create configuration and get Facebook instance
Configuration configuration = configurationBuilder.build();
FacebookFactory ff = new FacebookFactory(configuration);
Facebook Facebook = ff.getInstance();
Facebook.postStatusMessage("Hello World from Facebook4J.");
}
}
so, what i need to do next?
Have you created and authorized your app on https://developers.facebook.com ?
This is actually the first step.

Resources