restfull webservice was not connecting sap - java

I'm creating a restfull webservice for connecting SAP.So,here web service methods all are work correctly but only one method was throws error,below is that method.
#Path("/Run")
public class RunBapi {
#GET
public Response runBapi() {
return Response.status(200).entity("getUser is called").build();
}
#GET
#Path("/query")
public Response getUsers(
#QueryParam("LIFNR") String accountNO,
#QueryParam("BUKRS") String companyCode,
#QueryParam("EKORG") String po,
#QueryParam("CHAR1") String indicator) {
ExecuteBapi bapi = new ExecuteBapi();
bapi.bapi(accountNO,companyCode,po,indicator);
return Response.status(200).entity("accountNO is: "+accountNO).build();
}
}
and my ExecuteBapi class is
import com.sap.mw.jco.IFunctionTemplate;
import com.sap.mw.jco.JCO;
public class ExecuteBapi {
public JCO.Client mConnection;
public JCO.Repository mRepository;
public JCO.Function function = null;
public void connectDev()
{
System.out.println("in");
try
{
mConnection = connectSAP();
mConnection.connect();
mRepository = new JCO.Repository("clss", mConnection);
System.out.println("sapconnected");
}
catch(Exception e)
{
System.out.println("error=="+e);
}
}
public JCO.Client connectSAP() {
try {
System.out.println("sap");
setmConnection(JCO.createClient("sapclient",
"userName",
"password",
"en",
"hostname",
"00"));
System.out.println("sap connected");
} catch (Exception ex) {
System.out.println("error in conneting=="+ex);
}
return getmConnection();
}
public JCO.Function createFunction(String name) throws Exception {
try {
IFunctionTemplate ft = mRepository.getFunctionTemplate(name.toUpperCase());
if (ft == null) {
return null;
}
return ft.getFunction();
} catch (Exception ex) {
throw new Exception("Problem retrieving JCO.Function object." + ex);
}
}
public void bapi(String accountNO, String companyCode, String po, String indicator){
System.out.println("bapiex");
connectDev();
}
public static void main(String args[]){
ExecuteBapi bapi = new ExecuteBapi();
connectDev();
}
/**
* #return the mConnection
*/
public JCO.Client getmConnection() {
return mConnection;
}
/**
* #param mConnection the mConnection to set
*/
public void setmConnection(JCO.Client mConnection) {
this.mConnection = mConnection;
}
}
so here we running ExcecuteBapi class manualy SAP will connect,but we run this method in webservice it'll throw error like
org.jboss.resteasy.spi.UnhandledException: java.lang.NoClassDefFoundError:com/sap/mw/jco/JCO
Please help me.

Related

java.lang.AssertionError at org.java_websocket.client.WebSocketClient.run(WebSocketClient.java:190)

