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

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");
}
}

Related

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

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");
}

Connect Java rest API to JIra

I want to connect Java with JIRA trial account. I tested this code:
public class JiraImpl
{
private static URI JIRA_URL = URI.create("https://sonoratest.atlassian.net");
private static final String JIRA_ADMIN_USERNAME = "sonoratestw#gmail.com";
private static final String JIRA_ADMIN_PASSWORD = "sonpass";
public static void main(String[] args) throws IOException, InterruptedException, ExecutionException
{
try
{
AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
JiraRestClient restClient = factory.createWithBasicHttpAuthentication(JIRA_URL, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD);
Iterable<BasicProject> allProjects = restClient.getProjectClient().getAllProjects().claim();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
But when I run it nothing happens. Wahat is the proper way to get data from JIRA using REST API?
Update. I also tried this:
private static URI JIRA_URL = URI.create("https://sonoratest.atlassian.net/rest/auth/1/session");
I get
java.util.concurrent.ExecutionException: RestClientException{statusCode=Optional.of(404), errorCollections=[ErrorCollection{status=404, errors={}, errorMessages=[]}]}
at com.google.common.util.concurrent.AbstractFuture$Sync.getValue(AbstractFuture.java:299)
at com.google.common.util.concurrent.AbstractFuture$Sync.get(AbstractFuture.java:286)
at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:116)
at com.google.common.util.concurrent.ForwardingFuture.get(ForwardingFuture.java:63)
at com.atlassian.jira.rest.client.internal.async.DelegatingPromise.get(DelegatingPromise.java:102)
at com.jira.impl.JiraImpl.main(JiraImpl.java:23)
Caused by: RestClientException{statusCode=Optional.of(404), errorCollections=[ErrorCollection{status=404, errors={}, errorMessages=[]}]}
Try getting an issue first, since that is so basic.
import java.net.URI;
import java.util.Optional;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import com.atlassian.util.concurrent.Promise;
public class JRC
{
public Issue getIssue(String issueKey) throws Exception
{
final URI jiraServerUri = new URI("https://jira-domain");
final JiraRestClient restClient = new AsynchronousJiraRestClientFactory().createWithBasicHttpAuthentication(jiraServerUri, "user#domain.com", "password");
Promise issuePromise = restClient.getIssueClient().getIssue(issueKey);
return Optional.ofNullable((Issue) issuePromise.claim()).orElseThrow(() -> new Exception("No such issue"));
}
}
You can also take a look at this code to get a fully working sample:
https://github.com/somaiah/jrjc

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();
}
}
}

Grizzly Http Server - accepting only one connection at a time

