Pircbotx channel setMode() not working in main() method - java

I'm trying to set mode to an IRC channel but PircBotX doesn't seems to execute the command when called in the main method. The command executes when I send the message (!setRModePlus) that I have set up in the code. Where am I wrong with my code?
import org.pircbotx.Channel;
import org.pircbotx.Configuration;
import org.pircbotx.PircBotX;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.types.GenericMessageEvent;
public class MyListener extends ListenerAdapter {
static Channel channel = null;
static PircBotX bot = null;
#Override
public void onGenericMessage(GenericMessageEvent event) {
if (event.getMessage().startsWith("!setRModePlus")) {
channel = bot.getUserChannelDao().getChannel("#mychannel");
channel.send().setMode("+R");
}
if (event.getMessage().startsWith("!setRModeMinus")) {
channel = bot.getUserChannelDao().getChannel("#mychannel");
channel.send().setMode("-R");
}
}
public static void main(String[] args) throws Exception {
//Configure the bot
Configuration configuration = new Configuration.Builder()
.setName("myname")
.addServer("myserver")
.setNickservPassword("mypassword")
.addAutoJoinChannel("#mychannel")
.addListener(new MyListener())
.buildConfiguration();
//Create bot with the configuration
bot = new PircBotX(configuration);
bot.startBot();
channel = bot.getUserChannelDao().getChannel("#mychannel");
channel.send().setMode("+R");
}
Thank you for any help you can offer.
Sorry for my English.

Problem solved now. I added onConnect method and send the command like this
public void onConnect(ConnectEvent event) {
event.getBot().send().mode("#mychannel", "+R");
event.getBot().send().mode("#mychannel", "-R");
}

Related

How to get IP address of a web service client?

I created a web service using Eclipse (luna), Tomcat8 and Axis2.To do, I wrote in Java a class 'AddOperator' defining the service as folow:
public class AddOperator {
public int add(int x,int y) {
return x+y;
}
}
I created also a client who consomms this service using the class'AddClientOpp' as folow:
public class AddClientOpp {
public static void main(String[] args) throws RemoteException {
AddOperatorStub stub = new AddOperatorStub();
Add add = new Add();
add.setX(25);
add.setY(30);
System.out.println(stub.add(add).get_return());
}
}
Now, I need to obtain the client's IP adress consomming my web service. I searched and found a few methods and portions of codes that would allow to do this, such as:
import javax.servlet.http.HttpServletRequest;
//...
private static String getClientIp(HttpServletRequest request) {
String remoteAddr = "";
if (request != null) {
remoteAddr = request.getHeader("X-FORWARDED-FOR");
if (remoteAddr == null || "".equals(remoteAddr)) {
remoteAddr = request.getRemoteAddr();
}
}
return remoteAddr;
}
or:
import java.net.*;
import java.io.*;
import java.applet.*;
public class GetClientIP extends Applet {
public void init() {
try {
InetAddress Ip =InetAddress.getLocalHost();
System.out.println("IP:"+Ip.getHostAddress());
} catch(Exception e) {
e.printStackTrace();
}
}
}
But I do not know where to integrate these code portions or methods into my web service creation process described above!!
if someone has an idea about thi please tell me what i have to do. it's verry important for my project!!
thanks.
You can use the following code to retrieve the client address:
MessageContext.getCurrentMessageContext().getProperty(MessageContext.REMOTE_ADDR)

Text to Speech Converter not working

I am trying to do text to speech converter using java code.And i am using freetts.jar to do this.I need to use this in my web application.
import com.sun.speech.freetts.*;
public class convert {
private static final String VOICENAME="kevin";
public static void call(){
Voice voice;
VoiceManager vm=VoiceManager.getInstance();
System.out.println("come");
voice=vm.getVoice(VOICENAME);
voice.allocate();
try{
voice.speak("wellcome to my world");
System.out.println("coming here good");
}
catch(Exception e){
System.out.println(e);
}
}
public static void main(String agrs[]){
call();
}
}
In the above code was not working voice.speak() method was not working .I don't know why.can any one help me to fix this?
And also i need to know how to make the text to voice conversion with own voice .
Thank you
There is no problem with the code. you must have added only freetts.jar to your buildpath. It will give nullpointer exception.
Add all the jars from the lib folder of freetts-1.2.2-bin to your buildpath.
The same code worked for me.
try and tell me.
And for your implementing your own voice: check out these articles
http://www.codeproject.com/Articles/182881/Text-to-Speech?msg=5074134#xx5074134xx
http://www.acapela-group.com/voices/voice-replacement/faq-my-own-voice/
I know i am posting it little late, but this may help someone. I tried the similar, and it worked for me. Please find the code below.
package com.mani.texttospeech;
import java.beans.PropertyVetoException;
import java.util.Locale;
import javax.speech.AudioException;
import javax.speech.Central;
import javax.speech.EngineException;
import javax.speech.EngineStateError;
import javax.speech.synthesis.Synthesizer;
import javax.speech.synthesis.SynthesizerModeDesc;
import javax.speech.synthesis.Voice;
/**
*
* #author Manindar
*/
public class SpeechUtils {
SynthesizerModeDesc desc;
Synthesizer synthesizer;
Voice voice;
public void init(String voiceName) throws EngineException, AudioException, EngineStateError, PropertyVetoException {
if (desc == null) {
System.setProperty("freetts.voices", "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory");
desc = new SynthesizerModeDesc(Locale.US);
Central.registerEngineCentral("com.sun.speech.freetts.jsapi.FreeTTSEngineCentral");
synthesizer = Central.createSynthesizer(desc);
synthesizer.allocate();
synthesizer.resume();
SynthesizerModeDesc smd = (SynthesizerModeDesc) synthesizer.getEngineModeDesc();
Voice[] voices = smd.getVoices();
for (Voice voice1 : voices) {
if (voice1.getName().equals(voiceName)) {
voice = voice1;
break;
}
}
synthesizer.getSynthesizerProperties().setVoice(voice);
}
}
public void terminate() throws EngineException, EngineStateError {
synthesizer.deallocate();
}
public void doSpeak(String speakText) throws EngineException, AudioException, IllegalArgumentException, InterruptedException {
synthesizer.speakPlainText(speakText, null);
synthesizer.waitEngineState(Synthesizer.QUEUE_EMPTY);
}
public static void main(String[] args) throws Exception {
SpeechUtils su = new SpeechUtils();
su.init("kevin16");
// su.init("kevin");
// su.init("mbrola_us1");
// su.init("mbrola_us2");
// su.init("mbrola_us3");
// high quality
su.doSpeak("Hi this is Manindar. Welcome to audio world.");
su.terminate();
}
}
And add the below dependencies to your pom.xml file.
<dependencies>
<dependency>
<groupId>net.sf.sociaal</groupId>
<artifactId>freetts</artifactId>
<version>1.2.2</version>
</dependency>
</dependencies>
Hope this will be helpful.

Kryonet RMI, cannot wait for response on connection's update thread

I would like to make a game using LibGDX and Kryonet library, using RMI. So I created clean project. What I want to do for now is, setup server to listen on port 10048 and on new connection to print client's name which will I get by calling a method on client's class...
Here is the code:
ICardsTableImpl.java
package clzola.cardstable.client;
public interface ICardsTableGameImpl {
public String getName();
}
CardsTableServer.java
package clzola.cardstable.server;
import clzola.cardstable.client.ICardsTableGameImpl;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Server;
import com.esotericsoftware.kryonet.rmi.ObjectSpace;
import com.esotericsoftware.minlog.Log;
import java.io.IOException;
import java.util.HashMap;
public class CardsTableServer extends Server {
private HashMap<Integer, Connection> connections;
public CardsTableServer() throws IOException {
connections = new HashMap<Integer, Connection>();
addListener(new NetworkListener(this));
Kryo kryo = getKryo();
ObjectSpace.registerClasses(kryo);
kryo.register(ICardsTableGameImpl.class);
bind(10048);
}
#Override
protected Connection newConnection() {
Player player = new Player();
addConnection(player);
return player;
}
public void addConnection(Connection connection) {
this.connections.put(connection.getID(), connection);
}
public Connection getConnection(int connectionId) {
return this.connections.get(connectionId);
}
public Connection removeConnection(int connectionId) {
return this.connections.remove(connectionId);
}
public static void main(String[] args) throws IOException {
Log.set(Log.LEVEL_DEBUG);
CardsTableServer server = new CardsTableServer();
server.start();
}
}
NetworkListener.java
package clzola.cardstable.server;
import clzola.cardstable.client.ICardsTableGameImpl;
import com.badlogic.gdx.Gdx;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import com.esotericsoftware.kryonet.rmi.ObjectSpace;
public class NetworkListener extends Listener {
private CardsTableServer server;
public NetworkListener(CardsTableServer server) {
this.server = server;
}
#Override
public void connected(Connection connection) {
Player player = ((Player) connection);
ICardsTableGameImpl game = ObjectSpace.getRemoteObject(player, 0, ICardsTableGameImpl.class);
player.name = game.getName(); // This is where I get excpetion...
Gdx.app.log("Server", "Player name: " + player.name);
}
#Override
public void disconnected(Connection connection) {
server.removeConnection(connection.getID());
}
}
Player.java
package clzola.cardstable.server;
import com.esotericsoftware.kryonet.Connection;
public class Player extends Connection {
public String name;
}
CardsTableGame.java
package clzola.cardstable.client;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryonet.Client;
import com.esotericsoftware.kryonet.rmi.ObjectSpace;
public class CardsTableGame extends ApplicationAdapter implements ICardsTableGameImpl {
SpriteBatch batch;
Stage stage;
Client client;
String name = "Lazar";
ObjectSpace objectSpace;
#Override
public void create () {
batch = new SpriteBatch();
stage = new Stage(new ScreenViewport(), batch);
try {
client = new Client();
client.start();
Kryo kryo = client.getKryo();
ObjectSpace.registerClasses(kryo);
kryo.register(ICardsTableGameImpl.class);
ObjectSpace objectSpace = new ObjectSpace();
objectSpace.register(0, this);
objectSpace.addConnection(client);
client.connect(5000, "127.0.0.1", 10048);
} catch (Exception e) {
Gdx.app.log("CardsTableGame", e.getMessage(), e);
}
}
#Override
public void render () {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
#Override
public String getName() {
return this.name;
}
}
After running it, I get exception on the server side:
Exception in thread "Server" java.lang.IllegalStateException: Cannot wait for an RMI response on the connection's update thread.
at com.esotericsoftware.kryonet.rmi.ObjectSpace$RemoteInvocationHandler.waitForResponse(ObjectSpace.java:420)
at com.esotericsoftware.kryonet.rmi.ObjectSpace$RemoteInvocationHandler.invoke(ObjectSpace.java:408)
at com.sun.proxy.$Proxy0.getName(Unknown Source)
at clzola.cardstable.server.NetworkListener.connected(NetworkListener.java:24)
at com.esotericsoftware.kryonet.Server$1.connected(Server.java:48)
at com.esotericsoftware.kryonet.Connection.notifyConnected(Connection.java:214)
at com.esotericsoftware.kryonet.Server.acceptOperation(Server.java:417)
at com.esotericsoftware.kryonet.Server.update(Server.java:249)
at com.esotericsoftware.kryonet.Server.run(Server.java:372)
at java.lang.Thread.run(Thread.java:745)
And I have no idea why... What am I doing wrong??
(This is the first time ever I am trying to use RMI)
The Listener is executed by the Kryonet-update-thread. This thread is checking the socket regularly to receive the messages. Calling game.getName() makes the caller wait until the answer was delivered over the network. If you do that on the update thread you'd probably put your server in deadlock because kryonet cannot receive the answer it is waiting on, since you block the update thread. This is why it throws the exception.
In an rmi example from the kryonet git they solve this problem by using a Listener working on its own thread.
// The ThreadedListener means the network thread won't be blocked when waiting for RMI responses.
client.addListener(new ThreadedListener(new Listener() {
public void connected (final Connection connection) {
TestObject test = ObjectSpace.getRemoteObject(connection, 42, TestObject.class);
// Normal remote method call.
assertEquals(43.21f, test.other());
// Make a remote method call that returns another remote proxy object.
OtherObject otherObject = test.getOtherObject();
// Normal remote method call on the second object.
assertEquals(12.34f, otherObject.value());
// When a remote proxy object is sent, the other side recieves its actual remote object.
connection.sendTCP(otherObject);
}
}));

How to check programmatically if Zookeeper is running?

I am using CuratorFramework (I'm still a newbie) in order to connect to a Zookeeper instance. I would like to import a configuration but before that I would like to test that my program is able to connect to Zookeeper. So far I have something like that:
public Boolean zookeeperRunning() {
CuratorFramework curatorFramework =
CuratorFrameworkFactory.newClient(zookeeperConn, new RetryOneTime(1));
curatorFramework.start();
CuratorZookeeperClient zkClient = curatorFramework.getZookeeperClient();
return zkClient.isConnected();
}
I've already started ZooKeeper on my local machine and I checked the connection with zkCli and the client is able to connect to it. The zookeeperCon variable is set to "127.0.0.1:2181" (I tried with localhost:2181 as well). The problem is that the above method always returns false despite the fact that zkServer is up n running. Most probably, the syntax is not correct but I could not find a solution online. Could you please help me with why the above code cannot find the zkServer which is up and running?
You can use a builder to create a configured client and setup a listener to monitor your zk instance's state:
// start client
client = CuratorFrameworkFactory.builder()
.connectString("localhost:2181")
.retryPolicy(new ExponentialBackoffRetry(1000, 3))
.namespace("heavenize")
.build();
client.getConnectionStateListenable().addListener(new ConnectionStateListener() {
#Override
public void stateChanged(CuratorFramework client, ConnectionState newState)
{
log.info("State changed to: "+newState);
}
});
}
You should first connect to zookeeper after you get the zkClient, if success, then check the isConnected status. Demo code below(Refer: here):
private static CuratorFramework buildConnection(String url) {
CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(url, new ExponentialBackoffRetry(100, 6));
// start connection
curatorFramework.start();
// wait 3 second to establish connect
try {
curatorFramework.blockUntilConnected(3, TimeUnit.SECONDS);
if (curatorFramework.getZookeeperClient().isConnected()) {
return curatorFramework.usingNamespace("");
}
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
// fail situation
curatorFramework.close();
throw new RuntimeException("failed to connect to zookeeper service : " + url);
}
you should connect to zookeeper server then check it. for example:
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.test.TestingServer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertTrue;
public class ZkClientTest {
TestingServer zkServer;
#Before
public void startZookeeper() throws Exception {
zkServer = new TestingServer(2181);
zkServer.start();
}
#After
public void stopZookeeper() throws IOException {
zkServer.stop();
}
#Test
public void should_connect_to_zookeeper_server_when_config_use_default_localhost_2181()
throws InterruptedException {
CuratorFramework client = ZkClient.getInstance().getClient();
try {
client.blockUntilConnected(3, TimeUnit.SECONDS);
assertTrue(ZkClient.getInstance().getClient().getZookeeperClient().isConnected());
} finally {
ZkClient.getInstance().close();
}
}
}

I'm missing something like: 'isConnected' on ClientDolphin class (open-dolphin)

If I run following java class, no exception or error message occures, but I'm sure that connection cannot be established (GrailsApplication1 is not running, and 'url' is not pointing to any bean):
public class ConnectNow {
private void connect() {
ClientDolphin dClient = new ClientDolphin();
dClient.setClientModelStore(new ClientModelStore(dClient));
String url = "http://localhost:8080/GrailsApplication1/";
ClientConnector connector = new HttpClientConnector(dClient, url);
connector.setCodec(new JsonCodec());
dClient.setClientConnector(connector);
dClient.send("Hi from client");
}
public static void main(String[] args) {
ConnectNow cn = new ConnectNow();
cn.connect();
System.out.println("End");
}
}
Soo, how can I recognize if connection is established? I'm newbie in client/server dev, so maybe I'm missing something obvious.
Thanks for any advice, or doc reference!
Now, I figured it out... Key is that I have to run the code as an Application, in this case javafx app. Then, if you try to transmit something (dClient send "Hi... - in this case), app tries to send a message, and you get ConnectException: Connection refused, if there is nothing running on url.
This seems to me as shortest version of open-dolphin server accessibity test:
import javafx.application.Application;
import javafx.stage.Stage;
import org.opendolphin.core.client.ClientDolphin;
import org.opendolphin.core.client.ClientModelStore;
import org.opendolphin.core.client.comm.ClientConnector;
import org.opendolphin.core.client.comm.HttpClientConnector;
import org.opendolphin.core.comm.JsonCodec;
/**
*
* #author Václav Hanton
*/
public class ConnectNow extends Application {
private void connect() {
ClientDolphin dClient = new ClientDolphin();
ClientModelStore mStore = new ClientModelStore(dClient);
dClient.setClientModelStore(mStore);
String url = "http://localhost:8080/GrailsApplication1/";
ClientConnector connector = new HttpClientConnector(dClient, url);
connector.setCodec(new JsonCodec());
dClient.setClientConnector(connector);
dClient.send("Hi from client");
}
public static void main(String[] args) {
ConnectNow cn = new ConnectNow();
cn.connect();
Application.launch();
}
#Override
public void start(Stage stage) throws Exception {
System.out.println("Started");
}
}

Categories