I am using WebSocketClient class to get the data from websocket in my android app but when anything change in Internet connection ( Disconnect from Internet ) it gives the following error in WebSocketClient.java file
USER_COMMENT=null
ANDROID_VERSION=10
APP_VERSION_NAME=0.0.1
BRAND=google
PHONE_MODEL=Android SDK built for x86_64
CUSTOM_DATA=
STACK_TRACE=java.lang.AssertionError
at org.java_websocket.client.WebSocketClient.run(WebSocketClient.java:190)
at java.lang.Thread.run(Thread.java:919)
But the WebSocketClient.java is read only file it is coming from java-websocket-1.3.0.jar file
WebSocketClient.java
package org.java_websocket.client;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.NotYetConnectedException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.CountDownLatch;
import org.java_websocket.SocketChannelIOHelper;
import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketAdapter;
import org.java_websocket.WebSocketFactory;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.WrappedByteChannel;
import org.java_websocket.WebSocket.READYSTATE;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_10;
import org.java_websocket.exceptions.InvalidHandshakeException;
import org.java_websocket.handshake.HandshakeImpl1Client;
import org.java_websocket.handshake.Handshakedata;
import org.java_websocket.handshake.ServerHandshake;
public abstract class WebSocketClient extends WebSocketAdapter implements Runnable {
protected URI uri;
private WebSocketImpl conn;
private SocketChannel channel;
private ByteChannel wrappedchannel;
private Thread writethread;
private Thread readthread;
private Draft draft;
private Map<String, String> headers;
private CountDownLatch connectLatch;
private CountDownLatch closeLatch;
private int timeout;
private WebSocketClient.WebSocketClientFactory wsfactory;
private InetSocketAddress proxyAddress;
public WebSocketClient(URI serverURI) {
this(serverURI, new Draft_10());
}
public WebSocketClient(URI serverUri, Draft draft) {
this(serverUri, draft, (Map)null, 0);
}
public WebSocketClient(URI serverUri, Draft draft, Map<String, String> headers, int connecttimeout) {
this.uri = null;
this.conn = null;
this.channel = null;
this.wrappedchannel = null;
this.connectLatch = new CountDownLatch(1);
this.closeLatch = new CountDownLatch(1);
this.timeout = 0;
this.wsfactory = new DefaultWebSocketClientFactory(this);
this.proxyAddress = null;
if (serverUri == null) {
throw new IllegalArgumentException();
} else if (draft == null) {
throw new IllegalArgumentException("null as draft is permitted for `WebSocketServer` only!");
} else {
this.uri = serverUri;
this.draft = draft;
this.headers = headers;
this.timeout = connecttimeout;
try {
this.channel = SelectorProvider.provider().openSocketChannel();
this.channel.configureBlocking(true);
} catch (IOException var6) {
this.channel = null;
this.onWebsocketError((WebSocket)null, var6);
}
if (this.channel == null) {
this.conn = (WebSocketImpl)this.wsfactory.createWebSocket(this, draft, (Socket)null);
this.conn.close(-1, "Failed to create or configure SocketChannel.");
} else {
this.conn = (WebSocketImpl)this.wsfactory.createWebSocket(this, draft, this.channel.socket());
}
}
}
public URI getURI() {
return this.uri;
}
public Draft getDraft() {
return this.draft;
}
public void connect() {
if (this.writethread != null) {
throw new IllegalStateException("WebSocketClient objects are not reuseable");
} else {
this.writethread = new Thread(this);
this.writethread.start();
}
}
public boolean connectBlocking() throws InterruptedException {
this.connect();
this.connectLatch.await();
return this.conn.isOpen();
}
public void close() {
if (this.writethread != null) {
this.conn.close(1000);
}
}
public void closeBlocking() throws InterruptedException {
this.close();
this.closeLatch.await();
}
public void send(String text) throws NotYetConnectedException {
this.conn.send(text);
}
public void send(byte[] data) throws NotYetConnectedException {
this.conn.send(data);
}
public void run() {
if (this.writethread == null) {
this.writethread = Thread.currentThread();
}
this.interruptableRun();
assert !this.channel.isOpen();
}
private final void interruptableRun() {
if (this.channel != null) {
try {
String host;
int port;
if (this.proxyAddress != null) {
host = this.proxyAddress.getHostName();
port = this.proxyAddress.getPort();
} else {
host = this.uri.getHost();
port = this.getPort();
}
this.channel.connect(new InetSocketAddress(host, port));
this.conn.channel = this.wrappedchannel = this.createProxyChannel(this.wsfactory.wrapChannel(this.channel, (SelectionKey)null, host, port));
this.timeout = 0;
this.sendHandshake();
this.readthread = new Thread(new WebSocketClient.WebsocketWriteThread());
this.readthread.start();
} catch (ClosedByInterruptException var3) {
this.onWebsocketError((WebSocket)null, var3);
return;
} catch (Exception var4) {
this.onWebsocketError(this.conn, var4);
this.conn.closeConnection(-1, var4.getMessage());
return;
}
ByteBuffer buff = ByteBuffer.allocate(WebSocketImpl.RCVBUF);
try {
while(this.channel.isOpen()) {
if (SocketChannelIOHelper.read(buff, this.conn, this.wrappedchannel)) {
this.conn.decode(buff);
} else {
this.conn.eot();
}
if (this.wrappedchannel instanceof WrappedByteChannel) {
WrappedByteChannel w = (WrappedByteChannel)this.wrappedchannel;
if (w.isNeedRead()) {
while(SocketChannelIOHelper.readMore(buff, this.conn, w)) {
this.conn.decode(buff);
}
this.conn.decode(buff);
}
}
}
} catch (CancelledKeyException var5) {
this.conn.eot();
} catch (IOException var6) {
this.conn.eot();
} catch (RuntimeException var7) {
this.onError(var7);
this.conn.closeConnection(1006, var7.getMessage());
}
}
}
private int getPort() {
int port = this.uri.getPort();
if (port == -1) {
String scheme = this.uri.getScheme();
if (scheme.equals("wss")) {
return 443;
} else if (scheme.equals("ws")) {
return 80;
} else {
throw new RuntimeException("unkonow scheme" + scheme);
}
} else {
return port;
}
}
private void sendHandshake() throws InvalidHandshakeException {
String part1 = this.uri.getPath();
String part2 = this.uri.getQuery();
String path;
if (part1 != null && part1.length() != 0) {
path = part1;
} else {
path = "/";
}
if (part2 != null) {
path = path + "?" + part2;
}
int port = this.getPort();
String host = this.uri.getHost() + (port != 80 ? ":" + port : "");
HandshakeImpl1Client handshake = new HandshakeImpl1Client();
handshake.setResourceDescriptor(path);
handshake.put("Host", host);
if (this.headers != null) {
Iterator i$ = this.headers.entrySet().iterator();
while(i$.hasNext()) {
Entry<String, String> kv = (Entry)i$.next();
handshake.put((String)kv.getKey(), (String)kv.getValue());
}
}
this.conn.startHandshake(handshake);
}
public READYSTATE getReadyState() {
return this.conn.getReadyState();
}
public final void onWebsocketMessage(WebSocket conn, String message) {
this.onMessage(message);
}
public final void onWebsocketMessage(WebSocket conn, ByteBuffer blob) {
this.onMessage(blob);
}
public final void onWebsocketOpen(WebSocket conn, Handshakedata handshake) {
this.connectLatch.countDown();
this.onOpen((ServerHandshake)handshake);
}
public final void onWebsocketClose(WebSocket conn, int code, String reason, boolean remote) {
this.connectLatch.countDown();
this.closeLatch.countDown();
if (this.readthread != null) {
this.readthread.interrupt();
}
this.onClose(code, reason, remote);
}
public final void onWebsocketError(WebSocket conn, Exception ex) {
this.onError(ex);
}
public final void onWriteDemand(WebSocket conn) {
}
public void onWebsocketCloseInitiated(WebSocket conn, int code, String reason) {
this.onCloseInitiated(code, reason);
}
public void onWebsocketClosing(WebSocket conn, int code, String reason, boolean remote) {
this.onClosing(code, reason, remote);
}
public void onCloseInitiated(int code, String reason) {
}
public void onClosing(int code, String reason, boolean remote) {
}
public WebSocket getConnection() {
return this.conn;
}
public final void setWebSocketFactory(WebSocketClient.WebSocketClientFactory wsf) {
this.wsfactory = wsf;
}
public final WebSocketFactory getWebSocketFactory() {
return this.wsfactory;
}
public InetSocketAddress getLocalSocketAddress(WebSocket conn) {
return this.channel != null ? (InetSocketAddress)this.channel.socket().getLocalSocketAddress() : null;
}
public InetSocketAddress getRemoteSocketAddress(WebSocket conn) {
return this.channel != null ? (InetSocketAddress)this.channel.socket().getLocalSocketAddress() : null;
}
public abstract void onOpen(ServerHandshake var1);
public abstract void onMessage(String var1);
public abstract void onClose(int var1, String var2, boolean var3);
public abstract void onError(Exception var1);
public void onMessage(ByteBuffer bytes) {
}
public ByteChannel createProxyChannel(ByteChannel towrap) {
return (ByteChannel)(this.proxyAddress != null ? new WebSocketClient.DefaultClientProxyChannel(towrap) : towrap);
}
public void setProxy(InetSocketAddress proxyaddress) {
this.proxyAddress = proxyaddress;
}
private class WebsocketWriteThread implements Runnable {
private WebsocketWriteThread() {
}
public void run() {
Thread.currentThread().setName("WebsocketWriteThread");
try {
while(!Thread.interrupted()) {
SocketChannelIOHelper.writeBlocking(WebSocketClient.this.conn, WebSocketClient.this.wrappedchannel);
}
} catch (IOException var2) {
WebSocketClient.this.conn.eot();
} catch (InterruptedException var3) {
}
}
}
public interface WebSocketClientFactory extends WebSocketFactory {
ByteChannel wrapChannel(SocketChannel var1, SelectionKey var2, String var3, int var4) throws IOException;
}
public class DefaultClientProxyChannel extends AbstractClientProxyChannel {
public DefaultClientProxyChannel(ByteChannel towrap) {
super(towrap);
}
public String buildHandShake() {
StringBuilder b = new StringBuilder();
String host = WebSocketClient.this.uri.getHost();
b.append("CONNECT ");
b.append(host);
b.append(":");
b.append(WebSocketClient.this.getPort());
b.append(" HTTP/1.1\n");
b.append("Host: ");
b.append(host);
b.append("\n");
return b.toString();
}
}
}
The third-party library has a description. You can write a class to inherit the WebSocketClient class and rewrite the code after network disconnection and reconnection. The code example of the third-party library is provided for reference.