I have a Grizzly Http Server with Async processing added. It is queuing my requests and processing only one request at a time, despite adding async support to it.
Path HttpHandler was bound to is: "/"
Port number: 7777
Behavior observed when I hit http://localhost:7777 from two browsers simultaneously is:
Second call waits till first one is completed. I want my second http call also to work simultaneously in tandom with first http call.
EDIT Github link of my project
Here are the classes
GrizzlyMain.java
package com.grizzly;
import java.io.IOException;
import java.net.URI;
import javax.ws.rs.core.UriBuilder;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.http.server.NetworkListener;
import org.glassfish.grizzly.nio.transport.TCPNIOTransport;
import org.glassfish.grizzly.strategies.WorkerThreadIOStrategy;
import org.glassfish.grizzly.threadpool.ThreadPoolConfig;
import com.grizzly.http.IHttpHandler;
import com.grizzly.http.IHttpServerFactory;
public class GrizzlyMain {
private static HttpServer httpServer;
private static void startHttpServer(int port) throws IOException {
URI uri = getBaseURI(port);
httpServer = IHttpServerFactory.createHttpServer(uri,
new IHttpHandler(null));
TCPNIOTransport transport = getListener(httpServer).getTransport();
ThreadPoolConfig config = ThreadPoolConfig.defaultConfig()
.setPoolName("worker-thread-").setCorePoolSize(6).setMaxPoolSize(6)
.setQueueLimit(-1)/* same as default */;
transport.configureBlocking(false);
transport.setSelectorRunnersCount(3);
transport.setWorkerThreadPoolConfig(config);
transport.setIOStrategy(WorkerThreadIOStrategy.getInstance());
transport.setTcpNoDelay(true);
System.out.println("Blocking Transport(T/F): " + transport.isBlocking());
System.out.println("Num SelectorRunners: "
+ transport.getSelectorRunnersCount());
System.out.println("Num WorkerThreads: "
+ transport.getWorkerThreadPoolConfig().getCorePoolSize());
httpServer.start();
System.out.println("Server Started #" + uri.toString());
}
public static void main(String[] args) throws InterruptedException,
IOException, InstantiationException, IllegalAccessException,
ClassNotFoundException {
startHttpServer(7777);
System.out.println("Press any key to stop the server...");
System.in.read();
}
private static NetworkListener getListener(HttpServer httpServer) {
return httpServer.getListeners().iterator().next();
}
private static URI getBaseURI(int port) {
return UriBuilder.fromUri("https://0.0.0.0/").port(port).build();
}
}
HttpHandler (with async support built in)
package com.grizzly.http;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import javax.ws.rs.core.Application;
import org.glassfish.grizzly.http.server.HttpHandler;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;
import org.glassfish.grizzly.http.util.HttpStatus;
import org.glassfish.grizzly.threadpool.GrizzlyExecutorService;
import org.glassfish.grizzly.threadpool.ThreadPoolConfig;
import org.glassfish.jersey.server.ApplicationHandler;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.spi.Container;
import com.grizzly.Utils;
/**
* Jersey {#code Container} implementation based on Grizzly
* {#link org.glassfish.grizzly.http.server.HttpHandler}.
*
* #author Jakub Podlesak (jakub.podlesak at oracle.com)
* #author Libor Kramolis (libor.kramolis at oracle.com)
* #author Marek Potociar (marek.potociar at oracle.com)
*/
public final class IHttpHandler extends HttpHandler implements Container {
private static int reqNum = 0;
final ExecutorService executorService = GrizzlyExecutorService
.createInstance(ThreadPoolConfig.defaultConfig().copy()
.setCorePoolSize(4).setMaxPoolSize(4));
private volatile ApplicationHandler appHandler;
/**
* Create a new Grizzly HTTP container.
*
* #param application
* JAX-RS / Jersey application to be deployed on Grizzly HTTP
* container.
*/
public IHttpHandler(final Application application) {
}
#Override
public void start() {
super.start();
}
#Override
public void service(final Request request, final Response response) {
System.out.println("\nREQ_ID: " + reqNum++);
System.out.println("THREAD_ID: " + Utils.getThreadName());
response.suspend();
// Instruct Grizzly to not flush response, once we exit service(...) method
executorService.execute(new Runnable() {
#Override
public void run() {
try {
System.out.println("Executor Service Current THREAD_ID: "
+ Utils.getThreadName());
Thread.sleep(25 * 1000);
} catch (Exception e) {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500);
} finally {
String content = updateResponse(response);
System.out.println("Response resumed > " + content);
response.resume();
}
}
});
}
#Override
public ApplicationHandler getApplicationHandler() {
return appHandler;
}
#Override
public void destroy() {
super.destroy();
appHandler = null;
}
// Auto-generated stuff
#Override
public ResourceConfig getConfiguration() {
return null;
}
#Override
public void reload() {
}
#Override
public void reload(ResourceConfig configuration) {
}
private String updateResponse(final Response response) {
String data = null;
try {
data = new Date().toLocaleString();
response.getWriter().write(data);
} catch (IOException e) {
data = "Unknown error from our server";
response.setStatus(500, data);
}
return data;
}
}
IHttpServerFactory.java
package com.grizzly.http;
import java.net.URI;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.http.server.NetworkListener;
import org.glassfish.grizzly.http.server.ServerConfiguration;
/**
* #author smc
*/
public class IHttpServerFactory {
private static final int DEFAULT_HTTP_PORT = 80;
public static HttpServer createHttpServer(URI uri, IHttpHandler handler) {
final String host = uri.getHost() == null ? NetworkListener.DEFAULT_NETWORK_HOST
: uri.getHost();
final int port = uri.getPort() == -1 ? DEFAULT_HTTP_PORT : uri.getPort();
final NetworkListener listener = new NetworkListener("IGrizzly", host, port);
listener.setSecure(false);
final HttpServer server = new HttpServer();
server.addListener(listener);
final ServerConfiguration config = server.getServerConfiguration();
if (handler != null) {
config.addHttpHandler(handler, uri.getPath());
}
config.setPassTraceRequest(true);
return server;
}
}
It seems the problem is the browser waiting for the first request to complete, and thus more a client-side than a server-side issue. It disappears if you test with two different browser processes, or even if you open two distinct paths (let's say localhost:7777/foo and localhost:7777/bar) in the same browser process (note: the query string partecipates in making up the path in the HTTP request line).
How I understood it
Connections in HTTP/1.1 are persistent by default, ie browsers recycle the same TCP connection over and over again to speed things up. However, this doesn't mean that all requests to the same domain will be serialized: in fact, a connection pool is allocated on a per-hostname basis (source). Unfortunately, requests with the same path are effectively enqueued (at least on Firefox and Chrome) - I guess it's a device that browsers employ to protect server resources (and thus user experience)
Real-word applications don't suffer from this because different resources are deployed to different URLs.
DISCLAIMER: I wrote this answer based on my observations and some educated guess. I think things may actually be like this, however a tool like Wireshark should be used to follow the TCP stream and definitely assert this is what happens.

Categories