How to manage different TwitterStream from different Thread - java

i'm trying to execute different Thread using different TwitterStream object with an single authentication:
public class Support {
private static final String accessToken = "xxxxxxx";
private static final String accessTokenSecret = "xxxxxxx";
public static final AccessToken token = new AccessToken(accessToken, accessTokenSecret);
private static final String consumerKey = "xxxxxxx";
private static final String consumerSecret = "xxxxxxx";
private static final Configuration conf = new ConfigurationBuilder().setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret).build();
public static TwitterStreamFactory factory = new TwitterStreamFactory(conf);
}
In every Thread i do:
public MyThread1(){
this.twitterStream = Support.factory.getInstance(Support.token);
}
public void run(){
StatusListener listener = ... ;
twitterStream.addListener(listener);
FilterQuery fq = new FilterQuery();
fq.track(new String[]{"hashtag1","hashtag2"});
twitterStream.filter(fq);
}
public MyThread2(){
this.twitterStream = Support.factory.getInstance(Support.token);
}
public void run(){
StatusListener listener = ... ;
twitterStream.addListener(listener);
FilterQuery fq = new FilterQuery();
fq.track(new String[]{"hashtag3","hashtag4"});
twitterStream.filter(fq);
}
But it gives me authentication error.. multiple request of the same authentication. How can i solve?

Here is how I did it:
public class MyTwitterApp implements {
private Twitter twitter;
private Query query;
public MyTwitterApp (){
twitter = TwitterFactory.getSingleton();
}
public static void main(String[] args) {
MyTwitterApp twitterApp = new MyTwitterApp();
twitterApp.getStreamingTweets();
}
public void getStreamingTweets(){
StatusListener listener = new StatusListener(){
public void onStatus(Status status) {
handleStatus(status);
}
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {}
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {}
public void onException(Exception ex) {ex.printStackTrace(); }
public void onScrubGeo(long arg0, long arg1) {}
public void onStallWarning(StallWarning arg0) {}
};
twitter.addListener(listener);
FilterQuery fq = new FilterQuery();
fq.count(0);
fq.track(new String[]{"#MyHashTag"});
twitter.filter(fq);
}
protected void handleStatus(Status tweet) {
if(tweet.isRetweet()){
return;
}
if(isMyHashTagTweet(tweet)){
//do something with tweet here
}
}
private boolean isMyHashTagTweet(Status tweet) {
HashtagEntity[] htes = tweet.getHashtagEntities();
for(HashtagEntity hte : htes){
if(hte.getText().equalsIgnoreCase("myhashtag")) {
return true;
}
}
return false;
}
}
Each thread will contain something like this.
twitter = TwitterFactory.getSingleton();
Will make sure you are reusing the same connection each time.
twitter.addListener(listener);
Will add a listener so that you will get called back to this thread (but you will get called back from every query added)
twitter.filter(fq);
Will add a new search query to follow.
isMyHashTagTweet(tweet)
Will check to make sure that the tweet returned by all queries live in your twitterStream are relevant for your current thread

Related

How to implement builder inside my already defined class

