I am getting null pointer exception when I call headerVerification method from main function of TestDriver class, though the element is present.
Start Server Class:
package WebTesting;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
public class StartServer {
private String host;
private String nameOfBrowser;
private int port;
private String url;
public StartServer(String host, int port, String nameOfBrowser, String url){
this.host=host;
this.port=port;
this.nameOfBrowser=nameOfBrowser;
this.url=url;
}
public static Selenium browser;
public void startServer(){
browser = new DefaultSelenium(host, port, nameOfBrowser, url);
browser.start();
browser.open("/");
System.out.println("Browser Started !!!");
}
}
Header Verification Class
package WebTesting;
import com.thoughtworks.selenium.Selenium;
public class HeaderVerification {
private String elementPath;
private String linkPath;
private String testLink;
public HeaderVerification(String elementPath, String linkPath, String testLink){
this.elementPath=elementPath;
this.linkPath=linkPath;
this.testLink=testLink;
}
public static Selenium browser;
public void headerVerification() throws InterruptedException{
System.out.println(elementPath);
if(browser.isElementPresent(elementPath)){
Thread.sleep(5000);
System.out.println("Header is Present");
browser.click(linkPath);
Thread.sleep(5000);
if(browser.getLocation().equals(testLink)){
System.out.println("Correct Location!!!");
}
else
System.out.println("Incorrect Location!!!");
browser.close();
System.out.println("Browser Closed!!!");
}
}
}
TestDriver Class
package WebTesting;
public class TestDriver {
/**
* #param args
*/
static StartServer ss = new StartServer("localhost", 4444, "*firefox", "http://docs.seleniumhq.org/");
static HeaderVerification hv = new HeaderVerification ("//div[#id='header']", "//a[#title='Overview of Selenium']", "http://docs.seleniumhq.org/about/");
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
ss.startServer();
hv.headerVerification();
}
}
The brower static variable is null in the HeaderVerification class. You should add
HeaderVerification.browser = browser;
in StarstServer.startServer() method.
Related
I am creating a program in java for websocket for blockchain.
My this example is working well :
`
import java.io.;
import com.neovisionaries.ws.client.;
public class Test
{
private static final String SERVER = "wss://ws.blockchain.info/inv";
public static void main(String[] args) throws Exception
{
WebSocket ws = connect();
ws.sendText("{\"op\":\"unconfirmed_sub\"}");
}
private static WebSocket connect() throws IOException, WebSocketException
{
return new WebSocketFactory().setConnectionTimeout(500000000).createSocket(SERVER)
.addListener(new WebSocketAdapter() {
public void onTextMessage(WebSocket websocket, String message) {
System.out.println(message);
}
})
.connect();
}
} `
but not this one :
`
import java.io.*;
import com.neovisionaries.ws.client.*;
public class Test
{
private static final String SERVER = "wss://ws.blockchain.info/inv";
public static void main(String[] args) throws Exception
{
WebSocket ws = connect();
ws.sendText("{\"op\":\"addr_sub\", \"addr\":\"65SQr6sh9SeS39PRbw8PHGp9wpv39\"}");
}
private static WebSocket connect() throws IOException, WebSocketException
{
return new WebSocketFactory().setConnectionTimeout(500000000).createSocket(SERVER)
.addListener(new WebSocketAdapter() {
public void onTextMessage(WebSocket websocket, String message) {
System.out.println(message);
}
})
.connect();
}
}`
Same way in jquery it is working, but not in java
My chat works fine on the localhost but when I try to do it on the remote server, it doesn't go on.
RemoteClass >
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface ChatInterface extends Remote {
public String getName() throws RemoteException;
public void sendMsg(String message) throws RemoteException;
public void setInterface (ChatInterface x) throws RemoteException; }
ClientImpl >
import Interface.ChatInterface;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class ChatClient extends UnicastRemoteObject implements ChatInterface{
private String name;
private ChatInterface server;
public ChatClient(String name) throws RemoteException{
this.name = name;
}
#Override
public String getName() throws RemoteException {
return this.name;
}
#Override
public void sendMsg(String message) throws RemoteException {
System.out.println(message);
}
#Override
public void setInterface(ChatInterface server) throws RemoteException {
this.server = server;
} }
ClientMain >
import Interface.ChatInterface;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Scanner;
public class Client{
public static void main(String[] args){
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
try {
Registry registry = LocateRegistry.getRegistry("hostname", port);
ChatInterface chatClient = new ChatClient("User01");
ChatInterface chatServer = (ChatInterface) registry.lookup("ChatServer");
System.out.println("[System] Chat is ready");
chatServer.setInterface(chatClient);
String message = "["+chatClient.getName()+"] got connected";
chatServer.sendMsg(message);
Scanner s = new Scanner(System.in);
while (true) {
message = s.nextLine().trim();
message = "["+ chatClient.getName()+"]" + message;
chatServer.sendMsg(message);
}
} catch (Exception e) {
System.out.println("[System] Server failed: " + e);
System.exit(1);
}
} }
ServerImpl >
import Interface.ChatInterface;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
public class ChatServer extends UnicastRemoteObject implements ChatInterface{
private String name;
private ArrayList<ChatInterface> clients;
public ChatServer(String name)throws RemoteException{
this.name = name;
this.clients = new ArrayList<>();
}
#Override
public String getName() throws RemoteException {
return this.name;
}
#Override
public void sendMsg(String message) throws RemoteException {
broadcast(message);
}
#Override
public synchronized void setInterface(ChatInterface client) throws RemoteException {
clients.add(client);
}
public ArrayList<ChatInterface> getClients(){
return clients;
}
private void broadcast(String message) throws RemoteException {
for (ChatInterface client : clients) {
client.sendMsg(message);
}
} }
ServerMain >
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Server {
public static void main(String[] args) {
try {
LocateRegistry.createRegistry(9876);
Registry registry = LocateRegistry.getRegistry(port);
ChatServer chatServer = new ChatServer("Server");
registry.bind("ChatServer", chatServer);
System.out.println("Server ready :)");
} catch (Exception e) {
System.out.println("[System] Server failed: " + e.toString());
System.exit(1);
}
}
}
The server doesn't do anything at this line
chatServer.setInterface(chatClient);
But doesn't provoke any error. It continues to run for both client & server.
If you have any advice, thank you
Below is my code to integrate with bugzilla and i am getting exception
import java.util.Map;
import com.j2bugzilla.base.Bug;
import com.j2bugzilla.base.BugFactory;
import com.j2bugzilla.base.BugzillaConnector;
import com.j2bugzilla.base.BugzillaMethod;
import com.j2bugzilla.rpc.LogIn;
import com.j2bugzilla.rpc.ReportBug;
public class bugzillaTest {
public static void main(String args[]) throws Exception {
//try to connect to bugzilla
BugzillaConnector conn;
conn=new BugzillaConnector();
conn.connectTo("http://bugzilllaurl");
LogIn login=new LogIn("pramod.kg","123#er");
conn.executeMethod(login);
int id=login.getUserID();
System.out.println("current user id"+id);
BugFactory factory=new BugFactory();
String component="Usability";
String description="this is a test desc";
String os="All";
String platform="PC";
String priority="High";
String product="MMNR7";
String summary="test summary";
String version="1.0";
Bug bugs= factory.newBug()
.setComponent(component)
.setDescription(description)
.setOperatingSystem(os)
.setPlatform(platform)
.setPriority(priority)
.setProduct(product)
.setSummary(summary)
.setVersion(version)
.createBug();
ReportBug report=new ReportBug(bugs);
try {
conn.executeMethod(report);
System.out.println("Bug is logged!");
} catch (Exception e) {
// TODO: handle exception
System.out.println("eror"+e.getMessage());
}
}
}
Exception is :
I have scucessfully logged in but when i run conn.executeMethod(report); i get below error.
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.xmlrpc.parser.XmlRpcResponseParser.getErrorCause()Ljava/lang/Throwable;
at org.apache.xmlrpc.client.XmlRpcStreamTransport.readResponse(XmlRpcStreamTransport.java:195)
at org.apache.xmlrpc.client.XmlRpcStreamTransport.sendRequest(XmlRpcStreamTransport.java:156)
at org.apache.xmlrpc.client.XmlRpcHttpTransport.sendRequest(XmlRpcHttpTransport.java:143)
at org.apache.xmlrpc.client.XmlRpcSunHttpTransport.sendRequest(XmlRpcSunHttpTransport.java:69)
at org.apache.xmlrpc.client.XmlRpcClientWorker.execute(XmlRpcClientWorker.java:56)
at org.apache.xmlrpc.client.XmlRpcClient.execute(XmlRpcClient.java:167)
at org.apache.xmlrpc.client.XmlRpcClient.execute(XmlRpcClient.java:137)
at org.apache.xmlrpc.client.XmlRpcClient.execute(XmlRpcClient.java:126)
at com.j2bugzilla.base.BugzillaConnector.executeMethod(BugzillaConnector.java:164)
at bugzillaTest.main(bugzillaTest.java:92)
Add all the below jars and check
xmlrpc-client-3.1.3
xmlrpc-common-3.1.3
xmlrpc-server-3.1.3
l got fix this issue as below
public class bugzillaTest {
private static final String COMP = "Usability";
private static final String DES = "this is a test desc";
private static final String OS = "All";
private static final String PLAT = "PC";
private static final String PRIO = "High";
private static final String PRO = "MMNR7";
private static final String SUM = "test summary";
private static final String VER = "1.0";
public static void main(String args[]) throws Exception {
// try to connect to bugzilla
BugzillaConnector conn;
BugFactory factory;
Bug bugs;
ReportBug report;
conn = new BugzillaConnector();
conn.connectTo("http://192.168.0.31/");
LogIn login = new LogIn("username", "password");
// create a bug
factory = new BugFactory();
bugs = factory
.newBug().
setOperatingSystem(OS)
.setPlatform(PLAT)
.setPriority(PRIO)
.setProduct(PRO)
.setComponent(COMP)
.setSummary(SUM)
.setVersion(VER)
.setDescription(DES)
.createBug();
report=new ReportBug(bugs);
try{conn.executeMethod(login);
conn.executeMethod(report);
}
catch(Exception e){System.out.println(e.getMessage());}
}
}
I am new to Apache MINA kindly guide me how to read from IoSession. I have stored a POJO in it.
public static EchoUDPServerDiscoveryObjectResponseProperties echoProperties
session.write(echoProperties);
Custom Client:
package client;
import java.net.InetSocketAddress;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.util.logging.Level;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.future.ReadFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.example.udp.client.MemMonClient;
import org.apache.mina.transport.socket.nio.NioDatagramConnector;
/**
*
* #author az
*/
public class CustomClient extends IoHandlerAdapter{
private IoSession session;
private IoConnector connector;
private ConnectFuture connFuture;
public CustomClient() throws InterruptedException{
connector = new NioDatagramConnector();
connector.setHandler(this);
connFuture = connector.connect(new InetSocketAddress("192.168.3.22",6502));
connFuture.addListener(new IoFutureListener<ConnectFuture>() {
public void operationComplete(ConnectFuture future) {
if (future.isConnected()) {
session = future.getSession();
try {
try {
sendData();
// connFuture.await();
} catch (CharacterCodingException ex) {
java.util.logging.Logger.getLogger(MemMonClient.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
private void sendData() throws InterruptedException, CharacterCodingException {
IoBuffer buffer = IoBuffer.allocate(8);
buffer.setAutoExpand(true);
buffer.putString("any", Charset.forName("UTF-8").newEncoder());
buffer.flip();
session.write(buffer);
}
#Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
cause.printStackTrace();
}
#Override
public void messageReceived(IoSession session, Object message)
throws Exception {
connFuture.getSession().getConfig().setUseReadOperation(true);
ReadFuture r = connFuture.getSession().read();
connFuture.await();
connFuture.getSession().getConfig().setUseReadOperation(true);
Object obj = r.getMessage();
System.out.println("r.getMessage(); "+obj);
IoBuffer buffer = IoBuffer.allocate(2048);
buffer.setAutoExpand(true);
Object objReceived = buffer.getObject();
System.out.println(objReceived.toString());
System.out.println("reveived Session recv...");
}
#Override
public void messageSent(IoSession session, Object message) throws Exception {
System.out.println("Message sent...");
}
#Override
public void sessionClosed(IoSession session) throws Exception {
System.out.println("Session closed...");
}
#Override
public void sessionCreated(IoSession session) throws Exception {
System.out.println("Session created...");
}
#Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
System.out.println("Session idle...");
}
#Override
public void sessionOpened(IoSession session) throws Exception {
System.out.println("Session opened...");
}
public static void main (String are[]){
try{
new CustomClient();
}catch(Exception ex){ex.printStackTrace();}
}
}
POJO Java
package pojo;
import java.io.Serializable;
/**
*
* #author az
*/
public class kojo implements Serializable{
private String name = "null";
private String address = "null";
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the address
*/
public String getAddress() {
return address;
}
/**
* #param address the address to set
*/
public void setAddress(String address) {
this.address = address;
}
}
Custom Server Java
package server;
import java.io.IOException;
import java.net.InetSocketAddress;
import org.apache.mina.transport.socket.DatagramSessionConfig;
import org.apache.mina.transport.socket.nio.NioDatagramAcceptor;
/**
*
* #author az
*/
public class CustomServer {
public CustomServer(){
try {
NioDatagramAcceptor acceptor = new NioDatagramAcceptor();
acceptor.setHandler(new ServerHandler(this));
//DefaultIoFilterChainBuilder filter = acceptor.getFilterChain();
DatagramSessionConfig dcfg = acceptor.getSessionConfig();
dcfg.setReuseAddress(true);
acceptor.bind(new InetSocketAddress(6501));
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void receiveUpdate(){
}
public static void main(String are[]){
new CustomServer();
}
}
Server Handler
package server;
import java.nio.charset.Charset;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
/**
*
* #author az
*/
public class ServerHandler extends IoHandlerAdapter {
private CustomServer server;
public ServerHandler(CustomServer server) {
this.server = server;
}
#Override
public void messageReceived(IoSession session, Object message)
throws Exception {
if (message instanceof IoBuffer) {
//decode POJO and send to client
IoBuffer buffer = (IoBuffer) message;
System.out.println(buffer.getString(Charset.forName("UTF-8").newDecoder()));
buffer.setAutoExpand(true);
buffer.putObject(new pojo.POJO());
buffer.flip();
session.write(buffer);
System.out.print("Object Attached and Sent");
}
}
#Override
public void messageSent(IoSession session, Object message) {
System.out.println("Message sent");
}
#Override
public void sessionClosed(IoSession session) throws Exception {
System.out.println("Session closed...");
}
#Override
public void sessionCreated(IoSession session) throws Exception {
System.out.println("Session created...");
}
#Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
System.out.println("Session idle...");
}
#Override
public void sessionOpened(IoSession session) throws Exception {
System.out.println("Session Opened...");
}
}
For school we made a Java application with RMI, there are 3 applications: Server, Client and Rekenaar.
The line where it goes wrong is the Line: "test = (Range[])m.getAllRange();", it gives an dispatchUncaughtException.
package rekenaar;
import server.Opdracht;
import java.rmi.Naming;
import java.util.logging.Level;
import java.util.logging.Logger;
import interfaces.*;
import java.rmi.RemoteException;
/**
*
* #author Windows
*/
public class Rekenaar implements Runnable{
private Range range;
private IRekenCoördinator coordinator;
private long[] priemgetallen;
private Opdracht op;
private Range[] test;
public Rekenaar()
{
try{
this.coordinator = null;
this.coordinator = (IRekenCoördinator) Naming.lookup("rmi://127.0.0.1:1099/RekenC");
this.priemgetallen = coordinator.getPriemgetallen();
this.op = null;
}catch(Exception ex){ex.printStackTrace();}
}
public void Bereken()
{
try{
long rangeOndergrens = (op.getGetal()/2000) * 2000;
range = new Range(priemgetallen, rangeOndergrens);
op.setRange(range);
op.setUitkomst(range.geefSemiPriem(op.getGetal()));
coordinator.RemoveID(op.CheckRange());
IMagazijn m = op.getMagazijn();
test = (Range[])m.getAllRange();
String hoi = m.hoi();
m.AddRange(op);
}catch(RemoteException ex){ex.printStackTrace();}
}
#Override
public void run() {
KrijgtOpdracht();
}
private void KrijgtOpdracht()
{
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(Rekenaar.class.getName()).log(Level.SEVERE, null, ex);
}
if(coordinator != null)
{
try{
op = (Opdracht)coordinator.getOpdracht();
}
catch (Exception ex)
{
ex.printStackTrace();
}
if(op != null ) this.Bereken();
this.run();
}
}
}
Interface:
package interfaces;
import java.io.IOException;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
*
* #author Windows
*/
public interface IMagazijn extends Remote {
/**
*
* #param op Uitgerekende opdracht waarvan de gegevens verwerkt moeten worden op de server
* #throws IOException
*/
public String hoi() throws RemoteException;
public IRange[] getAllRange() throws RemoteException;
public void AddRange(IOpdracht op) throws RemoteException;
}
And here is the Magazijn itself which gives the IRange over RMI:
package server;
import java.rmi.RemoteException;
import java.util.ArrayList;
import interfaces.*;
import java.rmi.server.UnicastRemoteObject;
public class Magazijn extends UnicastRemoteObject implements IMagazijn{
private IRange[] ranges;
private long ondergrens;
public void setOndergrens(long ondergrens) {
this.ondergrens = ondergrens;
}
private long bovengrens;
public void setBovengrens(long bovengrens) {
this.bovengrens = bovengrens;
}
private transient MagazijnManager MM;
private transient ArrayList<Opdracht> dubbeleOpdrachten;
private transient RekenCoördinator RC;
private transient int MAGAZIJN_GROOTTE;
public Magazijn(long ondergrens, long bovengrens, MagazijnManager mm, RekenCoördinator RC)throws RemoteException
{
ranges = new IRange[(int)(bovengrens-ondergrens)/2000];
this.bovengrens = bovengrens;
this.ondergrens = ondergrens;
dubbeleOpdrachten = new ArrayList<Opdracht>();
this.MM = mm;
this.RC = RC;
MAGAZIJN_GROOTTE = (int)(bovengrens - ondergrens) + 1;
}
public void AddRange(IOpdracht op) throws RemoteException
{
ArrayList<IOpdracht> returnList = new ArrayList<IOpdracht>();
ranges[op.getRangeIndex()] = op.getRange();
returnList.add(op);
for(Opdracht o : dubbeleOpdrachten)
{
if(o.getRangeIndex() == op.getRangeIndex())
{
o.setRange(op.getRange());
o.setUitkomst(o.getRange().geefSemiPriem(o.getGetal()));
returnList.add(o);
}
}
MM.StuurOpdrachtenTerug(returnList);
}
public IRange[] getAllRange() throws RemoteException
{
return ranges;
}
public String hoi() throws RemoteException
{
return "poep";
}
public IRange getRange(int rangeIndex)
{
return ranges[rangeIndex];
}
public void StuurOpdracht(Opdracht op)
{
Opdracht o =null;
o = RC.AddOpdracht(op);
if(o!=null)
{
dubbeleOpdrachten.add(o);
}
}
public long getOndergrens()
{
return ondergrens;
}
public long getBovengrens()
{
return bovengrens;
}
public int getMagazijnGrootte()
{
return MAGAZIJN_GROOTTE;
}
}
The Rekenaar got the whole class "Range" so that is not the problem. The problem is something between the casting of IRange into Range. Range itself is Serializable and implements IRange.
The error I get: Exception in thread "main" java.lang.ClassCastException: [Linterfaces.IRange; cannot be cast to [Lrekenaar.Range;
When using RMI, you won't receive the same implementations you have on the server side. Instead you get a proxy class which will call your server. So you cannot cast your method.
Change test to a
IRange[] test
That should do it.