I'm working in a project in Java and I need to follow some twitter account to collect data about the traffic.
I started using the Twitter API but suddenly i found the limit too low so I changed to the stream API. Here there is no limit but I only know how to search something into the currect stream, not to get only the streams from the accounts I want.
Is that posiible with the twitter4J api?
My code is the following one:
TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
StatusListener listener = new StatusListener() {
#Override
public void onException(Exception arg0) {
// TODO Auto-generated method stub
}
#Override
public void onDeletionNotice(StatusDeletionNotice arg0) {
// TODO Auto-generated method stub
}
#Override
public void onScrubGeo(long arg0, long arg1) {
// TODO Auto-generated method stub
}
#Override
public void onStatus(Status status) {
//I process the tweet.
}
#Override
public void onTrackLimitationNotice(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStallWarning(StallWarning arg0) {
// TODO Auto-generated method stub
}
};
FilterQuery fq = new FilterQuery();
String keywords[] = {"a","e","i","o","u"};
fq.track(keywords);
twitterStream.addListener(listener);
twitterStream.filter(fq);
You can specify users you want to follow using the FilterQuery object, e.g.:
long[] userIds = { ...omitted... };
fq.follow(userIds);
twitterStream.filter(fq);
Be aware that when filtering Tweets only need to match one of the conditions, i.e. the track or follow, so you may need to do some manual filtering if you intend to use both.
For more information check out Twitter's documentation for the follow parameter and filter stream.
twitter.createFriendship("screenName");
Related
I'm using Postman to test Chat feature (socket.io technology with version 2).
Currently, i have to implement Chat test cases using Java.
Postman request information:
1. Socket server: https://hc-socketio-example.xyz
2. Header.authorization: xxx
3. Header.source: app
4. Message.text with JSON format:
{ "ticketId": "63bcc910c22293b4b0495fe4", "content": "test ", "type": "text"}
My Java code to connect socket server:
URI uri = URI.create("https://hc-socket.unibag.xyz");
// #formatter:off
IO.Options options = IO.Options.builder().build();
// #formatter:on
Socket socket = IO.socket(uri, options);
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
System.out.println("Connected to server...");
}
});
socket.connect();
My issues need the help:
Look like my code gets wrong because no String "Connected to server..." printed.
I don't know the way to set the header or request: "authentication", "source"
I'm not sure the way to send JSON message like above:
COULD SOMEONE TAKE A LOOK AND GIVE ME THE ADVISE IN ORDER I COULD FIX MY CODE?
THANKS A LOT IN ADVANCE.
I tried researching on the internet some examples but no luck. I'm confusing about the way to send socket request.
Chats are typically facilitated through web sockets over http, assuming you want to build a chat system that runs over the internet.
I have a working program written that can establish a connection and send/receive messages from the Chat Server.
As a prerequisite you need a third party library.
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.0</version>
</dependency>
Also accompanied is the piece of client code that can send headers, get acknowledgement for connections and send/receive json messages
public class ChatWebSocketClient extends WebSocketClient{
public ChatWebSocketClient(URI serverURI, Map<String, String> headers) {
super(serverURI, new Draft_17(), headers, 0);
}
#Override
public void onOpen(ServerHandshake handshakedata) {
// TODO Auto-generated method stub
}
#Override
public void onMessage(String message) {
// TODO Auto-generated method stub
}
#Override
public void onClose(int code, String reason, boolean remote) {
// TODO Auto-generated method stub
}
#Override
public void onError(Exception ex) {
// TODO Auto-generated method stub
}
public static void main(String args[]) throws Exception {
Map<String, String> headers = new HashMap();
headers.put("header1", "value1 for header1");
ChatWebSocketClient client = new ChatWebSocketClient(new URI("Remote_Chat_EndPoint"), headers);
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
#Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return new java.security.cert.X509Certificate[]{};
}
#Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// TODO Auto-generated method stub
}
#Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// TODO Auto-generated method stub
}
}};
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
client.setWebSocketFactory(new DefaultSSLWebSocketClientFactory(sc));
client.connect();
client.send("{\"key\":\"Hello World\"}");
}
}
I don't know how to acquire token without username and password using the adal4j library. I have this code:
public class GetToken implements AuthenticationCallback {
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "resource";
String redirectUrl = "redirecturl";
String authority = "https://login.microsoftonline.com/common/";
ExecutorService executor = null;
ClientAssertion clientId = new ClientAssertion("my-client-id");
AuthenticationCallback callback;
// Authenticate the registered application with Azure Active Directory.
AuthenticationContext authContext;
try {
authContext = new AuthenticationContext(authority, false,executor);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Future <AuthenticationResult> result = authContext.acquireToken(resource, clientId, callback);
}
#Override
public void onSuccess(AuthenticationResult result) {
// TODO Auto-generated method stub
}
#Override
public void onFailure(Throwable exc) {
// TODO Auto-generated method stub
}
}
And I don't know how to acquire token ....
Check this link: https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-devquickstarts-webapp-java#step-8-create-the-basicfilter-file-for-basicfilter-mvc
Look into the getAccessToke() method.This is what you're looking for:
ExecutorService executor = Executors.newFixedThreadPool(1);
Hope this helps!
You will get an IllegalArgumentException as the Executor service passed to AuthenticationContext is null.
it is throw NullPointerException when i use RPCServiceClient and asynchronous call.But it is normal using RPCServiceClient.invokeBlocking.
my axis2 version is 1.6.4.
this is my code:
public void sendMsg(String xmldata, AxisCallback callback) throws AxisFault {
String webServiceURL = "http://171.8.212.68:8191/axis2/services/UserService";
String sendflag = "true";
if ("true".equals(sendflag)) {
RPCServiceClient serviceClient = new RPCServiceClient();
Options options = serviceClient.getOptions();
EndpointReference targetEPR = new EndpointReference(webServiceURL);
options.setTo(targetEPR);
Object[] opAddEntryArgs = new Object[]{xmldata};
QName opAddEntry = new QName("http://downstream.sysinterface.topsms.topnet.com", "sendMsg");
if (callback == null) {
callback = new AxisCallback() {
public void onComplete() {
// TODO Auto-generated method stub
System.out.println("***********onComplete");
}
public void onError(Exception exception) {
// TODO Auto-generated method stub
exception.printStackTrace();
System.out.println("***********onError:"+exception.getMessage()+":"+ Arrays.toString(exception.getStackTrace()));
System.out.println(getStackTrace(exception));
}
public void onFault(MessageContext context) {
// TODO Auto-generated method stub
System.out.println("***********onFault");
}
public void onMessage(MessageContext context) {
// TODO Auto-generated method stub
System.out.println("***********onMessage");
}
};
}
serviceClient.invokeNonBlocking(opAddEntry, opAddEntryArgs, callback);
serviceClient.cleanupTransport();
serviceClient.cleanup();
}
}
Exception is below:
java.lang.NullPointerException
at org.apache.axis2.context.AbstractContext.needPropertyDifferences(AbstractContext.java:239)
at org.apache.axis2.context.AbstractContext.setProperty(AbstractContext.java:202)
at org.apache.axis2.transport.http.AbstractHTTPSender.getHttpClient(AbstractHTTPSender.java:568)
at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:157)
at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:75)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:396)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:223)
at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:443)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:406)
at org.apache.axis2.description.OutInAxisOperationClient$NonBlockingInvocationWorker.run(OutInAxisOperation.java:446)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:767)
My post request code as follows
When post request to the server it reach twice in to the server
and i am sure call httpRequest once.When i call once the request reach server twice or thrise;
private void invokePostOrderRestService(
final RestPostDataCallback<Order> callback,
final RequestOrder requestOrder) {
String URL = BASE_URL + "postOrder";
Log.e("post ordercccccc", "orderPosted");
JSONObject jsonObject = convertOrderRequestToJson(requestOrder);
if (jsonObject != null) {
OrderProApplication
.getContext()
.getRestClient()
.postJsonObject(URL, jsonObject,
new ResponseListener<JSONObject>() {
#Override
public void onSuccess(JSONObject response) {
// TODO Auto-generated method stub
Log.e("Order Post Success","Post Order Successssssssssssssssss");
String status = "";
try {
status = response.getString("status");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (status.equals("OK")) {
callback.onRestPostDataCompleted(
ResultCode.RESULT_OK, null);
} else {
callback.onRestPostDataCompleted(
ResultCode.RESULT_FAIL, null);
}
}
#Override
public void onRestError(RestError error) {
// TODO Auto-generated method stub
Log.e("Order Post Failed","Post Order failedddddddddddddddddddd");
i = i + 1;
callback.onRestPostDataCompleted(
ResultCode.RESULT_FAIL, null);
}
});
} else {
callback.onRestPostDataCompleted(ResultCode.RESULT_FAIL, null);
}
}
And am pretty sure my url is correct.
Thanks:).
Most likely your method is being called twice. Check where you are calling out the method - this might be occurred thanks to misunderstanding of Activity/Fragment lifecycle.
Put a print in the beginning of your invoke method and check, if it prints out twice.
I am trying to write a Http API in android. I am using a AsyncTask to run the calls to my web service.I am not interested in updating the UI, instead all I want is the data to use in my application logic. This is what I have so far:
public class DataManager{
public static String result;
public DataManager ()
{
}
public String get ()
{
User user = new User ();
user.execute("http://someuri/service/users/id/21001");
return user.getResult();
}
}
public class User extends AsyncTask <String,Void,String>{
private String result;
#Override
protected String doInBackground(String... arg0)
{
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet (arg0[0]);
try
{
HttpResponse response = client.execute (get);
if (response.getStatusLine().getStatusCode () == 200)
{
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity);
}
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
this.result = result;
}
public String getResult ()
{
return result;
}
}
I want a typical call to be:
DataManager manager = new DataManager ();
String value = manager.get ();
But when I run this I get back null. What is causing this and how can I refactor this code to get the desired behavior.
The whole idea of a thread is that it runs concurrently. Basically, here's what you're doing:
User user = new User (); // Create User object
user.execute("http://someuri/service/users/id/21001"); // Start thread
return user.getResult(); // Return thread result
However, there is no time for the thread to run between "start" and "return result".
I would suggest using some kind of callback; first, make get() return void, and remove the return statement. Then, you pass in some object which implements YourCallback, and then call onCallback(result) from within onPostExecute().
Your calling code would then look like this:
DataManager x = new DataManager();
x.get(new YourCallback() {
public void onCallback(String result) {
// ...
}
});
There is a much fuller example in this fantastic answer.