twitter4j: getting credential errors even though i had set them? - credentials

package twitter4j.examples.tweets;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.conf.*;
import java.io.IOException;
public final class UpdateStatus {
public static void main(String[] args) throws IOException {
String testPost = "hello from otc";
String consumerKey = "key";
String consumerSecret = "secret";
String accessToken = "access";
String accessSecret = "access_secret";
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(consumerKey)
.setOAuthConsumerSecret(consumerSecret)
.setOAuthAccessToken(accessToken)
.setOAuthAccessTokenSecret(accessSecret);
try {
TwitterFactory factory = new TwitterFactory();
Twitter twitter = factory.getInstance();
AccessToken accestoken = new AccessToken(accessToken, accessSecret);
twitter.setOAuthAccessToken(accestoken);
Status status = twitter.updateStatus(testPost);
System.out.println("it worked!");
if (status.getId() == 0) {
System.out
.println("Error occured while posting tweets to twitter");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
why do i keep getting this error:
401:Authentication credentials (http://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid conumer key/secret, access token/secret, and the system clock in in sync.
error - Could not authenticate with OAuth.
request - /1/statuses/update.json
Relevant discussions can be on the Internet at:
http://www.google.co.jp/search?q=e06d87a8 or
http://www.google.co.jp/search?q=5851cbdb
TwitterException{exceptionCode=[e06d87a8-5851cbdb], statusCode=401, retryAfter=-1, rateLimitStatus=null, featureSpecificRateLimitStatus=null, version=2.2.3}
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:189)
at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:102)
at twitter4j.TwitterImpl.post(TwitterImpl.java:1871)
at twitter4j.TwitterImpl.updateStatus(TwitterImpl.java:459)
at twitter4j.examples.tweets.UpdateStatus.main(UpdateStatus.java:35)
i have set the credentials in the file already, have i not?

i figured it out heres a working code:
package twitter4j.examples.tweets;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import java.io.IOException;
public final class UpdateStatus {
public static void main(String[] args) throws IOException {
String tweet = "your first tweet via java";
String accessToken = "your access token";
String accessSecret = "your access token secret";
try {
TwitterFactory factory = new TwitterFactory();
Twitter twitter = factory.getInstance();
AccessToken accestoken = new AccessToken(accessToken, accessSecret);
twitter.setOAuthAccessToken(accestoken);
Status status = twitter.updateStatus(tweet);
System.out.println("it worked!");
if (status.getId() == 0) {
System.out
.println("Error occured while posting tweets to twitter");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
note: for this to work you MUST create an application on twitter
you must have a twitter4j.properties file which contain the following
debug set to true
oauth.consumerKey
oauth.consumerSecret
oauth.accessToken
oauth.accessTokenSecret
all the keys and tokens are from the twitter application
make sure your application access level all say "read and write"

Related

After Logout, login with the same user credentials is not working with Mongo Realm

I am using below code to log out the the current logged in user
public async Task Logout()
{
SecureStorage.RemoveAll();
await RealmMain.realmApp.CurrentUser.LogOutAsync();
}
Then, I use below code to sign in back again.
public async Task<bool> LoginWithCredential(Action<string> error)
{
try {
var credentials = Credentials.EmailPassword(userId, pass);
var user = await RealmMain.realmApp.LogInAsync(credentials);
return user != null;
}
catch (Exception ex){
SecureStorage.RemoveAll();
Console.WriteLine(ex);
error(exceptionText);
return false;
}
}
RealmMain Class is like this below.
public sealed class RealmMain
{
private const string AppId = "*************";
public static App realmApp = App.Create(AppId);
public SyncConfiguration ConfigForSync
{
get
{
var temp = new SyncConfiguration(realmApp.CurrentUser.Id, realmApp.CurrentUser)
{
// EncryptionKey = AppContext.GetBytes(AppContext.DbKey)
};
Console.WriteLine(temp.EncryptionKey);
return temp;
}
}
public static RealmMain Instance { get; } = new RealmMain();
private RealmMain()
{
}
}
Problem here is - When is log out and then try to sign in with the same user credential.
I get below error.
"Realms.Sync.Exceptions.AppException: Unknown: must authenticate first
at Realms.Sync.App.LogInAsync (Realms.Sync.Credentials credentials)"
If I use some different user to sign in after logging out.
I get this.
In nutshell Logout and then login is not working for me, I have to quit the app to make it work every time.
Any suggestion to solve this issue would be appreciated.

how to create NexmoClient object?

I tried to get NexmoClient object without success.
I Fill in API_KEY and API_SECRET with the values I copied from the Nexmo Dashboard.
import com.nexmo.client.NexmoClient;
import com.nexmo.client.auth.AuthMethod;
import com.nexmo.client.auth.TokenAuthMethod;
import com.nexmo.client.sms.SmsSubmissionResult;
import com.nexmo.client.sms.messages.TextMessage;
public class SendSMS {
public static void main(String[] args) throws Exception {
AuthMethod auth = new TokenAuthMethod(1111,22222);
NexmoClient client = new NexmoClient(auth);
}
}
"
After the Gradle run, I was expected to NexmoClient object as they wrote in the docs https://www.nexmo.com/blog/2017/05/03/send-sms-messages-with-java-dr/
for continue to the next step, but I didn't know where to insert the following info
TextMessage message = new TextMessage(FROM_NUMBER, TO_NUMBER, "Hello from
Nexmo!");
SmsSubmissionResult[] responses =
client.getSmsClient().submitMessage(message);
for (SmsSubmissionResult response : responses) {
System.out.println(response);
}
You can put that code below where you initialize the client. Your whole class will then look like this:
import com.nexmo.client.NexmoClient;
import com.nexmo.client.auth.AuthMethod;
import com.nexmo.client.auth.TokenAuthMethod;
import com.nexmo.client.sms.messages.TextMessage;
public class SendSMS {
private static final String FROM_NUMBER = "";
private static final String TO_NUMBER = "";
public static void main(String[] args) throws Exception {
AuthMethod auth = new TokenAuthMethod(1111, 22222);
NexmoClient client = new NexmoClient(auth);
TextMessage message = new TextMessage(FROM_NUMBER, TO_NUMBER, "Hello from Nexmo !");
SmsSubmissionResult[] responses = client.getSmsClient().submitMessage(message);
for (SmsSubmissionResult response : responses) {
System.out.println(response);
}
}
}
This blog post is actually a bit old and suggests using an older version of the server SDK. There's an updated example on the developer portal as some things have changed in the newer versions of the SDK: https://developer.nexmo.com/messaging/sms/code-snippets/send-an-sms

Fastest way to return view in customRestService using a bean

I have written a custom rest Service on an Xpage, which is tied to a bean. The Xpage is:
<xe:restService
id="restServiceCustom"
pathInfo="custom"
ignoreRequestParams="false"
state="false"
preventDojoStore="true">
<xe:this.service>
<xe:customRestService
contentType="application/json"
serviceBean="XXXX.PCServiceBean">
</xe:customRestService>
</xe:this.service>
</xe:restService>
I cobbled together my java agent from some excellent posts around the net. I have just started on the GET. My code runs but I it seems pretty slow (on my dev server). I want to make it as fast as possible. I am using a ViewEntryCollection and I am "flushing" at each record which I assume is streaming.
I am putting my own "[" in the code, so I assume that I am not doing something right, as I never saw any examples of anyone else doing this.
Any suggestions would be greatly appreciated.
package com.XXXXX.bean;
import java.io.IOException;
import java.io.Writer;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.openntf.domino.Database;
import org.openntf.domino.Session;
import org.openntf.domino.View;
import org.openntf.domino.ViewEntry;
import org.openntf.domino.ViewEntryCollection;
import org.openntf.domino.utils.Factory;
import com.ibm.commons.util.io.json.JsonException;
import com.ibm.commons.util.io.json.util.JsonWriter;
import com.ibm.domino.services.ServiceException;
import com.ibm.domino.services.rest.RestServiceEngine;
import com.ibm.xsp.extlib.component.rest.CustomService;
import com.ibm.xsp.extlib.component.rest.CustomServiceBean;
public class PCServiceBean extends CustomServiceBean {
#Override
public void renderService(CustomService service, RestServiceEngine engine) throws ServiceException {
try {
HttpServletRequest request = engine.getHttpRequest();
HttpServletResponse response = engine.getHttpResponse();
response.setHeader("Content-Type", "application/json; charset=UTF-8");
String method = request.getMethod();
if (method.equals("GET")) {
this.doGet(request, response);
} else if (method.equals("POST")) {
this.doPost(request, response);
} else if (method.equals("PUT")) {
this.doPut(request, response);
} else if (method.equals("DELETE")) {
this.doDelete(request, response);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void doDelete(HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
}
private void doPut(HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
}
private void doPost(HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
}
private void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, JsonException {
Session session = Factory.getSession();
Database DB = session.getDatabase(session.getCurrentDatabase().getServer(), "scoApps\\PC\\PCData.nsf");
View pcView = DB.getView("viewAllByStatus");
int i = 1;
Writer out = response.getWriter();
JsonWriter writer = new JsonWriter(out, false);
writer.out("[");
ViewEntryCollection vec = pcView.getAllEntries();
int count = vec.getCount();
for (ViewEntry entry : vec) {
Vector<?> columnValues = entry.getColumnValues();
writer.startObject();
writer.startProperty("unid");
writer.outStringLiteral(String.valueOf(columnValues.get(1)));
writer.endProperty();
writer.startProperty("status");
writer.outStringLiteral(String.valueOf(columnValues.get(0)));
writer.endProperty();
writer.startProperty("assetTag");
writer.outStringLiteral(String.valueOf(columnValues.get(2)));
writer.endProperty();
writer.startProperty("serialNumber");
writer.outStringLiteral(String.valueOf(columnValues.get(3)));
writer.endProperty();
writer.startProperty("model");
writer.outStringLiteral(String.valueOf(columnValues.get(4)));
writer.endProperty();
writer.startProperty("currentLocation");
writer.outStringLiteral(String.valueOf(columnValues.get(5)));
writer.endProperty();
writer.endObject();
if (i != count) {
i = i + 1;
writer.out(",");
writer.flush();
}
}
writer.out("]");
writer.flush();
}
}
Change your code to
JsonWriter writer = new JsonWriter(out, false);
writer.startArray();
ViewEntryCollection vec = pcView.getAllEntries();
int count = vec.getCount();
for (ViewEntry entry : vec) {
Vector<?> columnValues = entry.getColumnValues();
writer.startArrayItem();
writer.startObject();
writer.startProperty("unid");
writer.outStringLiteral(String.valueOf(columnValues.get(1)));
writer.endProperty();
...
writer.endObject();
writer.endArrayItem();
}
writer.endArray();
writer.flush();
It uses JsonWriter's
startArray() and endArray() instead of out("[") and out("]")
startArrayItem() and endArrayItem() instead of out(",") and flush()
The JSON response string gets shorter if you set JsonWriter's compact option to true:
JsonWriter writer = new JsonWriter(out, true);
I see two problems.
First - use ViewNavigator. Here's good explanation of its performance gain.
https://www.mindoo.com/web/blog.nsf/dx/17.01.2013085308KLEB9S.htm
Second - prepare your JSON in advance. This is very good technique to avoid unnecessary code (and time to process it) to get JSON data from Domino documents.
https://quintessens.wordpress.com/2015/09/05/working-with-json-in-your-xpages-application/

Groovy - Jira OAuth integration using HttpBuilder

I want to get data using JIRA REST api with provided JIRA OAuth authentication service.
Basically I'm able to achieve this task using ScribeJava with Groovy. But I want to decoupled all the process as below :-
Request to get request token
Request to get authorized URL
Request to access token
Request to get actual data using HTTPBuilder
So I'm able to achieve above mentioned first three steps using ScribeJava and storing the accessToken into Database for further request for data as below :-
import java.security.KeyFactory
import java.security.PrivateKey
import java.security.spec.PKCS8EncodedKeySpec
import com.github.scribejava.core.builder.api.DefaultApi10a
import com.github.scribejava.core.model.OAuth1RequestToken
import com.github.scribejava.core.services.RSASha1SignatureService
import com.github.scribejava.core.services.SignatureService
class JiraOauthProvider extends DefaultApi10a {
private String authURL
private String requestTokenURL
private String accessTokenURL
private String consumerPrivateKey
private JiraOauthProvider(authURL, requestTokenURL, accessTokenURL, consumerPrivateKey) {
this.authURL = authURL
this.requestTokenURL = requestTokenURL
this.accessTokenURL = accessTokenURL
this.consumerPrivateKey = consumerPrivateKey
}
private static JiraOauthProvider instance = null
public static JiraOauthProvider instance(Map map) {
if(instance == null) {
instance = new JiraOauthProvider(map.authURL,
map.requestTokenURL,
map.accessTokenURL,
map.consumerPrivateKey)
}
return instance
}
#Override
public String getAccessTokenEndpoint() {
return accessTokenURL
}
#Override
public String getRequestTokenEndpoint() {
return requestTokenURL
}
#Override
public String getAuthorizationUrl(OAuth1RequestToken requestToken) {
return String.format(authURL, requestToken.getToken())
}
#Override
public SignatureService getSignatureService() {
return new RSASha1SignatureService(getPrivateKey())
}
private PrivateKey getPrivateKey() {
byte[] key = Base64.getDecoder().decode(consumerPrivateKey)
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key)
KeyFactory kf = KeyFactory.getInstance("RSA")
return kf.generatePrivate(keySpec)
}
Now I'm building OAuthService as :-
private static final String CALLBACK_URI = "callback-url"
protected static final String CONSUMER_KEY = "consumer-key"
protected static final String CONSUMER_PRIVATE_KEY = "private-key"
Map oAuthMap = [
"authURL" :"auth-url=%s",
"requestTokenURL":"request-token-url",
"accessTokenURL":"access-token-url",
"consumerPrivateKey":CONSUMER_PRIVATE_KEY
]
//Buid oauth service to get request token, auth url and access token
OAuth10aService service = ServiceBuilder()
.apiKey(CONSUMER_KEY)
.apiSecret(CONSUMER_PRIVATE_KEY).callback(CALLBACK_URI)
.build(JiraOauthProvider.instance(oAuthMap))
OAuth1RequestToken requestToken = service.getRequestToken()
def authURL = service.getAuthorizationUrl(requestToken)
//Now after redirect to this authURL and providing credential I'm getting oauthVerifier code to get accessToken and secretToken
def oauthVerifier = "oauth verifier code"
//Now calling to get accessToken
OAuth1AccessToken oAuth1AccessToken = service.getAccessToken(requestToken, oauthVerifier);
def accessToken = oAuth1AccessToken.getToken()
def secretToken = oAuth1AccessToken.getTokenSecret()
//now I'm storing this `accessToken`and `secretToken` into DB for further future data request.
So after all above stuff I'm able to achieve above mentioned three steps and storing the access token into db for future request only for data.
So to achieve 4th step to getting actual data using HTTPBuilder I'm doing some thing as below :-
def http = new HTTPBuilder('base-url')
http.auth.oauth CONSUMER_KEY, CONSUMER_PRIVATE_KEY, accessToken, secretToken
http.request(Method.GET, ContentType.JSON) { req ->
uri.path = 'path'
response.success = { resp, json ->
println json
}
response.failure = { resp, json -> print json }
}
}
But I'm getting response as :-
{oauth_problem=signature_method_rejected}
So, could anyone suggest me how can I get actual data using HTTPBuilder with OAuth authentication using accessToken and secretToken?
Note:- I can get actual data as well using ScribeJava Api with OAuthRequest but requirement is to get actual data using HTTPBuilder
I just want a pointer that how to achieve it.
After lot of search I have got the solution from here. Actually HTTPBuilder internally using Signpost which signing the request using HmacSha Signer while Jira rest api supports RSA-SHA1 Signer to validate the HttpRequest that's why it's giving response as :-
{oauth_problem=signature_method_rejected}
So, basically I have to do custom RSA-SHA1 Signer to get the signature to http request. To achive this I'm using Google Data (GData) APIs to sign the data using RSA-SHA1 Signer before HttprRequest as below :-
private static PrivateKey getPrivateKey(String consumerKey) {
try {
byte[] key = Base64.getDecoder().decode(consumerKey)
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key)
KeyFactory kf = KeyFactory.getInstance("RSA")
return kf.generatePrivate(keySpec)
} catch (Exception e) {
throw new RuntimeException(e)
}
}
import com.google.gdata.client.authn.oauth.OAuthParameters
import com.google.gdata.client.authn.oauth.OAuthRsaSha1Signer
import com.google.gdata.client.authn.oauth.OAuthUtil
import com.google.gdata.client.authn.oauth.RsaSha1PrivateKeyHelper
OAuthRsaSha1Signer rsaSigner = new OAuthRsaSha1Signer()
rsaSigner.setPrivateKey(getPrivateKey(CONSUMER_PRIVATE_KEY))
OAuthParameters params = new OAuthParameters()
params.setOAuthConsumerKey(CONSUMER_KEY)
params.setOAuthNonce(OAuthUtil.getNonce())
params.setOAuthTimestamp(OAuthUtil.getTimestamp())
params.setOAuthSignatureMethod("RSA-SHA1")
params.setOAuthType(OAuthParameters.OAuthType.TWO_LEGGED_OAUTH)
params.setOAuthToken(accessToken)
String paramString = params.getBaseParameters().sort().collect{it}.join('&')
String baseString = [
OAuthUtil.encode("GET"),
OAuthUtil.encode('base-url' + 'path'),
OAuthUtil.encode(paramString)
].join('&')
String signature = rsaSigner.getSignature(baseString, params);
params.addCustomBaseParameter("oauth_signature", signature);
//Now calling using HTTPBuilder with signed data
def http = new HTTPBuilder('base-url')
http.request(Method.GET, ContentType.JSON) { req ->
uri.path = 'path'
uri.query = params.getBaseParameters()
response.success = { resp, json ->
println json
}
response.failure = { resp, json -> print json }
}
}

Creating a java client for secured esb proxy

I want to create a java client for version proxy service present in wso2 esb. I have secured the version proxy with Username Token Authentication scenario. Now i have started creating the java client to invoke this secured proxy service and my client code is:
package org.wso2.carbon.security.ws;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.description.AxisBinding;
import org.apache.axis2.description.AxisEndpoint;
import org.apache.axis2.rpc.client.RPCServiceClient;
import org.apache.neethi.Policy;
import javax.xml.namespace.QName;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map;
public class HelloServiceClient {
static {
System.setProperty("javax.net.ssl.trustStore", "/path/to/keystore" + File.separator+ "wso2carbon.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
}
public static void main(String[] args) {
try {
int securityScenario = getSecurityScenario();
String repository = "/path/to/repo" + File.separator + "repository";
ConfigurationContext confContext =
ConfigurationContextFactory.
createConfigurationContextFromFileSystem(repository, null);
String endPoint = "HelloServiceHttpSoap12Endpoint";
if(securityScenario == 1){
endPoint = "HelloServiceHttpsSoap12Endpoint"; // scenario 1 uses HelloServiceHttpsSoap12Endpoint
}
RPCServiceClient dynamicClient =
new RPCServiceClient(confContext,
new URL("http://pc213712:8281/services/Version?wsdl"),
new QName("http://version.services.core.carbon.wso2.org", "Version"),
endPoint);
//Engage Modules
dynamicClient.engageModule("rampart");
dynamicClient.engageModule("addressing");
//TODO : Change the port to monitor the messages through TCPMon
if(securityScenario != 1){
dynamicClient.getOptions().setTo(new EndpointReference("http://pc213712:8281/services/Version/"));
}
//Get the policy from the binding and append the rampartconfig assertion
Map endPoints = dynamicClient.getAxisService().getEndpoints();
AxisBinding axisBinding = ((AxisEndpoint) endPoints.values().iterator().next()).getBinding();
Policy policy = axisBinding.getEffectivePolicy();
**policy.addAssertion(RampartConfigBuilder.createRampartConfig(securityScenario));**
axisBinding.applyPolicy(policy);
//Invoke the service
Object[] returnArray = dynamicClient.invokeBlocking(new QName("http://www.wso2.org/types","greet"),
new Object[]{"Alice"},
new Class[]{String.class});
System.out.println((String) returnArray[0]);
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static int getSecurityScenario() {
int scenarioNumber = 0;
while (scenarioNumber < 1 || scenarioNumber > 15) {
System.out.print("Insert the security scenario no : ");
String inputString = readOption();
try {
scenarioNumber = new Integer(inputString);
} catch (Exception e) {
System.out.println("invalid input, insert a integer between 1 and 15");
}
if(scenarioNumber < 1 || scenarioNumber > 15){
System.out.println("Scenario number should be between 1 and 15");
}
}
return scenarioNumber;
}
private static String readOption() {
try {
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String str;
while ((str = console.readLine()).equals("")) {
}
return str;
} catch (Exception e) {
return null;
}
}
}
But in the above code i am struck at one line that is :
policy.addAssertion(RampartConfigBuilder.createRampartConfig(securityScenario));
Here in my rampart_core jar I am getting RampartConfigBuilder class but inside this class there is no such method called createRampartConfig. So i am unable to create Rampart configurations. What can i do to solve this issue? looking forward to your solutions. Thanks in advance

Resources