Copy a file client server java rmi - java

I'm making a simple client-server rmi application with SSL. The code works fine, but when I copy a file that weights 58kb, it generates a copy that weights 1kb.
I'm going crazy with this. I will appreciate any help. This is the code:
Client:
package tpfinal;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.rmi.AccessException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import javax.rmi.ssl.SslRMIClientSocketFactory;
public class Client {
public static void main (String[] args) throws FileNotFoundException, IOException {
if (args.length < 2) {
System.out.println("Se necesitan dos argumentos: Hostname y Filename");
System.exit(1);
}
try {
System.setProperty("javax.net.ssl.keyStore","C:\\Users\\Lucho\\workspace\\Distribuida\\bin\\keystore");
System.setProperty("javax.net.ssl.keyStorePassword","123456");
System.setProperty("javax.net.ssl.trustStore","C:\\Users\\Lucho\\workspace\\Distribuida\\bin\\truststore");
System.setProperty("javax.net.ssl.trustStorePassword","123456");
Registry registry = LocateRegistry.getRegistry(null, ServerInterface.PORT, new SslRMIClientSocketFactory());
ServerInterface server = (ServerInterface) registry.lookup("SSLServer");
int bufferSize = 1024;
int pos = 0;
Respuesta respuesta = new Respuesta();
String serverPath = System.getProperty("user.dir") + System.getProperty("file.separator") + args[1];
String clientCopyPath = System.getProperty("user.dir") + System.getProperty("file.separator") + "clicopia1-" + args[1];
String serverCopyPath = System.getProperty("user.dir") + System.getProperty("file.separator") + "sercopia2-" + args[1];
System.out.println(serverPath + " serverPath");
System.out.println(clientCopyPath + " clientCopyPath");
respuesta = server.leerArchivo(serverPath, pos, bufferSize);
while (respuesta.getLeidos() > 0) {
if (server.escribirArchivo(clientCopyPath, respuesta.getLeidos(), respuesta.getBuffer()) == -1) {
System.out.println("Se produjo un error al abrir el archivo copia1");
}
if (server.escribirArchivo(serverCopyPath, respuesta.getLeidos(), respuesta.getBuffer()) == -1) {
System.out.println("Se produjo un error al abrir el archivo copia2");
}
pos += respuesta.getLeidos();
respuesta = server.leerArchivo(serverPath, pos, bufferSize);
System.out.println(pos);
}
if (respuesta.getLeidos() == -1) {
System.out.println("Se produjo un error al abrir el archivo original");
}
} catch (AccessException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}
}
}
Server:
package tpfinal;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import javax.rmi.ssl.SslRMIClientSocketFactory;
import javax.rmi.ssl.SslRMIServerSocketFactory;
public class Server extends UnicastRemoteObject implements ServerInterface {
protected Server() throws RemoteException{
super(0, new SslRMIClientSocketFactory(), new SslRMIServerSocketFactory(null, null, true));
}
public static void main(String[] args) {
try {
System.setProperty("javax.net.ssl.keyStore","C:\\Users\\Lucho\\workspace\\Distribuida\\bin\\keystore");
System.setProperty("javax.net.ssl.keyStorePassword","123456");
System.setProperty("javax.net.ssl.trustStore","C:\\Users\\Lucho\\workspace\\Distribuida\\bin\\truststore");
System.setProperty("javax.net.ssl.trustStorePassword","123456");
Registry registry = LocateRegistry.getRegistry(null, ServerInterface.PORT, new SslRMIClientSocketFactory());
Server server = new Server();
registry.rebind("SSLServer", server);
System.out.println("SSLServer bound in registry");
} catch (Exception e) {
System.out.println("SSLServer error: " + e.getMessage());
e.printStackTrace();
}
}
#Override
public Respuesta leerArchivo(String fileName, int pos, int cant)
throws RemoteException, FileNotFoundException, IOException {
File archivo = new File(fileName);
Respuesta respuesta = new Respuesta();
respuesta.setLeidos(-1);
respuesta.setPedidos(cant);
if (archivo.exists() && archivo.setReadOnly()) {
FileInputStream in = new FileInputStream(archivo);
in.skip(pos); // Descartamos lo leĆ­do.
respuesta.setLeidos(in.read(respuesta.getBuffer(), 0, cant));
if (respuesta.getLeidos() == -1) {
respuesta.setLeidos(0);
}
in.close();
}
return respuesta;
}
#Override
public int escribirArchivo(String fileName, int cant, byte[] data)
throws RemoteException, FileNotFoundException, IOException {
File archivo = new File(fileName);
FileOutputStream out = new FileOutputStream(archivo);
out.write(data, 0, cant);
out.close();
return cant;
}
}
RmiRegistry
package tpfinal;
import java.rmi.registry.LocateRegistry;
import javax.rmi.ssl.SslRMIClientSocketFactory;
import javax.rmi.ssl.SslRMIServerSocketFactory;
public class RmiRegistry {
public static void main(String[] args) throws Exception {
System.out.println("Rmi Registry running on port " + ServerInterface.PORT);
System.setProperty("javax.net.ssl.keyStore","C:\\Users\\Lucho\\workspace\\Distribuida\\bin\\keystore");
System.setProperty("javax.net.ssl.keyStorePassword","123456");
System.setProperty("javax.net.ssl.trustStore","C:\\Users\\Lucho\\workspace\\Distribuida\\bin\\truststore");
System.setProperty("javax.net.ssl.trustStorePassword","123456");
LocateRegistry.createRegistry(ServerInterface.PORT,new SslRMIClientSocketFactory(), new SslRMIServerSocketFactory(null, null, true));
//Sleep
Thread.sleep(Long.MAX_VALUE);
}
}
ServerInterface:
package tpfinal;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface ServerInterface extends Remote {
int PORT = 8844;
public Respuesta leerArchivo(String fileName, int pos, int cant) throws RemoteException, FileNotFoundException, IOException;
public int escribirArchivo(String fileName, int cant, byte[] data) throws RemoteException, FileNotFoundException, IOException;
}
Response:
package tpfinal;
import java.io.Serializable;
public class Respuesta implements Serializable{
private static final long serialVersionId = 1L;
int pedidos;
int leidos;
byte[] buffer = new byte[1024];
public int getPedidos() {
return pedidos;
}
public void setPedidos(int pedidos) {
this.pedidos = pedidos;
}
public int getLeidos() {
return leidos;
}
public void setLeidos(int leidos) {
this.leidos = leidos;
}
public byte[] getBuffer() {
return buffer;
}
public void setBuffer(byte[] buffer) {
this.buffer = buffer;
}
}
The code works fine, but I'm not able to find this problem. If anyone want to try, you can remove the System.setProperty so you won't need to create keystore and truststore. Client must be executed like: java Client localhost nameOfAPicture for example: pic.jpg.