Parsion JSON String into JSONOBJECT in android [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Using GSON to parse a JSON with dynamic "key" and "value" in android
(2 answers)
Closed 5 years ago.
This is my JsonResponse , and since its not in array i am facing some difficulties , can any one help me out ? in android
{
"errorno": "0",
"responsemsg": "Login Success.",
"busid": "1234",
"returnmobileno": "1234567890"
}
try this
try {
JSONObject lJsonObject = new JSONObject(response);
String errorno = lJsonObject .getString("errorno");
String responsemsg = lJsonObject .getString("responsemsg");
String busid = response.lJsonObject ("busid");
String returnmobileno = lJsonObject .getString("returnmobileno");
} catch (JSONException e) {
e.printStackTrace();
}
Try this,
try {
String errorno = response.getString("errorno");
String responsemsg = response.getString("responsemsg");
String busid = response.getString("busid");
String returnmobileno = response.getString("returnmobileno");
Log.d(TAG, "errorno:" + errorno+" responsemsg:"+responsemsg+" busid:"+busid+" returnmobileno:"+returnmobileno);
} catch (JSONException e) {
e.printStackTrace();
}
use below code to pass your strong
serverData = gson.fromJson(response, ServerData.class);
in build.gradle -> dependencies
// retrofit, gson
implementation 'com.google.code.gson:gson:2.8.2'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
public class ApiClient {
public static final String SERVER_BASE_URL = "http://example.com/abc/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(SERVER_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
public interface ApiInterface {
#POST("appServices/getData.php")
#FormUrlEncoded
Call<ResponseBody> getAllDataJSONFromServer(#Field("vcode") String vcode);
}
public class ServerData implements Parcelable {
public static final Creator<ServerData> CREATOR = new Creator<ServerData>() {
#Override
public ServerData createFromParcel(Parcel in) {
return new ServerData(in);
}
#Override
public ServerData[] newArray(int size) {
return new ServerData[size];
}
};
private static final int VERSION = 1;
#SerializedName("errorno")
private String errorno;
#SerializedName(responsemsg)
private String responsemsg;
#SerializedName("busid")
private String busid;
#SerializedName("returnmobileno")
private String returnmobileno;
private void readFromParcel(Parcel in) {
if (in.readInt() == VERSION) {
errorno = in.readString();
responsemsg = in.readString();
busid = in.readString();
returnmobileno = in.readString();
}
}
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(VERSION);
parcel.writeString(errorno);
parcel.writeString(responsemsg);
parcel.writeString(busid);
parcel.writeString(returnmobileno);
}
#Override
public int describeContents() {
return 0;
}
public String getErrorno() {
return errorno;
}
public void setErrorno(String errorno) {
this.errorno = errorno;
}
public String getResponsemsg() {
return responsemsg;
}
public void setResponsemsg(String responsemsg) {
this.responsemsg = responsemsg;
}
public String getBusid() {
return busid;
}
public void setBusid(String busid) {
this.busid = busid;
}
public String getReturnmobileno() {
return returnmobileno;
}
public void setReturnmobileno(String returnmobileno) {
this.returnmobileno = returnmobileno;
}
}
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
// get and save all data from server
Call<ResponseBody> call = apiService.getAllDataJSONFromServer(local_vcode, local_cvcode, pckgName);
call.enqueue(new Callback<ResponseBody>() {
#SuppressWarnings("ConstantConditions")
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> responsebody) {
try {
String response = responsebody.body().string();
serverData = gson.fromJson(response, ServerData.class); // this will fetch data to model class ServerData
if (serverData != null) {
// do the rest here...
String vcode = serverData.getVcode();
Log.e("~~~ vode = ", vcode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
progressDialog.dismiss();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
try {
t.printStackTrace();
progressDialog.dismiss();
} catch (Exception ignored) {
}
}
});

playframework-2.3 Akka-Async interaction porting?

I have some old playframework 2.2 java webservice that interacts with akka, and now I should port them to playframework 2.3.
However, async has been deprecated and even after reading the doc about the async porting (http://www.playframework.com/documentation/2.3.x/JavaAsync) I wasn't able to understand how to apply it to my case (code below):
I must make the await for a timeout/akka server reply before starting the construction of my reply (ok()), otherwise I will block the thread.
I should make the actorselection async too.
I should make the akka server reply parsing/reply construction async too
I looked around and I wasn't able to find an example of such interactions, even in typesafe templates.
How could I do that?
/* playframework 2.2 code */
public class Resolve extends Controller {
private final static String RESOLVER_ACTOR = play.Play.application().configuration().getString("actor.resolve");
#CorsRest
#VerboseRest
#RequireAuthentication
#BodyParser.Of(BodyParser.Json.class)
public static Result getJsonTree() {
JsonNode json = request().body().asJson();
ProtoBufMessages.ResolveRequest msg;
ResolveRequestInput input;
try {
input = new ResolveRequestInput(json);
} catch (rest.exceptions.MalformedInputException mie) {
return badRequest(mie.getMessage());
}
msg = ((ProtoBufMessages.ResolveRequest)input.getMessage());
ActorSelection resolver = Akka.system().actorSelection(RESOLVER_ACTOR);
Timeout tim = new Timeout(Duration.create(4, "seconds"));
Future<Object> fut = Patterns.ask(resolver, input.getMessage(), tim);
return async (
F.Promise.wrap(fut).map(
new F.Function<Object, Result>() {
public Result apply(Object response) {
ProtoBufMessages.ResolveReply rsp = ((ProtoBufMessages.ResolveReply)response);
ResolveOutput output = new ResolveOutput(rsp);
return ok(output.getJsonReply());
}
}
)
);
}
}
I came out with the code below
public class Resolve extends Controller {
private final static String RESOLVER_ACTOR = play.Play.application().configuration().getString("actor.resolve");
private final static BrainProtoMessages.ResolveReply request_error = BrainProtoMessages.ResolveReply.newBuilder()
.setReturnCode(BResults.REQUEST_FAILED)
.build();
#CorsRest
#VerboseRest
#RequireAuthentication
#BodyParser.Of(BodyParser.Json.class)
public static Result resolve_map() {
final ResolveRequestInput input;
final F.Promise<ActorSelection> selected_target;
final F.Promise<Future<Object>> backend_request;
final F.Promise<BrainProtoMessages.ResolveReply> backend_reply;
final F.Promise<ObjectNode> decode_json;
final F.Promise<Result> ok_result;
final JsonNode json = request().body().asJson();
try {
input = new ResolveRequestInput(json);
} catch (rest.exceptions.MalformedInputException mie) {
return badRequest(mie.getMessage());
}
selected_target = F.Promise.promise(
new F.Function0<ActorSelection>() {
#Override
public ActorSelection apply() throws Throwable {
return Akka.system().actorSelection(RESOLVER_ACTOR);
}
}
);
backend_request =
selected_target.map(
new F.Function<ActorSelection, Future<Object>>() {
#Override
public Future<Object> apply(ActorSelection actorSelection) throws Throwable {
return Patterns.ask(actorSelection, input.getMessage(),new Timeout(Duration.create(4, "seconds")));
}
}
);
backend_reply = backend_request.map(
new F.Function<Future<Object>, BrainProtoMessages.ResolveReply>() {
#Override
public BrainProtoMessages.ResolveReply apply(Future<Object> akka_reply) throws Throwable {
try {
return (BrainProtoMessages.ResolveReply) Await.result(akka_reply, Duration.create(4, "seconds"));
}catch(Exception error)
{
return request_error;
}
}
}
);
decode_json = backend_reply.map(
new F.Function<BrainProtoMessages.ResolveReply, ObjectNode>() {
#Override
public ObjectNode apply(BrainProtoMessages.ResolveReply response) throws Throwable {
return new ResolveOutput(response).getJsonReply();
}
}
);
ok_result = decode_json.map(
new F.Function<ObjectNode, Result>() {
#Override
public Result apply(ObjectNode reply) {
return ok(reply);
}
}
);
try {
return ok_result.get(8000);
}catch(Exception error)
{
return internalServerError();
}
}
}

PHP to Java Connection

I am working on a project where I send supposedly press a button on a webpage and it then executes a command in java. What I'm looking for is something like this. Say if I pressed a button and then it sends a command to the minecraft server to reload plugins. How would I go achieving this? Thanks
When you have to comunicate between different applications you will problably need a bridge. In your case I'd suggest to use Minecraft's RCON service (must be enabled in the confingiration) or a plugin that do something similar, like Websend.
Websend code is actually available on Github if you would like to know how the plugin work.
Connection between PHP and Java through sockets
Step 1:
Create a java server
I have created a nice API for these situations. you can use them if you would like:
ChatServer
all you need to do is create a new instance of this class
package com.weebly.foxgenesis.src;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.io.*;
public final class ChatServer implements Runnable
{
private final int CLIENTMAXIMUM;
private ChatServerThread clients[];
private ServerSocket server = null;
private Thread thread = null;
private int clientCount = 0;
private final ServerReciever output;
private List<ConnectHandler> connectHandlers = new ArrayList<ConnectHandler>();
private List<QuitHandler> quitHandlers = new ArrayList<QuitHandler>();
/**
* creates a new ChatServer for connection between clients
* #param a ServerReciever implementing class
*/
public ChatServer(ServerReciever a)
{
CLIENTMAXIMUM = a.getMaximunClients();
output = a;
clients = new ChatServerThread[CLIENTMAXIMUM];
try
{
server = new ServerSocket();
server.bind(new InetSocketAddress(output.getHost(), output.getPort()));
log(server);
start();
}
catch(IOException ioe)
{
error("Can not bind to port " + a.getPort() + ": " + ioe.getMessage());
}
}
/**
* Force the Server to handle a msg
*/
public void add(String text)
{
output.handle(text);
}
/**
* Force the Server to handle an error
*/
public void error(String text)
{
output.handleError(text);
}
/**
* Log to the server
*/
public void log(Object text)
{
output.handleLog(text);
}
/**
* send a message to a specific client
* #param ID ID of client
* #param msg
*/
public void send(int ID, String msg)
{
clients[findClient(ID)].send(msg);
add(msg);
}
/**
* Called by runnable
*/
public void run()
{
while (thread != null)
{
try
{
if(clientCount != CLIENTMAXIMUM){
log("Waiting for a client ...");
addThread(server.accept());
}
}
catch(IOException ioe)
{
error("Server accept error: " + ioe);
stop();
}
}
}
private void start()
{
if (thread == null)
{
thread = new Thread(this);
thread.start();
}
}
/**
* Stops the server
*/
#SuppressWarnings("deprecation")
public void stop()
{
if (thread != null)
{
thread.stop();
thread = null;
}
}
private int findClient(int ID)
{
for (int i = 0; i < clientCount; i++)
if (clients[i].getID() == ID)
return i;
return -1;
}
/**
* sends a message to a
* #param ID
* #param input
*/
public synchronized void handle(int ID, String input)
{
StringTokenizer t = new StringTokenizer(input);
String[] arg = new String[t.countTokens()];
for(int i=0; t.hasMoreElements(); i++)
arg[i] = t.nextToken(",");
if(arg[0] == "new")
switch(input)
{
case".bye":
{
clients[findClient(ID)].send(".bye");
remove(ID);
break;
}
default:
{
for (int i = 0; i < clientCount; i++)
clients[i].send(input);
break;
}
}
}
/**
* sends a message to all clients
* #param input message to send
*/
public void sendAll(String input)
{
for (int i = 0; i < clientCount; i++)
clients[i].send(input);
}
/**
* remove a selected ID
* #param ID ID of client
*/
#SuppressWarnings("deprecation")
public synchronized void remove(int ID)
{
int pos = findClient(ID);
if (pos >= 0)
{
ChatServerThread toTerminate = clients[pos];
log("Removing client thread " + ID + " at " + pos);
if (pos < clientCount-1)
for (int i = pos+1; i < clientCount; i++)
clients[i-1] = clients[i];
clientCount--;
QuitEvent e = new QuitEvent(toTerminate.getID());
e.setGameBreaking(true);
for(QuitHandler a: quitHandlers)
a.quit(e);
try
{
toTerminate.close(); }
catch(IOException ioe)
{
error("Error closing thread: " + ioe);
}
toTerminate.stop();
}
}
private void addThread(Socket socket)
{
if (clientCount < clients.length)
{
log("Client accepted: " + socket);
clients[clientCount] = new ChatServerThread(this, socket);
try
{
clients[clientCount].open();
clients[clientCount].start();
ClientConnectEvent e = new ClientConnectEvent(clients[clientCount],clients[clientCount].getID());
clientCount++;
for(ConnectHandler a: connectHandlers)
a.connect(e);
}
catch(IOException ioe)
{
error("Error opening thread: " + ioe);
}
}
else
error("Client refused: maximum " + clients.length + " reached.");
}
public String toString()
{
return "ChatServer{;host=" + output.getHost() + ";port=" + output.getPort() + ";clients=" + clientCount + ";}";
}
public int getAmountOfClients()
{
return clientCount;
}
public void addConnectHandler(ConnectHandler handler)
{
connectHandlers.add(handler);
}
public void removeConnectHandler(ConnectHandler handler)
{
connectHandlers.remove(handler);
}
public int getMaxClients()
{
return CLIENTMAXIMUM;
}
public void addQuitHandler(QuitHandler quitHandler)
{
quitHandlers.add(quitHandler);
}
public void removeQuitHandler(QuitHandler quithandler)
{
quitHandlers.remove(quithandler);
}
}
ChatServerThread
Used by the ChatServer as client connections
package com.weebly.foxgenesis.src;
import java.net.*;
import java.io.*;
public final class ChatServerThread extends Thread
{
private ChatServer server = null;
private Socket socket = null;
private int ID = -1;
private DataInputStream streamIn = null;
private DataOutputStream streamOut = null;
public ChatServerThread(ChatServer server, Socket socket)
{
super();
this.server = server;
this.socket = socket;
this.ID = socket.getPort();
}
#SuppressWarnings("deprecation")
public void send(String msg)
{
try
{
streamOut.writeUTF(msg);
streamOut.flush();
}
catch(IOException ioe)
{
server.error(ID + " ERROR sending: " + ioe.getMessage());
server.remove(ID);
stop();
}
}
public int getID()
{
return ID;
}
#SuppressWarnings("deprecation")
#Override
public void run()
{
server.log("Server Thread " + ID + " running.");
while (true)
{
try
{
server.handle(ID, streamIn.readUTF());
}
catch(IOException ioe)
{
server.error(ID + " ERROR reading: " + ioe.getMessage());
server.remove(ID);
stop();
}
}
}
public void open() throws IOException
{
streamIn = new DataInputStream(new
BufferedInputStream(socket.getInputStream()));
streamOut = new DataOutputStream(new
BufferedOutputStream(socket.getOutputStream()));
}
public void close() throws IOException
{
if (socket != null) socket.close();
if (streamIn != null) streamIn.close();
if (streamOut != null) streamOut.close();
}
}
ClientConnectEvent
package com.weebly.foxgenesis.src;
public class ClientConnectEvent extends ConnectionEvent
{
private final ChatServerThread client;
public ClientConnectEvent(ChatServerThread client, int clientID)
{
super(clientID);
this.client = client;
}
public ChatServerThread getClient()
{
return client;
}
#Override
public boolean isConnectionBreaking(){return false;}
}
ConnectHandler
package com.weebly.foxgenesis.src;
public interface ConnectHandler
{
public void connect(ClientConnectEvent e);
}
ClientQuitEvent
package com.weebly.foxgenesis.src;
public class ClientQuitEvent extends ConnectionEvent
{
public ClientQuitEvent(int clientID)
{
super(clientID);
}
#Override
public boolean isConnectionBreaking()
{
return true;
}
}
QuitHandler
package com.weebly.foxgenesis.src;
public interface QuitHandler
{
public void quit(ClientQuitEvent e);
}
ServerReciever
package com.weebly.foxgenesis.src;
public interface ServerReciever
{
public void handle(String msg);
public void handleError(String msg);
public int getPort();
public int getMaximunClients();
public void handleLog(Object text);
public String getHost();
}
ConnectionEvent
package com.weebly.foxgenesis.src;
public abstract class ConnectionEvent
{
public abstract boolean isConnectionBreaking();
private int clientID;
public ConnectionEvent(int clientID)
{
this.clientID = clientID;
}
public int getClientID()
{
return clientID;
}
}
Step 2:
Connect Server to Bukkit
i have provided an example on how to connect the server to bukkit by making a new plugin.
public class MyPlugin extends JavaPlugin
{
#Override
public void onEnable()
{
ChatServer server = new ChatServer(new ServerReciever()
{
#Override
public void handle(String msg){handleMsg(msg);}
#Override
public void handleError(String msg){handleErr(msg);}
#Override
public int getPort(){return 25567}
#Override
public int getMaximunClients(){return 100;}
#Override
public void handleLog(Object text){log(text);}
#Override
public String getHost(){return "localhost";}
}
}
public void handleLog(Object text)
{
System.out.println(text);
}
public void handelErr(String msg)
{
System.err.println(msg);
}
public void handleMsg(String msg)
{
if(msg.equalsIgnoreCase("reload"))
Bukkit.reloadOrSomething(); //i don't know the void off the top of my head
}
}
Step 3:
Port Forward
if you don't know what that is go ahead and google it. there are some great tutorials online. you want to port forward the port that you set in the code.
Step 4:
Send a message to the Server
i do not know PHP but all you need to do is send a UTF-8 Encoded message to the server's ip on the port that you hard coded above.
Step 5:
ENJOY!

Need ideas on fixing RSS feed parsing

http://www.ibm.com/developerworks/opensource/library/x-android/
I am using the code here, specifically the AndroidSaxParser. The problem is, is that I get all 4 parts of the Message objects the same as the title. I've combed it over and over, but I can't find anything wrong with what I put together.
Any ideas on where to look?
Here is the code:
public class AndroidSaxFeedParser extends BaseFeedParser {
public AndroidSaxFeedParser(String feedUrl) {
super(feedUrl);
}
public List<Message> parse() {
final Message currentMessage = new Message();
RootElement root = new RootElement("rss");
final List<Message> messages = new ArrayList<Message>();
Element channel = root.getChild("channel");
Element item = channel.getChild(ITEM);
item.setEndElementListener(new EndElementListener(){
public void end() {
messages.add(currentMessage.copy());
}
});
item.getChild(TITLE).setEndTextElementListener(new EndTextElementListener(){
public void end(String body) {
currentMessage.setTitle(body);
}
});
item.getChild(LINK).setEndTextElementListener(new EndTextElementListener(){
public void end(String body) {
currentMessage.setLink(body);
}
});
item.getChild(DESCRIPTION).setEndTextElementListener(new EndTextElementListener(){
public void end(String body) {
currentMessage.setDescription(body);
}
});
item.getChild(PUB_DATE).setEndTextElementListener(new EndTextElementListener(){
public void end(String body) {
currentMessage.setDate(body);
}
});
try {
Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, root.getContentHandler());
} catch (Exception e) {
throw new RuntimeException(e);
}
return messages;
}
}
public abstract class BaseFeedParser implements FeedParser {
// names of the XML tags
static final String PUB_DATE = "pubDate";
static final String DESCRIPTION = "description";
static final String LINK = "link";
static final String TITLE = "title";
static final String ITEM = "item";
static final String CHANNEL = "channel";
final URL feedUrl;
protected BaseFeedParser(String feedUrl){
try {
this.feedUrl = new URL(feedUrl);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
protected InputStream getInputStream() {
try {
return feedUrl.openConnection().getInputStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

Categories

Resources