I'm new to Kotlin, and, man, it's awesome!
I'm creating a Discord bot with it using JDA & Maven, it works, but, I created a basic command handler, and now, I get a lot of errors saying "Expecting top level declaration" on a top level declaration. 🤔
Here is my code (btw, I already found that Array<String?> error):
package com.blueslimee.kirani.listeners
import net.dv8tion.jda.core.entities.*
import net.dv8tion.jda.core.hooks.*
import net.dv8tion.jda.core.JDA
import net.dv8tion.jda.core.events.message.MessageReceivedEvent
import com.blueslimee.kirani.utils.KiraniLogging
import com.blueslimee.kirani.KiraniCommand
import com.blueslimee.kirani.utils.Registry
class MessageListener() : ListenerAdapter() {
override fun onMessageReceived (event: MessageReceivedEvent) {
val jda: JDA = event.getJDA()
// todo: cmds guild-only event.isFromType(ChannelType.TEXT)
if (!event.getAuthor().isBot()) {
var msgContent: String? = event.getMessage()
if (msgContent === null) {
return
}
var args: Array<String?> = msgContent!!.split(" ")
var firstArg: String? = args[0]
if (!firstArg!!.startsWith("k-", true)) {
return
}
firstArg = firstArg!!.replace("k-", "", true)
var cmde: KiraniCommand? = Registry.getCommand(firstArg)
if (cmde != null) {
try {
cmde!!.run(jda, event, args)
} catch (e: Exception) {
event.getChannel().sendMessage("Oopsie Woopsie, um erro ocorreu! Meu dono já foi reportado sobre, peço que aguarde.").queue()
e.printStackTrace()
}
}
}
}
}
Thanks!
Use
var args: List<String> = msgContent.split(" ").toList()
instead of
var args: Array<String?> = msgContent!!.split(" ")
Here's a simple .net core 1.1 console app. Call it with a -r parameter and it reads all the messages in the rabbitmq Queue, call it with any other parameters, and each parameter is enqueued as a message.
Here's the problem, I can enqueue the messages fine, but all attempts to read the messages result in no messages being read. Clearly I'm not consuming the queue correctly, and would appreciate some guidance.
Thanks!
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
namespace RabbitMqDemo
{
class Program
{
static void Main(string[] args)
{
var client = new MessagingClient();
if (args.Length == 1 && args[0].ToLower() == "-r")
{
Console.WriteLine("Reading Messages from Queue.");
var messages = client.ReceiveMessages();
Console.WriteLine($"Read {messages.Length} message(s) from queue.");
foreach(var msg in messages)
Console.WriteLine(msg);
}
else
{
foreach (var msg in args)
{
client.SendMessage(msg);
}
Console.WriteLine($"Enqueued {args.Length} Message.");
}
}
}
internal class MessagingClient
{
private readonly ConnectionFactory connectionFactory;
private string ExchangeName => "defaultExchange";
private string RoutingKey => "";
private string QueueName => "Demo";
private string HostName => "localhost";
public MessagingClient()
{
this.connectionFactory = new ConnectionFactory {HostName = this.HostName};
}
public void SendMessage(string message)
{
using (var connection = this.connectionFactory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
this.QueueDeclare(channel, this.QueueName);
var properties = this.SetMessageProperties(channel, message);
string messageJson = JsonConvert.SerializeObject(message);
var body = Encoding.UTF8.GetBytes(messageJson);
channel.BasicPublish(exchange: this.ExchangeName, routingKey: this.RoutingKey, basicProperties: properties, body: body);
}
}
}
public string[] ReceiveMessages()
{
var messages = new List<string>();
using (var connection = this.connectionFactory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
this.QueueDeclare(channel, this.QueueName);
channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
string bodystring = Encoding.UTF8.GetString(ea.Body);
messages.Add(bodystring);
// ReSharper disable once AccessToDisposedClosure
channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
};
channel.BasicConsume(queue: this.QueueName, autoAck: false, consumer: consumer);
}
}
return messages.ToArray();
}
private void QueueDeclare(IModel channel, string queueName)
{
channel.ExchangeDeclare(ExchangeName, type: ExchangeType.Direct,
durable: true,
autoDelete: false,
arguments: null);
var queueDeclared = channel.QueueDeclare(queue: queueName,
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
channel.QueueBind(queueName, ExchangeName, RoutingKey);
}
private IBasicProperties SetMessageProperties(IModel channel, object message)
{
var properties = channel.CreateBasicProperties();
properties.ContentType = "application/json";
properties.Persistent = true;
return properties;
}
}
}
First, use the management UI to ensure that your exchange and queue are set up correctly and that messages have been published to it.
Second, ReceiveMessages() and thus your reader probably returns immediately with an empty array before the event has a chance to fire. You have no code to wait while the consumer receives messages from RabbitMQ. Notice in the tutorial how Console.ReadLine() is used. In your example, you can use a synchronization object (ManualResetEvent) to prevent ReceiveMessages() from returning until a certain message count is read.
i work on a project with activemq java and i use ssl or udp connection .To receive messqge i use a QeueueReceiver and MessageListener Classes .the problem is that the ssl connection perfectly but when i choose a udp connection and i send 7 messages and i put the listener working i receive 5 messages after i receive only 2 messages . i DONT know what exactly the problem sombedoy can help please there is a code
code
ry {
switch (protocol) {
case "UDP":
connectionFactoryUDP = new ActiveMQConnectionFactory(brokerUrlUDP);
connection = connectionFactoryUDP.createQueueConnection(username, password);
break;
case "TLS":
connectionFactoryTLS = new ActiveMQSslConnectionFactory();
// create connection
connectionFactoryTLS.setBrokerURL(brokerUrlTLS);
connectionFactoryTLS.setTrustStore(trustStore);
connectionFactoryTLS.setTrustStorePassword(trustStorePassword);
connectionFactoryTLS.setKeyStore(keyStore);
connectionFactoryTLS.setKeyStorePassword(keyStorePassword);
connection = connectionFactoryTLS.createQueueConnection(username,password);
break;}
//ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(this.username, this.password, "tcp://localhost:61616");
// create connection
// start
connection.start();
// create session
// create queue (it will create if queue doesn't exist)
// create listener
System.out.println("____________________________________");
MessageListener messageListener = new MessageListener() {
#Override
public void onMessage(Message message) {
System.out.println("____________________________________");
// only text type message
if (message instanceof TextMessage) {
TextMessage txt = (TextMessage) message;
try {
System.out.println("Message received =---_________--" + txt.getText());
} catch (JMSException e) {
System.out.println("error retrieving message");
System.exit(1);
}
}
}
};
session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue(queueName);
QueueReceiver consumer = session.createReceiver(queue);
consumer.setMessageListener(messageListener);
System.in.read();
consumer.close();
session.close();
connection.close();
System.out.println("-----------closed----------");
log console
2015-10-16 18:30:42 DEBUG UdpTransport:382 - Binding to address: 0.0.0.0/0.0.0.0:0
2015-10-16 18:30:42 DEBUG Connection:1:55 - SENDING: ConnectionInfo {commandId = 1, responseRequired = true, connectionId = ID:aymenmhidhi-PC-57832-1445013042216-1:1, clientId = ID:aymenmhidhi-PC-57832-1445013042216-0:1, clientIp = null, userName = aymenmhidhi, password = *****, brokerPath = null, brokerMasterConnector = false, manageable = true, clientMaster = true, faultTolerant = false, failoverReconnect = false}
2015-10-16 18:30:42 DEBUG UdpTransport:124 - Sending oneway from: udp://localhost:61625?trace=true#49257 to target: localhost/127.0.0.1:61625 command: ConnectionInfo {commandId = 1, responseRequired = true, connectionId = ID:aymenmhidhi-PC-57832-1445013042216-1:1, clientId = ID:aymenmhidhi-PC-57832-1445013042216-0:1, clientIp = null, userName = aymenmhidhi, password = *****, brokerPath = null, brokerMasterConnector = false, manageable = true, clientMaster = true, faultTolerant = false, failoverReconnect = false}
2015-10-16 18:30:42 DEBUG DefaultReplayBuffer:47 - Adding command ID: 1 to replay buffer: org.apache.activemq.transport.reliable.DefaultReplayBuffer#7e3e2cff object: java.nio.DirectByteBuffer[pos=129 lim=4096 cap=4096]
2015-10-16 18:30:42 DEBUG CommandDatagramChannel:242 - Channel: udp://localhost:61625?trace=true#49257 sending datagram: 1 to: localhost/127.0.0.1:61625
2015-10-16 18:30:42 DEBUG CommandDatagramChannel:110 - Channel: udp://localhost:61625?trace=true#49257 received from: Endpoint[name:/127.0.0.1:49258] about to process: Response {commandId = 1, responseRequired = false, correlationId = 1}
2015-10-16 18:30:42 DEBUG Connection:1:60 - RECEIVED: Response {commandId = 1, responseRequired = false, correlationId = 1}
2015-10-16 18:30:42 DEBUG CommandDatagramChannel:110 - Channel: udp://localhost:61625?trace=true#49257 received from: Endpoint[name:/127.0.0.1:49258] about to process: ConnectionControl {commandId = 2, responseRequired = false, suspend = false, resume = false, close = false, exit = false, faultTolerant = false, connectedBrokers = , reconnectTo = , token = null, rebalanceConnection = false}
2015-10-16 18:30:42 DEBUG Connection:1:60 - RECEIVED: ConnectionControl {commandId = 2, responseRequired = false, suspend = false, resume = false, close = false, exit = false, faultTolerant = false, connectedBrokers = , reconnectTo = , token = null, rebalanceConnection = false}
2015-10-16 18:30:42 DEBUG CommandDatagramChannel:110 - Channel: udp://localhost:61625?trace=true#49257 received from: Endpoint[name:/127.0.0.1:49258] about to process: BrokerInfo {commandId = 3, responseRequired = false, brokerId = ID:aymenmhidhi-PC-57133-1445011516433-0:1, brokerURL = tcp://aymenmhidhi-PC:61616, slaveBroker = false, masterBroker = false, faultTolerantConfiguration = false, networkConnection = false, duplexConnection = false, peerBrokerInfos = null, brokerName = localhost, connectionId = 0, brokerUploadUrl = null, networkProperties = null}
2015-10-16 18:30:42 DEBUG Connection:1:60 - RECEIVED: BrokerInfo {commandId = 3, responseRequired = false, brokerId = ID:aymenmhidhi-PC-57133-1445011516433-0:1, brokerURL = tcp://aymenmhidhi-PC:61616, slaveBroker = false, masterBroker = false, faultTolerantConfiguration = false, networkConnection = false, duplexConnection = false, peerBrokerInfos = null, brokerName = localhost, connectionId = 0, brokerUploadUrl = null, networkProperties = null}
2015-10-16 18:30:42 DEBUG Connection:1:55 - SENDING: ConsumerInfo {commandId = 2, responseRequired = true, consumerId = ID:aymenmhidhi-PC-57832-1445013042216-1:1:-1:1, destination = ActiveMQ.Advisory.TempQueue,ActiveMQ.Advisory.TempTopic, prefetchSize = 1000, maximumPendingMessageLimit = 0, browser = false, dispatchAsync = true, selector = null, clientId = null, subscriptionName = null, noLocal = true, exclusive = false, retroactive = false, priority = 0, brokerPath = null, optimizedAcknowledge = false, noRangeAcks = false, additionalPredicate = null}
2015-10-16 18:30:42 DEBUG UdpTransport:124 - Sending oneway from: udp://localhost:61625?trace=true#49257 to target: /127.0.0.1:49258 command: ConsumerInfo {commandId = 2, responseRequired = true, consumerId = ID:aymenmhidhi-PC-57832-1445013042216-1:1:-1:1, destination = ActiveMQ.Advisory.TempQueue,ActiveMQ.Advisory.TempTopic, prefetchSize = 1000, maximumPendingMessageLimit = 0, browser = false, dispatchAsync = true, selector = null, clientId = null, subscriptionName = null, noLocal = true, exclusive = false, retroactive = false, priority = 0, brokerPath = null, optimizedAcknowledge = false, noRangeAcks = false, additionalPredicate = null}
2015-10-16 18:30:42 DEBUG DefaultReplayBuffer:47 - Adding command ID: 2 to replay buffer: org.apache.activemq.transport.reliable.DefaultReplayBuffer#7e3e2cff object: java.nio.DirectByteBuffer[pos=155 lim=4096 cap=4096]
2015-10-16 18:30:42 DEBUG CommandDatagramChannel:242 - Channel: udp://localhost:61625?trace=true#49257 sending datagram: 2 to: /127.0.0.1:49258
2015-10-16 18:30:42 DEBUG CommandDatagramChannel:110 - Channel: udp://localhost:61625?trace=true#49257 received from: Endpoint[name:/127.0.0.1:49258] about to process: Response {commandId = 4, responseRequired = false, correlationId = 2}
2015-10-16 18:30:42 DEBUG Connection:1:60 - RECEIVED: Response {commandId = 4, responseRequired = false, correlationId = 2}
brokerurl
brokerUrlUDP=udp://localhost:61625?trace=true
Thanks.
package eu.dedalus.x1v1.arr.arrReceiver;
import java.util.concurrent.ThreadPoolExecutor;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQSslConnectionFactory;
import org.apache.activemq.broker.TransportConnector;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
public class ActiveMQQueuListener {
private static final Logger log = Logger
.getLogger(ActiveMQQueuListener.class.getName());
private String brokerUrlTLS;
private String brokerUrlUDP;
private String username;
private String password;
private ArrListener listener;
private String queueName;
private String protocol;
private String keyStore;
private String trustStore;
private String keyStorePassword;
private String trustStorePassword;
private boolean exit = false;
private QueueConnection connection = null;
private QueueSession session = null;
private ActiveMQConnectionFactory connectionFactoryUDP;
private ActiveMQSslConnectionFactory connectionFactoryTLS;
private MessageConsumer consumer;
private ThreadPoolExecutor executor;
private TransportConnector connector;
public void startReceiving() throws Exception {
System.out.println("------Start receiving---------");
try {
switch (protocol) {
case "UDP":
connectionFactoryUDP = new ActiveMQConnectionFactory(
brokerUrlUDP);
connection = connectionFactoryUDP.createQueueConnection(
username, password);
break;
case "TLS":
connectionFactoryTLS = new ActiveMQSslConnectionFactory();
// create connection
connectionFactoryTLS.setBrokerURL(brokerUrlTLS);
connectionFactoryTLS.setTrustStore(trustStore);
connectionFactoryTLS.setTrustStorePassword(trustStorePassword);
connectionFactoryTLS.setKeyStore(keyStore);
connectionFactoryTLS.setKeyStorePassword(keyStorePassword);
connection = connectionFactoryTLS.createQueueConnection(
username, password);
break;
}
// ConnectionFactory connectionFactory = new
// ActiveMQConnectionFactory(this.username, this.password,
// "tcp://localhost:61616");
// create connection
// start
connection.start();
// create session
// create queue (it will create if queue doesn't exist)
// create listener
MessageListener messageListener = new MessageListener() {
#Override
public void onMessage(Message message) {
// only text type message
if (message instanceof TextMessage) {
TextMessage txt = (TextMessage) message;
try {
System.out
.println("Message received =---_________--"
+ txt.getText());
} catch (JMSException e) {
System.out.println("error retrieving message");
System.exit(1);
}
}
}
};
session = connection.createQueueSession(false,
Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue(queueName);
QueueReceiver consumer = session.createReceiver(queue);
consumer.setMessageListener(messageListener);
System.in.read();
consumer.close();
session.close();
connection.close();
System.out.println("-----------closed----------");
} catch (Exception e) {
System.out.println("Exception while sending message to the queue"
+ e);
throw e;
}
}
public void setListener(ArrListener listener) {
this.listener = listener;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public ArrListener getListener() {
return listener;
}
public static Logger getLog() {
return log;
}
public String getQueueName() {
return queueName;
}
public void setQueueName(String queueName) {
this.queueName = queueName;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getKeyStore() {
return keyStore;
}
public void setKeyStore(String keyStore) {
this.keyStore = keyStore;
}
public String getTrustStore() {
return trustStore;
}
public void setTrustStore(String trustStore) {
this.trustStore = trustStore;
}
public String getKeyStorePassword() {
return keyStorePassword;
}
public void setKeyStorePassword(String keyStorePassword) {
this.keyStorePassword = keyStorePassword;
}
public String getTrustStorePassword() {
return trustStorePassword;
}
public void setTrustStorePassword(String trustStorePassword) {
this.trustStorePassword = trustStorePassword;
}
public String getBrokerUrlTLS() {
return brokerUrlTLS;
}
public void setBrokerUrlTLS(String brokerUrlTLS) {
this.brokerUrlTLS = brokerUrlTLS;
}
public String getBrokerUrlUDP() {
return brokerUrlUDP;
}
public void setBrokerUrlUDP(String brokerUrlUDP) {
this.brokerUrlUDP = brokerUrlUDP;
}
public void exitMethod() {
System.exit(1);
try {
consumer.close();
session.close();
connection.close();
System.out.println("-----------closed----------");
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public boolean isExit() {
return exit;
}
public void setExit(boolean exit) {
this.exit = exit;
}
public Connection getConnection() {
return connection;
}
public ActiveMQConnectionFactory getConnectionFactoryUDP() {
return connectionFactoryUDP;
}
public void setConnectionFactoryUDP(
ActiveMQConnectionFactory connectionFactoryUDP) {
this.connectionFactoryUDP = connectionFactoryUDP;
}
public ActiveMQSslConnectionFactory getConnectionFactoryTLS() {
return connectionFactoryTLS;
}
public void setConnectionFactoryTLS(
ActiveMQSslConnectionFactory connectionFactoryTLS) {
this.connectionFactoryTLS = connectionFactoryTLS;
}
}
Deploying ear on Glassfish 3.1.2 and trying to lookup EJB bean from #PostConstruct method in web service:
#PostConstruct
public void init()
{
try
{
InitialContext initialContext = new InitialContext();
browserService = (IBrowserService) initialContext.lookup("java:comp/env/BrowserService");
}
catch (NamingException ex)
{
Logger.getLogger(BrowserWS.class.getName()).log(Level.SEVERE, null, ex);
}
}
and got
[#|2012-04-25T10:15:54.768+0300|SEVERE|glassfish3.1.2|browser.service.BrowserWS|_ThreadID=22;_ThreadName=admin-thread-pool-4848(4
);|javax.naming.NamingException: Lookup failed for 'java:comp/env/BrowserService' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterpri
se.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.ur
l.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NamingException: Invocation exception: Got null ComponentInvocation ]
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:518)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:455)
When i try do the same from web method all works fine.
#WebMethod
public XmlLookupResult lookup(
#WebParam(name = "inLookupId", mode = WebParam.Mode.IN) String id,
#WebParam(name = "inLookupParams", mode = WebParam.Mode.IN) List<String> params,
#WebParam(name = "inFetchLimit", mode = WebParam.Mode.IN) int limit)
{
try
{
InitialContext initialContext = new InitialContext();
browserService = (IBrowserService) initialContext.lookup("java:comp/env/BrowserService");
}
catch (NamingException ex)
{
Logger.getLogger(BrowserWS.class.getName()).log(Level.SEVERE, null, ex);
}
return browserService.lookup(id, params, limit);
}
So, why i can't lookup beans from #PostConstruct method?
From specification whe have JNDI access to java:comp/env from PostConstruct...
Thanks
UPD:
BrowserService declared in web.xml as
<ejb-local-ref>
<ejb-ref-name>BrowserService</ejb-ref-name>
<local>browser.service.IBrowserService</local>
</ejb-local-ref>
am trying to get the user details from ADAM Active Directory.
i used the following java code.
import javax.naming.*;
import javax.naming.directory.*;
import java.util.Hashtable;
public class SimpleQuery {
public static void main(String[] args) {
StringBuffer output = new StringBuffer();
attribute="street";
query="(&(cn=ldap1))";
try {
String url = "ldap://172.16.12.178:389/cn=users,dc=sharepoint,dc=com";
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, url);
DirContext context = new InitialDirContext(env);
String[] attributeFilter = {"cn", "givenName", "SN", "street", "streetAddress", "postalAddress", "postOfficeBox", "l", "st", "postalCode", "c", "telephoneNumber", "homePhone", "mobile", "pager", "mail", "objectCategory", "objectClass", "userAccountControl"};
SearchControls ctrl = new SearchControls();
ctrl.setReturningAttributes(attributeFilter);
ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration enumeration = context.search("", query, ctrl);
while (enumeration.hasMore()) {
SearchResult result = (SearchResult) enumeration.next();
Attributes attribs = result.getAttributes();
NamingEnumeration values = ((BasicAttribute) attribs.get(attribute)).getAll();
while (values.hasMore()) {
if (output.length() > 0) {
output.append("|");
}
output.append(values.next().toString());
}
}
} catch (Exception e) {
System.out.println("Exception : "+e);
e.printStackTrace();
}
System.out.print(output.toString());
}
public SimpleQuery() {}}
and am getting this exception:
javax.naming.NamingException: [LDAP: error code 1 - 000004DC: LdapErr: DSID-0C09
06DC, comment: In order to perform this operation a successful bind must be comp
leted on the connection., data 0, v1db0 ]; remaining name ''
Is there any attribute i need to put?.
Please guide me.
Thanks
You're attempting the operation anonymously and it isn't permitted. You need to set Context.SECURITY_PRINCIPAL/SECURITY_CREDENTIALS in the env before attempting the operation.