Every time you call escribirArchivos() you are creating a new file, rather than appending to it. So the file is always the size of the last write to it.
Difficult to see the point of reading a file from the server and then copying it back twice.

Related

Sending a file line by line, in 2 seconds intervals, using ticker behaviours

My question is: How to send a line of a file to another agent every 2 seconds using ticker behaviours?
More specifically, in the first iteration, the agent sends the first line. In the second, the agent sends the second line etc.
My code below:
package pack1;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.TickerBehaviour;
import jade.lang.acl.ACLMessage;
import jade.wrapper.ControllerException;
public class Agent2 extends Agent {
private static final long serialVersionUID = 1L;
int nombre_ligne = 0;
BufferedReader lecteurAvecBuffer = null;
#Override
protected void setup() {
FileInputStream fis;
try {
fis = new FileInputStream("/home/hduser/Bureau/word.txt");
#SuppressWarnings("resource")
LineNumberReader l = new LineNumberReader(new BufferedReader(
new InputStreamReader(fis)));
while ((l.readLine()) != null) {
nombre_ligne = l.getLineNumber();
}
lecteurAvecBuffer = new BufferedReader(new FileReader(
"/home/hduser/Bureau/esclave1/abc.txt"));
int a = 1;
while (a <= ((int) nombre_ligne) / 3) {
a++;
String word = lecteurAvecBuffer.readLine();
addBehaviour(new TickerBehaviour(this, 2000) {
private static final long serialVersionUID = 1L;
#Override
protected void onTick() {
ACLMessage message = new ACLMessage(ACLMessage.INFORM);
message.addReceiver(new AID("agent1", AID.ISLOCALNAME));
message.setContent(word);
send(message);
}
});
a++;
}
lecteurAvecBuffer.close();
} catch (FileNotFoundException exc) {
System.out.println("Erreur d'ouverture");
} catch (IOException e) {
e.printStackTrace();
}
}
protected void takeDown() {
System.out.println("Destruction de l'agent");
}
#Override
protected void afterMove() {
try {
System.out.println(" La Destination : "
+ this.getContainerController().getContainerName());
} catch (ControllerException e) {
e.printStackTrace();
}
}
}
You don't say nothing about what is the problem with your code. I guess you get at least a compiler message about:
message.setContent(word);
As you access a local variable from an inner class, you must declare the variable as final in the context, like:
final String word = lecteurAvecBuffer.readLine();

