I'm having trouble figuring how to deal with disconnections with hbc twitter api. The doc says I need slow down reconnect attempts according to the type of error experienced. Where do I get the type of error experienced? Is it in the msgQueue or the eventQueue or wherever?
#Asynchronous
#Override
public void makeLatestsTweets() {
msgList = new LinkedList<Tweet>();
BlockingQueue<String> msgQueue = new LinkedBlockingQueue<String>(100);
BlockingQueue<Event> eventQueue = new LinkedBlockingQueue<Event>(100);
Hosts hosebirdHosts = new HttpHosts(Constants.SITESTREAM_HOST);
StatusesFilterEndpoint hosebirdEndpoint = new StatusesFilterEndpoint();
userIds = addFollowings();
hosebirdEndpoint.followings(userIds);
Authentication hosebirdAuth = new OAuth1(CONSUMER_KEY, CONSUMER_SECRET,
TOKEN, SECRET);
ClientBuilder builder = new ClientBuilder().hosts(hosebirdHosts)
.authentication(hosebirdAuth).endpoint(hosebirdEndpoint)
.processor(new StringDelimitedProcessor(msgQueue))
.eventMessageQueue(eventQueue);
Client hosebirdClient = builder.build();
hosebirdClient.connect();
while (!hosebirdClient.isDone()) {
try {
String msg = msgQueue.take();
Tweet tweet = format(msg);
if (tweet != null) {
System.out.println(tweet.getTweetsContent());
msgList.addFirst(tweet);
if (msgList.size() > tweetListSize) {
msgList.removeLast();
}
caller.setMsgList(msgList);
}
} catch (InterruptedException e) {
hosebirdClient.stop();
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Related
I have a queue on Rabbitmq and each time I run my code the queue on the rebbitmq website is empty. I think it's because each time the basicConsume fetches all of the elements at once.
I need help in a way to get an element one at a time.
this is the function to add to queue:
public static void addToQueueRabbit(String qname, String id) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
//If we wanted to connect to a node on a different machine we'd simply specify its hostname or IP address here
factory.setHost("localhost");
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
//Declaring a queue is idempotent - it will only be created if it doesn't exist already.
channel.queueDeclare(qname, false, false, false, null);
String message = id;
channel.basicPublish("", qname, null, message.getBytes());
System.out.println( "Added to queue: "+qname);
}
}
this code is how the queue build:
public class waitingQueueConsumer implements Runnable {
private ConnectionFactory factory;
private Connection connection;
private Channel channel;
public waitingQueueConsumer() throws TimeoutException, IOException {
factory = new ConnectionFactory();
factory.setHost("localhost");
connection = factory.newConnection();
channel = connection.createChannel();
//declare the queue from which we're going to consume
channel.queueDeclare("waitingQueue", false, false, false, null);
// System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
System.out.println("init waitingQueueConsumer DONE");
}
public synchronized void run() {
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
//spliited to ID:permit:token
String[] splitted = message.split(":");
int permit = Integer.parseInt(splitted[1]);
String token = splitted[2];
System.out.println("permit: "+permit);
permit--;
//update the permit
message = splitted[0]+":"+permit+":"+token;
//TODO send the api request.
String id = splitted[0];
//to change to production when ready
apiService APICall= new apiService(id,token);
Boolean isUrlExist = null;
boolean isUrlExistArray[]=null;
boolean isMotobiEmpty= false;
Boolean tokenExpired = false;
JSONObject jsonObject=null;
try {
jsonObject = APICall.send();
if (jsonObject.get("data") instanceof JSONArray) {
tokenExpired=true;
}
else {
isUrlExistArray = APICall.checkForCsvLink(jsonObject);
if(isUrlExistArray[0]== true && isUrlExistArray[1]==false){
String urlMotobi = APICall.returnMotobiUrl(jsonObject);
csvCompare csvUrl = new csvCompare(urlMotobi, "");
isMotobiEmpty= csvUrl.checkIfReportEmpty(urlMotobi);
}
isUrlExist = isUrlExistArray[0] && isUrlExistArray[1];
}
} catch(ParseException e){
e.printStackTrace();
} catch(InterruptedException e){
e.printStackTrace();
}
try {
if(tokenExpired == true){
buildMail mymail = new buildMail(jsonObject);
mymail.mailForTokenExpired(id, token);
}
else if (isMotobiEmpty == true){
queueUtils.addToQueueRabbit("comparingQueue", "equal&" + id);
}
else if (isUrlExist) {
//the report is ready lets take the urls
//url1&url2&id
String urls = "";
urls = APICall.returnUrls(jsonObject);
APICall.setMailInfo(jsonObject);
queueUtils.addToQueueRabbit("comparingQueue", urls + "&" + id);
} else if (permit > 0) {
System.out.println("waiting 30 secs");
queueUtils.addToQueueRabbit("waitingQueue", message);
sleep(30000);
} else {
//inc the reports we handled
TestServiceApplication.compareReportsCounter++;
int num = TestServiceApplication.compareReportsCounter;
buildMail mymail = new buildMail(jsonObject);
mymail.mailForUnreadyUrl(APICall, isUrlExistArray, id);
}
} catch (TimeoutException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
};
try {
channel.basicConsume("waitingQueue", true, deliverCallback, consumerTag -> { });
} catch (IOException e) {
e.printStackTrace();
}
}
}
i would like for help in explanation how to get only the fist element from rabbitmq and if its possible at all.
I'm writing a Java bot with https://github.com/rubenlagus/TelegramBots, and I have a problem, when I click inline keyboard button, this little clock:
appears and after some time it says that my bot is not responding. My bot is actually fully functional except this one thing. Here is how I receive callbacks:
#Override
public void onUpdateReceived(Update update) {
var messagesToSend = updateReceiver.handle(update);
if (messagesToSend != null && !messagesToSend.isEmpty()) {
messagesToSend.forEach(response -> {
if (response instanceof SendMessage) {
try {
execute((SendMessage) response);
} catch (TelegramApiException e) {
e.printStackTrace();
}
} else if (response instanceof SendPhoto) {
try {
execute((SendPhoto) response);
} catch (TelegramApiException e) {
e.printStackTrace();
}
} else if (response instanceof FileSaveRequest) {
FileSaveRequest request = (FileSaveRequest) response;
try {
saveFile(request);
} catch (TelegramApiException | IOException e) {
e.printStackTrace();
}
}
});
}
}
=
This is only part of the whole code
} else if (update.hasCallbackQuery()) {
final CallbackQuery callbackQuery = update.getCallbackQuery();
final long chatId = callbackQuery.getFrom().getId();
final User user = userRepository.findById(chatId)
.orElseGet(() -> userRepository.save(new User(chatId)));
AnswerCallbackQuery acceptCallback = new AnswerCallbackQuery();
acceptCallback.setShowAlert(false);
acceptCallback.setCallbackQueryId(String.valueOf(update.getCallbackQuery().getId()));
acceptCallback.setCacheTime(1000);
List<PartialBotApiMethod<? extends Serializable>> resultList =
new ArrayList<>(
getHandlerByCallBackQuery(callbackQuery.getData())
.handle(user, callbackQuery.getData()));
resultList.add(acceptCallback);
return resultList;
}
As you can see, I still attach AnswerCallbackQuery but it still doesent work. What's wrong?
you must use answercallbackquery
I just already solve that issue. It's not problem on Library but it could error in some exceptions.
var messagesToSend = updateReceiver.handle(update);
if (messagesToSend != null && !messagesToSend.isEmpty()) {
I dont have full your code but I think there's some confused written and happen exception before if (update.callbackQuery())...
Here is my sample:
#Override
public void onUpdateReceived(Update update) {
// I have error, cannot getCallbackQuery because of print which call method getMessage.getText() is null -> happen exception error on the println
// -> System.out.println(update.getMessage.getText());
if (update.hasMessage() && !update.getMessage().getText().isEmpty()) {
String chat_id = update.getMessage().getChatId().toString();
if (update.getMessage().getText().equals("/start")) {
SendMessage sendMessage = new SendMessage();
sendMessage.setText("Here is option:");
sendMessage.setChatId(chat_id);
sendMessage.setParseMode(ParseMode.MARKDOWN);
InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
List<List<InlineKeyboardButton>> listInlineButton = new ArrayList<>();
List<InlineKeyboardButton> reportSaleBtn = new ArrayList<>();
List<InlineKeyboardButton> reportBuyBtn = new ArrayList<>();
List<InlineKeyboardButton> reportPriceBtn = new ArrayList<>();
InlineKeyboardButton saleBtn = new InlineKeyboardButton();
InlineKeyboardButton buyBtn = new InlineKeyboardButton();
InlineKeyboardButton priceBtn = new InlineKeyboardButton();
saleBtn.setText(Constant.SALE_REPORT_TEXT);
saleBtn.setCallbackData(Constant.SALE_REPORT);
buyBtn.setText(Constant.BUY_REPORT_TEXT);
buyBtn.setCallbackData(Constant.BUY_REPORT);
priceBtn.setText(Constant.PRICE_TEXT);
priceBtn.setCallbackData(Constant.PRICE_REPORT);
reportSaleBtn.add(saleBtn);
reportBuyBtn.add(buyBtn);
reportPriceBtn.add(priceBtn);
listInlineButton.add(reportSaleBtn);
listInlineButton.add(reportBuyBtn);
listInlineButton.add(reportPriceBtn);
inlineKeyboardMarkup.setKeyboard(listInlineButton);
sendMessage.setReplyMarkup(inlineKeyboardMarkup);
try {
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
else if (update.hasCallbackQuery()) {
CallbackQuery callbackQuery = update.getCallbackQuery();
String data = callbackQuery.getData();
String chat_id = callbackQuery.getMessage().getChat().getId().toString();
SendChatAction sendChatAction = new SendChatAction();
if (data.equals(Constant.SALE_REPORT)) {
sendChatAction.setChatId(chat_id);
SendMessage sendMessage = new SendMessage();
sendMessage.setText("Generating report, please wait!");
sendMessage.setChatId(chat_id);
try {
sendChatAction.setAction(ActionType.TYPING);
execute(sendChatAction);
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
Why it got an error. Click we click on /start Bot will display all inlinekeyboard.
In the button you only setText() and setCallbackData(). So update.GetMessage() is null.
In while update.getMessage().getText() is null cannot print out. So it is error and it skip the else if (update.hasCallbackQuery()) {...}
I think you can check again your code below:
#Override
public void onUpdateReceived(Update update) {
//check carefully before if may there's exception error before if
}
I hope what I explain may solve your problems too.
I have simple table with several required and nullable columns. My java application writes data into it via JsonStreamWriter. Most of time everything is ok, but sometimes it fails with error
java.util.concurrent.ExecutionException:
com.google.api.gax.rpc.PermissionDeniedException:
io.grpc.StatusRuntimeException: PERMISSION_DENIED: Permission
'TABLES_UPDATE_DATA' denied on resource
'projects/project-name/datasets/dataset-name/tables/table-name' (or it
may not exist).
Data the similar, I am just append it, without update and I have no idea what goes wrong.
private Queue<Map<String, Object>> queue = new ConcurrentLinkedQueue<>();
private JsonStreamWriter streamWriter;
#Autowired
private BigQueryManager manager;
#PostConstruct
private void initialize() {
WriteStream stream = WriteStream.newBuilder().setType(WriteStream.Type.COMMITTED).build();
TableName parentTable = TableName.of(project, dataset, table);
CreateWriteStreamRequest writeStreamRequest = CreateWriteStreamRequest.newBuilder().setParent(parentTable.toString()).setWriteStream(stream).build();
WriteStream writeStream = manager.getClient().createWriteStream(writeStreamRequest);
try {
streamWriter = JsonStreamWriter.newBuilder(writeStream.getName(), writeStream.getTableSchema(), manager.getClient()).build();
} catch (Exception ex) {
log.error("Unable to initialize stream writer.", ex);
}
}
#Override
public void flush() {
try {
List<Pair<JSONArray, Future>> tasks = new ArrayList<>();
while (!queue.isEmpty()) {
JSONArray batch = new JSONArray();
JSONObject record = new JSONObject();
queue.poll().forEach(record::put);
batch.put(record);
tasks.add(new Pair<>(batch, streamWriter.append(batch)));
}
List<AppendRowsResponse> responses = new ArrayList<>();
tasks.forEach(task -> {
try {
responses.add((AppendRowsResponse) task.getValue().get());
} catch (Exception ex) {
log.debug("Exception while task {} running: {}", task.getKey(), ex.getMessage(), ex);
}
});
responses.forEach(response -> {
if (!"".equals(response.getError().getMessage())) {
log.error(response.getError().getMessage());
}
});
} finally {
streamWriter.close();
}
}
#Override
public void addRow(Map<String, Object> row) {
queue.add(row);
}
This issue was fixed in v1.20.0. If you’re using a lower version, consider updating the library. I you’re using a higher version you could try constructing the JsonStreamWriter builder with BigQuery client being initialized by StreamWriter by default:
streamWriter = JsonStreamWriter.newBuilder(writeStream.getName(), writeStream.getTableSchema()).build();
Hello. I'm trying to solve this problem for a while now. For some
reason I keep getting null pointer exception when I try to save a
object in my repository. Below you can see what happens and my
functions.
java.lang.NullPointerException at com.br.einstein.api.service.ApiTelegram.sendMsg(ApiTelegram.java:104)
at
com.br.einstein.api.service.ApiTelegram.onUpdateReceived(ApiTelegram.java:81)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541) at
org.telegram.telegrambots.meta.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
at
org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:317)
public void onUpdateReceived(Update update) {
ApiEinstein api = new ApiEinstein();
try {
JsonObject objSession = api.getSessionDetails();
String message = update.getMessage().getText();
api.sendChatRequest(objSession);
List < String > list = new ApiEinstein().ReadChatDetails(objSession);
sendMsg(update.getMessage().getChatId().toString(), list.toString());
new ApiEinstein().SendChatMessage(objSession, message);
api.syncChatSession(objSession);
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized void sendMsg(String chatId, String s) {
SendMessage sendMessage = new SendMessage();
// sendMessage.enableMarkdown(true);
sendMessage.setChatId(chatId);
sendMessage.setText(s);
long id = Long.valueOf(chatId);
Telegram telegram = new Telegram();
telegram.setChatId(id);
repository.save(telegram);
try {
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
} ```
I am using JAVA Telegram Bot API with Spring framework , I had a method in my HomeController and i had a class that handle all of the incoming messages from users. I got these errors in my spring log,then i got duplicated response from telegram bot API .whats is the problem ?
#PostConstruct
public void initBots() {
ApiContextInitializer.init();
TelegramBotsApi botsApi = new TelegramBotsApi();
BotService botService = new BotService();
try {
botsApi.registerBot(botService);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
[abrsystem1_bot Telegram Connection] org.telegram.telegrambots.logging.BotLogger.severe
BOTSESSION
org.telegram.telegrambots.exceptions.TelegramApiRequestException:
Error getting updates: [409] Conflict: terminated by other long poll
or webhook at
org.telegram.telegrambots.api.methods.updates.GetUpdates.deserializeResponse(GetUpdates.java:119)
at
org.telegram.telegrambots.updatesreceivers.DefaultBotSession$ReaderThread.getUpdatesFromServer(DefaultBotSession.java:255)
at
org.telegram.telegrambots.updatesreceivers.DefaultBotSession$ReaderThread.run(DefaultBotSession.java:186)
#Override
public void onUpdateReceived(Update update) {
try {
if (update.hasMessage() && update.getMessage().hasText()) {
String message_text = update.getMessage().getText();
String wellcome_text = "برای ثبت نام در سایت شماره تلفن همراه خود را به اشتراک بگذارید";
long chat_id = update.getMessage().getChatId();
if (message_text.equals("/start")) {
try {
SendMessage message = new SendMessage()
.setChatId(chat_id)
.setText(wellcome_text);
ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup();
List<KeyboardRow> keyboard = new ArrayList<KeyboardRow>();
KeyboardRow row = new KeyboardRow();
row.add((new KeyboardButton().setText("اشتراک شماره موبایل").setRequestContact(true)));
keyboard.add(row);
keyboardMarkup.setKeyboard(keyboard);
message.setReplyMarkup(keyboardMarkup);
try {
execute(message);
} catch (TelegramApiException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (message_text.equals("تایید مشخصات کاربری")) {
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(chat_id).setText("اطلاعات مورد تایید قرار گرفت");
try {
execute(sendMessage);
removeMarker(chat_id);
showContactInfo(chat_id, update);
} catch (Exception ex) {
ex.printStackTrace();
}
} else if (message_text.equals("تغییر مشخصات")) {
} else {
showUnknownCommand(chat_id);
}
} else if (update.getMessage().getContact() != null && update.getMessage().getChat() != null) {
long chat_id = update.getMessage().getChatId();
showContactInfo(chat_id, update);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I finally solved my problem after a day!when i was debugging my project with intellij idea on my computer , i created many instances for debug so i got multiple response from same chat id in telegram bot.so boring problem....