I am trying to convert my class to support builder in order to prettify my code, this is the code I am using and I try to define my method called addSMTPIntegration to use builder.
this is my class:
public class IntegrationsPage extends SettingsTab {
private static final By newIntegrationBth = Locators.findBy("settings_page_integrations_page_add_new_button");
private IntegrationsTable integrationsTable;
private SmtpIntegrationForm smtpIntegrationForm;
private ConfirmPopup confirmPopup;
public IntegrationsPage(DriverWrapper driver){
super(driver, "integrations",newIntegrationBth);
integrationsTable = new IntegrationsTable(driver);
smtpIntegrationForm = new SmtpIntegrationForm(driver);
confirmPopup = new ConfirmPopup(driver);
}
public void addSMTPIntegration(String name, String server, String port, String fromAddress, boolean mode, String userName, String password){
clickNewIntegrationButton();
smtpIntegrationForm.chooseIntegration(IntegrationType.SMTP);
smtpIntegrationForm.setIntegrationName(name);
smtpIntegrationForm.setIntegrationServer(server);
smtpIntegrationForm.setIntegrationPort(port);
smtpIntegrationForm.setIntegrationFromAddress(fromAddress);
smtpIntegrationForm.setIntegrationAuth(mode);
smtpIntegrationForm.setIntegrationUserName(userName);
smtpIntegrationForm.setIntegrationPassword(password);
smtpIntegrationForm.clickSaveButton();
LOG.i("SMTP configuration passed successfully");
}
private void clickNewIntegrationButton(){
clickButton(newIntegrationBth);
}
public IntegrationsRow waitIntegrationRowTable(String configurationName) {
return integrationsTable.waitRowDisplay(configurationName);
}
public boolean deleteIntegration(String integrationName) {
integrationsTable.findRow(integrationName).clickRow();
integrationsTable.delete(integrationName);
confirmPopup.clickYes();
return integrationsTable.findRow(integrationName) == null;
}
}
I am trying to define my addSMTPIntegration method to support builder in a manner that I would be able to build it in the following way:
smtpIntegrationForm.chooseIntegration(IntegrationType.SMTP).setIntegrationName(name).setIntegrationServer(server).... etc
This is my smtpIntegrationForm class:
public class SmtpIntegrationForm extends IntegrationCommonSection {
private static final By integrationServerBy = Locators.findBy("settings_page_integrations_page_integration_server_name_txt");
private static final By integrationPortBy = Locators.findBy("settings_page_integrations_page_integration_port_txt");
private static final By integrationFromAddressBy = Locators.findBy("settings_page_integrations_page_integration_from_address_txt");
SmtpIntegrationForm(DriverWrapper driver){
super(driver);
}
void setIntegrationServer(String server){
setText(integrationServerBy, server);
}
void setIntegrationPort(String port){
setText(integrationPortBy, port);
}
void setIntegrationFromAddress(String address){
setText(integrationFromAddressBy, address);
}
void chooseIntegration(IntegrationType integrationType){
clickButton(By.cssSelector("li[class~='qa_" + integrationType.value + "']"));
}
and this is IntegrationCommonSection class:
class IntegrationCommonSection extends PageElement {
private static final By integrationNameBy = Locators.findBy("settings_page_integrations_page_integration_name_txt");
private static final By integrationAuthBy = Locators.findBy("settings_page_integrations_page_integration_auth_bth");
private static final By integrationUserNameBy = Locators.findBy("settings_page_integrations_page_integration_username_txt");
private static final By integrationPasswordBy = Locators.findBy("settings_page_integrations_page_integration_password_txt");
private static final By integrationSaveBthBy = Locators.findBy("settings_page_integrations_page_integration_save_bth");
private static final By integrationTestBthBy = Locators.findBy("settings_page_integrations_page_integration_test_bth");
IntegrationCommonSection(DriverWrapper driver){
super(driver);
}
void setIntegrationName(String name){
clearAndSetCharacters(integrationNameBy, name);
}
void setIntegrationAuth(boolean mode){ //true - with auth, false - no auth
if(!isCheckBoxEnabled(integrationAuthBy) && mode) {
clickButton(integrationAuthBy);
}
}
void setIntegrationUserName(String userName){
setText(integrationUserNameBy, userName);
}
void setIntegrationPassword(String password){
setText(integrationPasswordBy, password);
}
void clickSaveButton(){
clickButton(integrationSaveBthBy);
}
void clickTestButton(){
clickButton(integrationTestBthBy);
}
}
just return "this" :
SmtpIntegrationForm setIntegrationServer(String server){
setText(integrationServerBy, server);
return this;
}
In order to do that, you need to modify the methods of SmtpIntegrationForm with the return of this object so that you can construct the statements in a builder pattern. There is nothing you can do in addSMTPIntegration() method to achieve this.
chooseIntegration(), setIntegrationName(), setIntegrationServer(), etc. methods inside SmtpIntegrationForm should have return type of SmtpIntegrationForm and the last statement in these methods should be return this; in order for you to achieve this.
Make the changes as:
public class SmtpIntegrationForm extends IntegrationCommonSection {
private static final By integrationServerBy = Locators.findBy("settings_page_integrations_page_integration_server_name_txt");
private static final By integrationPortBy = Locators.findBy("settings_page_integrations_page_integration_port_txt");
private static final By integrationFromAddressBy = Locators.findBy("settings_page_integrations_page_integration_from_address_txt");
SmtpIntegrationForm(DriverWrapper driver){
super(driver);
}
SmtpIntegrationForm setIntegrationServer(String server){
setText(integrationServerBy, server);
return this;
}
SmtpIntegrationForm setIntegrationPort(String port){
setText(integrationPortBy, port);
return this;
}
SmtpIntegrationForm setIntegrationFromAddress(String address){
setText(integrationFromAddressBy, address);
return this;
}
SmtpIntegrationForm chooseIntegration(IntegrationType integrationType){
clickButton(By.cssSelector("li[class~='qa_" + integrationType.value + "']"));
return this;
}
}

synchronized before field outside of new Thread()

I want to make a part of asynchronous. I added a new Thread() and put to it code. What have to be done with fields and methods outside?
public class Record {
private String actionDetails;
public void setActionDetails(String actionDetails) {
this.actionDetails = actionDetails;
}
}
public class Recorder {
private Record record;
public void record(Record record){
this.record = record;
}
}
public class Test {
private static Recorder recorder = new Recorder();
private static StringBuilder builder;
public static void main(String[] args) {
builder.append("Test");
new Thread(() -> {
final Record record = new Record();
record.setActionDetails(builder.toString());
recorder.record(record);
}).start();
}
}
I think that for recorder, record(), setActionDetails() should use synchronized modificator and use StringBuffer instead StringBuilder.

Method that returns two classes in java

I have two classes:
public class UnoLoginPageUi {
public final Input username = new Input("id=username");
public final Input password = new Input("id=password");
public final Button loginButton = new Button("name=login");
}
and
public class DuoLoginPageUi {
public final Input username = new Input("id=usernameField");
public final Input password = new Input("id=passwordField");
public final Button loginButton = new Button("id=submitButton");
}
and in one common class I want to make something like that:
public void loginUsingUsernameAndPassword(String username, String password, String pageType) {
getUi(pageType).username.waitForToBeDisplayed();
getUi(pageType).username.setValue(username);
getUi(pageType).password.setValue(password);
getUi(pageType).loginButton.click();
}
where getUi() is a method that gas argument pageType (which is UNO or DUO).
private Class getUi(String pageType) {
if (pageType.equals("UNO")) {
return new DuoLoginPageUi();
}
else if (pageType.equals("DUO")) {
return new UnoLoginPageUi;
}
return null;
}
However it doesn't work as this method need to in type of this two pages with selectors - how to deal with that ?
You can create a interface called LoginPageUi. And let your UnoLoginPageUi and DuoLoginPageUi implement that interface.
Then your getUi method will be private LoginPageUi getUi(String pageType).
Off topic: I would recommend to implement an enum instead of String pageType.
Create a common abstraction for the two classes
public abstract class LoginPageUi {
public final Input username = new Input("id=username");
public final Input password = new Input("id=password");
public final Button loginButton = new Button("name=login");
}
and have UnoLoginPageUi and DuoLoginPageUi extend that
public class UnoLoginPageUi extends LoginPageUi {
public static String getPageType() { return "UNO"; }
}
public class DuoLoginPageUi extends LoginPageUi {
public static String getPageType() { return "DUO"; }
}
The method would return the common abstraction
private LoginPageUi getUi(String pageType) {
if (pageType.equals(DuoLoginPageUi.getPageType())) {
return new DuoLoginPageUi();
}
else if (pageType.equals(UnoLoginPageUi.getPageType())) {
return new UnoLoginPageUi;
}
return null;
}
I also hope you realize that every time you call getUi(pageType) it is returning a new instance. by the time you call getUi(pageType).loginButton.click(); the instance returned has no values set.
Refactor:
public void loginUsingUsernameAndPassword(String username, String password, String pageType) {
LoginPageUi ui = getUi(pageType);
if (ui != null) {
ui.username.waitForToBeDisplayed();
ui.username.setValue(username);
ui.password.setValue(password);
ui.loginButton.click();
}
}
create Parent class or interface for both called UI:
public abstract class Ui{
}
public interface Ui{
}
and extend it:
public class UnoLoginPageUi extends Ui{
public final Input username = new Input("id=username");
public final Input password = new Input("id=password");
public final Button loginButton = new Button("name=login");
}
public class DuoLoginPageUi extends Ui {
public final Input username = new Input("id=usernameField");
public final Input password = new Input("id=passwordField");
public final Button loginButton = new Button("id=submitButton");
}
or
public class UnoLoginPageUi implements Ui{
public final Input username = new Input("id=username");
public final Input password = new Input("id=password");
public final Button loginButton = new Button("name=login");
}
public class DuoLoginPageUi implements Ui {
public final Input username = new Input("id=usernameField");
public final Input password = new Input("id=passwordField");
public final Button loginButton = new Button("id=submitButton");
}
then return parent reference as:
private Ui getUi(String pageType) {
if (pageType.equals("UNO")) {
return new DuoLoginPageUi();
}
else if (pageType.equals("DUO")) {
return new UnoLoginPageUi;
}
return null;
}

android java is not enclosing class

this is my class
public class mm {
public class MessageHandler {
public HashMap<String, Command> commandMap;
public MessageHandler() {
this.commandMap = new HashMap<>();
commandMap.put("init", new CreateOfferCommand());
commandMap.put("offer", new CreateAnswerCommand());
commandMap.put("answer", new SetRemoteSDPCommand());
commandMap.put("candidate", new AddIceCandidateCommand());
}
public Emitter.Listener onMessage = new Emitter.Listener() {
#Override
public void call(Object... args) {
JSONObject data = (JSONObject) args[0];
try {
String from = data.getString("from");
String type = data.getString("type");
JSONObject payload = null;
if(!type.equals("init")) {
payload = data.getJSONObject("payload");
}
// if peer is unknown, try to add him
if(!peers.containsKey(from)) {
// if MAX_PEER is reach, ignore the call
int endPoint = findEndPoint();
if(endPoint != MAX_PEER) {
Peer peer = addPeer(from, endPoint);
peer.pc.addStream(localMS);
commandMap.get(type).execute(from, payload);
}
} else {
commandMap.get(type).execute(from, payload);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
public Emitter.Listener onId = new Emitter.Listener() {
#Override
public void call(Object... args) {
String id = (String) args[0];
mListener.onCallReady(id);
}
};
public Emitter.Listener onCall = new Emitter.Listener() {
#Override
public void call(Object... args) {
String id = (String) args[0];
mListener.onCalling(id);
}
};
}
......................
.........
}
and when i call the inner class from another class its give me an enclosing class
mm.MessageHandler messageHandler = new mm.MessageHandler();
when i make inner class messageHandler a static the error gone but its shown anothe error inside inner class so can i call the inner class without make it static ?
mm n = new mm();
mm.MessageHandler messageHandler = n.new MessageHandler();
or use static in your inner class
hope that's help

Passing information from interceptor to controller method

I am Using Play 2.3 (Java).
I have a onRequest method inside my Global.java file.
Following some answers on Stackoverflow and other resources, my Global.java is like -
private static ArrayList<String> admin_users = new ArrayList<String>();
public static ArrayList<String> getAdmin_users() {
return admin_users;
}
public static void setAdmin_users(ArrayList<String> admin_users) {
Global.admin_users = admin_users;
}
#Override
public void onStart(play.Application arg0) {
ArrayList<String> admins = new ArrayList<String>();
admins.add("aahuja");
admins.add("chlr");
admins.add("bobba");
setAdmin_users(admins);
}
private static ArrayList<String> admin_users = new ArrayList<String>();
public static ArrayList<String> getAdmin_users() {
return admin_users;
}
public static void setAdmin_users(ArrayList<String> admin_users) {
Global.admin_users = admin_users;
}
#Override
public void onStart(play.Application arg0) {
ArrayList<String> admins = new ArrayList<String>();
admins.add("aahuja");
admins.add("chlr");
admins.add("bobba");
setAdmin_users(admins);
}
private class ActionWrapper extends Action.Simple {
private String user;
public ActionWrapper(Action<?> action, String user) {
this.delegate = action;
this.user = user;
}
#Override
public Promise<Result> call(Http.Context ctx) throws java.lang.Throwable {
Promise<Result> result = this.delegate.call(ctx);
ctx.args.put("Name", this.user);
}
#Override
public Action<?> onRequest(Http.Request request, java.lang.reflect.Method actionMethod) {
if(request.getHeader("OriginalName") != null){
if(getAdmin_users().contains(request.getHeader("OriginalName"))){
if(request.hasHeader("IMPERSONATE") && request.getHeader("IMPERSONATE").equals("true")){
return new ActionWrapper(super.onRequest(request, actionMethod), request.getHeader("IMPERSONATE-IDENTITY"));
}
}
return new ActionWrapper(super.onRequest(request, actionMethod), request.getHeader("OriginalName"));
}
else
return super.onRequest(request, actionMethod);
}
Now, inside my controller file, I have a method like this -
public static Promise<Result> all() {
String name = (String) ctx().args.get("Name");
System.out.println(name);
// rest of code
}
Now when I pass a request to this application with the header information like -
OriginalName: abcd, I get a value of null inside my controller printed out.
Is ctx the correct way to pass data? If not whats the correct way.
I am trying to take the redundant logic out of the main business logic.
The same can also be achieved if we are able to modify the header information when it gets passed from the interceptor to the controller. But I cant find any suitable way of doing so.
Try to put the ctx.args.put() before calling the delegate:
#Override
public Promise<Result> call(Http.Context ctx) throws java.lang.Throwable {
ctx.args.put("Name", this.user);
Promise<Result> result = this.delegate.call(ctx);
}
You are setting the value afther your action run. So you cannot access the value inside your action.

Categories

Resources