SCTP : java.net.ConnectException: Connection refused

I'm trying to implement a SCTP connection, everything works fine from the server's side but when I run the client program I get the following error:
java.net.ConnectException: Connection refused
at sun.nio.ch.SctpNet.connect0(Native Method)
at sun.nio.ch.SctpNet.connect(SctpNet.java:73)
at sun.nio.ch.SctpChannelImpl.connect(SctpChannelImpl.java:372)
at sun.nio.ch.SctpChannelImpl.connect(SctpChannelImpl.java:438)
at com.sun.nio.sctp.SctpChannel.open(SctpChannel.java:221)
at com.eska.sctp.client.SCTPClient.<init>(SCTPClient.java:20)
at com.eska.sctp.client.SCTPClient.main(SCTPClient.java:62)
The Server Code:
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Iterator;
import com.sun.nio.sctp.AbstractNotificationHandler;
import com.sun.nio.sctp.AssociationChangeNotification;
import com.sun.nio.sctp.AssociationChangeNotification.AssocChangeEvent;
import com.sun.nio.sctp.HandlerResult;
import com.sun.nio.sctp.MessageInfo;
import com.sun.nio.sctp.SctpChannel;
import com.sun.nio.sctp.SctpServerChannel;
import com.sun.nio.sctp.ShutdownNotification;
public class SCTPServer {
private final static int SERVER_PORT = 1111;
private final static int BUFFER_SIZE = 1024;
private SctpServerChannel ssc;
public SCTPServer(int port) throws IOException {
this.ssc = SctpServerChannel.open();
// m.alkhader
// this.ssc.bind(new InetSocketAddress(port));
this.ssc.bind(new InetSocketAddress("127.0.0.1", port));
System.out.println("SCTP server started.");
System.out.println("Local addresses :");
Iterator iterator = this.ssc.getAllLocalAddresses().iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
public void launch() throws IOException {
ByteBuffer buf = ByteBuffer.allocate(BUFFER_SIZE);
CharBuffer cbuf = CharBuffer.allocate(BUFFER_SIZE);
Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
while (true) {
System.out.println("Waiting for client connection...");
SctpChannel sc = this.ssc.accept();
System.out.println("Client connected");
System.out.println("Remote adresses :");
Iterator iterator = sc.getRemoteAddresses().iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
AssociationHandler assocHandler = new AssociationHandler();
MessageInfo messageInfo = null;
do {
buf.clear();
cbuf.clear();
messageInfo = sc.receive(buf, null, assocHandler);
buf.flip();
messageInfo.unordered(true);
if (messageInfo != null && buf.limit() > 0) {
decoder.decode(buf, cbuf, true);
cbuf.flip();
System.out.print("Stream(" + messageInfo.streamNumber()
+ "):");
System.out.println(cbuf);
}
} while (messageInfo != null && buf.limit() > 0);
System.out.println("Connection closed by peer.");
}
}
public static void main(String[] args) {
try {
SCTPServer server = new SCTPServer(SERVER_PORT);
server.launch();
} catch (IOException e) {
System.out.println("Error : " + e.getMessage());
}
}
static class AssociationHandler extends AbstractNotificationHandler {
public HandlerResult handleNotification(
AssociationChangeNotification not, PrintStream stream) {
if (not.event().equals(AssocChangeEvent.COMM_UP)) {
int outbound = not.association().maxOutboundStreams();
int inbound = not.association().maxInboundStreams();
stream.printf("New association setup with %d outbound streams"
+ ", and %d inbound streams.\n", outbound, inbound);
}
return HandlerResult.CONTINUE;
}
public HandlerResult handleNotification(ShutdownNotification not,
PrintStream stream) {
stream.printf("The association has been shutdown.\n");
return HandlerResult.RETURN;
}
}
}
The Client Code:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Scanner;
import com.sun.nio.sctp.MessageInfo;
import com.sun.nio.sctp.SctpChannel;
public class SCTPClient {
private SctpChannel sc;
private final static int SERVER_PORT = 1111;
private final static int BUFFER_SIZE = 1024;
public SCTPClient(String addr, int port) throws IOException {
this.sc = SctpChannel.open(new InetSocketAddress(addr, port), 0, 0);
}
public void start() throws IOException {
MessageInfo messageInfo = MessageInfo.createOutgoing(null, 0);
Charset charset = Charset.forName("ISO-8859-1");
CharsetEncoder encoder = charset.newEncoder();
ByteBuffer buf = ByteBuffer.allocate(BUFFER_SIZE);
CharBuffer cbuf = CharBuffer.allocate(BUFFER_SIZE);
Scanner scan = new Scanner(System.in);
int i = 0;
int max = this.sc.association().maxInboundStreams();
// messageInfo.unordered(true);
while (scan.hasNext()) {
buf.clear();
cbuf.clear();
cbuf.put(scan.nextLine());
cbuf.flip();
encoder.encode(cbuf, buf, true);
buf.flip();
messageInfo.streamNumber(i % max);
this.sc.send(buf, messageInfo);
i++;
}
}
public void stop() throws IOException {
this.sc.close();
}
public static void main(String[] args) {
try {
System.out.println("Client");
SCTPClient client = new SCTPClient("127.0.0.1", SERVER_PORT);
// SCTPClient client = new SCTPClient("192.168.0.1", SERVER_PORT);
System.out.println("Hello Client");
client.start();
client.stop();
} catch (IOException e) {
System.out.println("Error : " + e.getMessage());
e.printStackTrace();
}
}
}
everything works fine from the server's side

Java (Raspberry pi) Thread

I am a student who is studying java.(Especially Raspberry pi) I have a question this multuthread. It can be compiled. But it doesn't work in my kit. If you don't mind guys, could you check my code and help me?
Thanks...
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.File;
import java.io.FileWriter;
public class RcvThread2 implements Runnable{
private static final int sizeBuf = 50;
private Socket clientSocket;
private Logger logger;
private SocketAddress clientAddress;
public RcvThread2(Socket clntSock, SocketAddress clientAddress, Logger logger) {
this.clientSocket = clntSock;
this.logger = logger;
this.clientAddress = clientAddress;
}
static class CloseExtends extends Thread {
static final String GPIO_OUT = "out";
static final String GPIO_ON = "1";
static final String GPIO_OFF = "0";
static final String[] GpioChannels = {"18"};
public static void main(String[] args) {
FileWriter[] commandChannels;
try {
FileWriter unexportFile = new FileWriter("sys/class/gpio/unexport");
FileWriter exportFile = new FileWriter("sys/class/gpio/gpio/export");
for(String gpioChannel : GpioChannels) {
System.out.println(gpioChannel);
File exportFileCheck =
new File("sys/class/gpio/gpio" +gpioChannel);
if(exportFileCheck.exists()) {
unexportFile.write(gpioChannel);
exportFile.flush();
}
exportFile.write(gpioChannel);
exportFile.flush();
FileWriter directionFile = new FileWriter("/sys/class/gpio/gpio" + gpioChannel + "/direction");
directionFile.write(GPIO_OUT);
directionFile.flush();
}
FileWriter commandChannel = new FileWriter("sys/class/gpio/gpio" + GpioChannels[0] + "/value");
int period = 20;
int repeatLoop = 25;
int counter;
while(true) {
for(counter = 0; counter < repeatLoop; counter++) {
commandChannel.write(GPIO_ON);
commandChannel.flush();
java.lang.Thread.sleep(2, 20000);
commandChannel.write(GPIO_OFF);
commandChannel.flush();
java.lang.Thread.sleep(period);
}
break;
}
} catch(Exception exception) {
exception.printStackTrace();
}
}
}
public void main(){
try {
InputStream ins = clientSocket.getInputStream();
OutputStream outs = clientSocket.getOutputStream();
int rcvBufSize;
byte[] rcvBuf = new byte[sizeBuf];
while ((rcvBufSize = ins.read(rcvBuf)) != -1) {
String rcvData = new String(rcvBuf, 0, rcvBufSize, "UTF-8");
if(rcvData.compareTo("MotorLock") == 0) {
CloseExtends te = new CloseExtends();
te.start();
}
if(rcvData.compareTo("MotorOpen") == 0) {
}
logger.info("Received data :" + rcvData + " (" + clientAddress + ")");
outs.write(rcvBuf, 0, rcvBufSize);
}
logger.info(clientSocket.getRemoteSocketAddress() + "Closed");
} catch (IOException ex) {
logger.log(Level.WARNING, "Exception in RcvThread", ex);
}finally {
try{
clientSocket.close();
System.out.println("Disconnected! Client IP :" + clientAddress);
} catch (IOException e) {}
}
}
}
The lower main method never gets called.
If you run your program it will execute the public static void main(String[] args) { method.
I think this is the method you want to run in the second thread?!
If you declare and run your new thread using
CloseExtends te = new CloseExtends();
te.start();
it will run the threads public void run() { method.
So if I understand your intention correctly you should change the name of the main method in the CloseExtends class to the threads run method and change the signature of the lower main method to the java programs main method public static void main(String[] args) {.
I would not name any other method "main" if it is not really a main method.
You can see an example of creating a new thread with the Runnable interface here: https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html

Different Result on DBPedia Spotlight by using the code and DBPedia Spotlight endpoint

This is the main class in which query is being fired
package extractKeyword;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.methods.GetMethod;
import org.dbpedia.spotlight.exceptions.AnnotationException;
import org.dbpedia.spotlight.model.DBpediaResource;
import org.dbpedia.spotlight.model.Text;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;
public class db extends AnnotationClient {
//private final static String API_URL = "http://jodaiber.dyndns.org:2222/";
private static String API_URL = "http://spotlight.dbpedia.org/";
private static double CONFIDENCE = 0.0;
private static int SUPPORT = 0;
// private static String powered_by ="non";
// private static String spotter ="CoOccurrenceBasedSelector";//"LingPipeSpotter"=Annotate all spots
//AtLeastOneNounSelector"=No verbs and adjs.
//"CoOccurrenceBasedSelector" =No 'common words'
//"NESpotter"=Only Per.,Org.,Loc.
//private static String disambiguator ="Default";//Default ;Occurrences=Occurrence-centric;Document=Document-centric
//private static String showScores ="yes";
#SuppressWarnings("static-access")
public void configiration(double CONFIDENCE,int SUPPORT)
//, String powered_by,String spotter,String disambiguator,String showScores)
{
this.CONFIDENCE=CONFIDENCE;
this.SUPPORT=SUPPORT;
// this.powered_by=powered_by;
//this.spotter=spotter;
//this.disambiguator=disambiguator;
//showScores=showScores;
}
public List<DBpediaResource> extract(Text text) throws AnnotationException {
// LOG.info("Querying API.");
String spotlightResponse;
try {
String Query=API_URL + "rest/annotate/?" +
"confidence=" + CONFIDENCE
+ "&support=" + SUPPORT
// + "&spotter=" + spotter
// + "&disambiguator=" + disambiguator
// + "&showScores=" + showScores
// + "&powered_by=" + powered_by
+ "&text=" + URLEncoder.encode(text.text(), "utf-8");
//LOG.info(Query);
GetMethod getMethod = new GetMethod(Query);
getMethod.addRequestHeader(new Header("Accept", "application/json"));
spotlightResponse = request(getMethod);
} catch (UnsupportedEncodingException e) {
throw new AnnotationException("Could not encode text.", e);
}
assert spotlightResponse != null;
JSONObject resultJSON = null;
JSONArray entities = null;
try {
resultJSON = new JSONObject(spotlightResponse);
entities = resultJSON.getJSONArray("Resources");
} catch (JSONException e) {
//throw new AnnotationException("Received invalid response from DBpedia Spotlight API.");
}
LinkedList<DBpediaResource> resources = new LinkedList<DBpediaResource>();
if(entities!=null)
for(int i = 0; i < entities.length(); i++) {
try {
JSONObject entity = entities.getJSONObject(i);
resources.add(
new DBpediaResource(entity.getString("#URI"),
Integer.parseInt(entity.getString("#support"))));
} catch (JSONException e) {
//((Object) LOG).error("JSON exception "+e);
}
}
return resources;
}
}
The extended class
package extractKeyword;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.dbpedia.spotlight.exceptions.AnnotationException;
import org.dbpedia.spotlight.model.DBpediaResource;
import org.dbpedia.spotlight.model.Text;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
import javax.ws.rs.HttpMethod;
/**
* #author pablomendes
*/
public abstract class AnnotationClient {
//public Logger LOG = Logger.getLogger(this.getClass());
private List<String> RES = new ArrayList<String>();
// Create an instance of HttpClient.
private static HttpClient client = new HttpClient();
public List<String> getResu(){
return RES;
}
public String request(GetMethod getMethod) throws AnnotationException {
String response = null;
// Provide custom retry handler is necessary
( getMethod).getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod((org.apache.commons.httpclient.HttpMethod) getMethod);
if (statusCode != HttpStatus.SC_OK) {
// LOG.error("Method failed: " + ((HttpMethodBase) method).getStatusLine());
}
// Read the response body.
byte[] responseBody = ((HttpMethodBase) getMethod).getResponseBody(); //TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
response = new String(responseBody);
} catch (HttpException e) {
// LOG.error("Fatal protocol violation: " + e.getMessage());
throw new AnnotationException("Protocol error executing HTTP request.",e);
} catch (IOException e) {
//((Object) LOG).error("Fatal transport error: " + e.getMessage());
//((Object) LOG).error(((HttpMethodBase) method).getQueryString());
throw new AnnotationException("Transport error executing HTTP request.",e);
} finally {
// Release the connection.
((HttpMethodBase) getMethod).releaseConnection();
}
return response;
}
protected static String readFileAsString(String filePath) throws java.io.IOException{
return readFileAsString(new File(filePath));
}
protected static String readFileAsString(File file) throws IOException {
byte[] buffer = new byte[(int) file.length()];
#SuppressWarnings("resource")
BufferedInputStream f = new BufferedInputStream(new FileInputStream(file));
f.read(buffer);
return new String(buffer);
}
static abstract class LineParser {
public abstract String parse(String s) throws ParseException;
static class ManualDatasetLineParser extends LineParser {
public String parse(String s) throws ParseException {
return s.trim();
}
}
static class OccTSVLineParser extends LineParser {
public String parse(String s) throws ParseException {
String result = s;
try {
result = s.trim().split("\t")[3];
} catch (ArrayIndexOutOfBoundsException e) {
throw new ParseException(e.getMessage(), 3);
}
return result;
}
}
}
public void saveExtractedEntitiesSet(String Question, LineParser parser, int restartFrom) throws Exception {
String text = Question;
int i=0;
//int correct =0 ; int error = 0;int sum = 0;
for (String snippet: text.split("\n")) {
String s = parser.parse(snippet);
if (s!= null && !s.equals("")) {
i++;
if (i<restartFrom) continue;
List<DBpediaResource> entities = new ArrayList<DBpediaResource>();
try {
entities = extract(new Text(snippet.replaceAll("\\s+"," ")));
System.out.println(entities.get(0).getFullUri());
} catch (AnnotationException e) {
// error++;
//LOG.error(e);
e.printStackTrace();
}
for (DBpediaResource e: entities) {
RES.add(e.uri());
}
}
}
}
public abstract List<DBpediaResource> extract(Text text) throws AnnotationException;
public void evaluate(String Question) throws Exception {
evaluateManual(Question,0);
}
public void evaluateManual(String Question, int restartFrom) throws Exception {
saveExtractedEntitiesSet(Question,new LineParser.ManualDatasetLineParser(), restartFrom);
}
}
The Main Class
package extractKeyword;
public class startAnnonation {
public static void main(String[] args) throws Exception {
String question = "What is the winning chances of BJP in New Delhi elections?";
db c = new db ();
c.configiration(0.25,0);
//, 0, "non", "AtLeastOneNounSelector", "Default", "yes");
c.evaluate(question);
System.out.println("resource : "+c.getResu());
}
}
The main problem is here when I am using DBPedia spotlight using spotlight jar (above code)then i am getting different result as compared to the dbpedia spotlight endpoint(dbpedia-spotlight.github.io/demo/)
Result using the above code:-
Text :-What is the winning chances of BJP in New Delhi elections?
Confidence level:-0.35
resource : [Election]
Result on DBPedia Spotlight endpoint(//dbpedia-spotlight.github.io/demo/)
Text:-What is the winning chances of BJP in New Delhi elections?
Confidence level:-0.35
resource : [Bharatiya_Janata_Party, New_Delhi, Election]
Why also the spotlight now don't have support as a parameter?

Sockets - SocketException: Socket Closed - Java

I've been playing around with sockets recently, but I've come across a problem...
I'm getting a "java.net.SocketException: socket closed" exception when I receive data from the server. I haven't closed the socket anywhere, in fact, the only place I use close() is on the scanner to read text from System.in;
Here is my code:
Client:
package packets.sidedcomputer;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import packets.MessagePacket;
import packets.sender.PacketSender;
import packets.side.Side;
public class Client extends SidedComputer
{
volatile boolean finished = false;
volatile String username;
volatile Server server;
public Socket clientSocket;
public ClientReciever reciever;
public Client(Server server, String username) throws UnknownHostException, IOException
{
this.username = username;
this.server = server;
this.reciever = new ClientReciever(this);
}
public void stopClient()
{
finished = true;
}
#Override
public void run()
{
Scanner scanner = new Scanner(System.in);
reciever.start();
while(!finished)
{
try
{
this.clientSocket = new Socket("192.168.1.25", 10501);
String line;
while((line = scanner.nextLine()) != null)
{
PacketSender sender = new PacketSender();
System.out.println("Client sending message \"" + line + "\" to server");
sender.sendPacket(new MessagePacket(line, username), clientSocket);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
scanner.close();
}
#Override
public Side getSide()
{
return Side.CLIENT;
}
}
Server:
package packets.sidedcomputer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import packets.Packet;
import packets.data.PacketData;
import packets.info.ClientInfo;
import packets.reciever.PacketReciever;
import packets.sender.PacketSender;
import packets.side.Side;
public class Server extends SidedComputer
{
volatile boolean finished = false;
public ServerSocket serverSocket;
public volatile List<ClientInfo> clients = new ArrayList<ClientInfo>();
public void stopServer()
{
finished = true;
}
public Server()
{
try
{
serverSocket = new ServerSocket(10501);
}
catch (IOException e)
{
e.printStackTrace();
}
}
#Override
public void run()
{
try
{
while (!finished)
{
Socket clientSocket = serverSocket.accept();
if(clientSocket != null)
{
ClientInfo clientInfo = new ClientInfo(clientSocket);
this.clients.add(clientInfo);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String dataString;
while((dataString = in.readLine()) != null)
{
PacketReciever packetReciever = new PacketReciever();
PacketData packetData = new PacketData();
packetData.decodeInto(dataString);
Packet packet = packetReciever.recievePacket(packetData, packetData.packetID, getSide(), clientSocket.getLocalAddress().getHostAddress().toString(), clientSocket.getLocalPort() + "");
PacketSender packetSender = new PacketSender();
for (ClientInfo client : this.clients)
{
PrintWriter out = new PrintWriter(client.socket.getOutputStream(), true);
packetSender.sendPacketToClient(packet, out);
}
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
#Override
public Side getSide()
{
return Side.SERVER;
}
}
Packet Sender:
package packets.sender;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import packets.Packet;
import packets.data.PacketData;
public class PacketSender implements IPacketSender
{
#Override
public void sendPacket(Packet packet, Socket socket)
{
if(packet.getDefualtID() == 0)
{
PacketData packetData = new PacketData(packet.getDefualtID());
packet.writeData(packetData);
String data = packetData.encodeIntoString();
sendData(socket, data);
}
}
protected void sendData(Socket socket, String data)
{
try
{
try
(
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
)
{
out.println(data);
}
catch (IOException e)
{
System.err.println("Couldn't get I/O for the connection to " + socket);
System.exit(1);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void sendPacketToClient(Packet packet, PrintWriter out)
{
PacketData packetData = new PacketData(packet.getDefualtID());
packet.writeData(packetData);
String data = packetData.encodeIntoString();
out.println(data);
}
}
Client Receiver:
package packets.sidedcomputer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import packets.data.PacketData;
import packets.reciever.PacketReciever;
import packets.side.Side;
public class ClientReciever extends Thread
{
public Client client;
public ClientReciever(Client client)
{
this.client = client;
}
volatile boolean running = true;
public void stopRunning()
{
running = false;
}
#Override
public void run()
{
while(running)
{
if(client.clientSocket != null)
{
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(client.clientSocket.getInputStream()));
String line;
while((line = in.readLine()) != null)
{
PacketReciever reciever = new PacketReciever();
PacketData packetData = new PacketData();
packetData.decodeInto(line);
reciever.recievePacket(packetData, packetData.packetID, Side.CLIENT, client.clientSocket.getLocalAddress().getHostAddress().toString(), client.clientSocket.getPort() + "");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
}
Packet Receiver:
package packets.reciever;
import packets.Packet;
import packets.MessagePacket;
import packets.data.PacketData;
import packets.side.Side;
public class PacketReciever implements IPacketReciever
{
#Override
public Packet recievePacket(PacketData packetData, int id, Side side, String hostName, String port)
{
Packet packet = null;
if(id == 0)
{
packet = new MessagePacket();
packet.readData(packetData);
packet.execute(side, hostName + ":" + port);
}
return packet;
}
}
I think the problem is your try-with-resources call in the sender, which will call close() at the end of the try block and hence close the Socket. Try using a single PrintWriter across all calls to sendData().

Categories