Multiple Exceptions Can't Be Thrown - java

I'm writing code for practicing setting up a server, but when I'm setting up the Input and Output streams, it says that I have to catch the IO Exception. However, I've already caught the exception. Here is the code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package server;
import java.io.*;
import java.net.*;
import java.util.Date;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.application.Platform;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
/**
*
*
*/
public class Server extends Application {
#Override
public void start(Stage primaryStage) {
TextArea ta = new TextArea();
Scene scene = new Scene(new ScrollPane(ta), 450, 200);
primaryStage.setTitle("Server");
primaryStage.setScene(scene);
primaryStage.show();
new Thread(() ->
{
try
{
ServerSocket serversocket = new ServerSocket(8000);
Platform.runLater(() -> {
ta.appendText("Server started at " + new Date() + '\n');
Socket socket = serversocket.accept();
DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
while(true)
{
double radius = inputFromClient.readDouble();
double area = Math.PI* radius * radius;
outputToClient.writeDouble(area);
Platform.runLater(() -> {
ta.appendText("Radius received from client: " + radius
+ '\n');
ta.appendText("Area is: " + area + '\n');
});
}
});
}
catch(IOException ex)
{
ex.printStackTrace();
}
}).start();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
The first time I call a method that could throw an exception, when setting up the server socket, there is no error detected on the IDE. However, the next time, when I try and set up the socket, and all subsequent times when an exception could happen, the IDE says that I need to catch the exception, even though I thought since it was all in a try/catch block, it was already caught. Thanks for any help.

Related

Errorwhen WriteObject from Server To Socket

Some one help me this this exception when send object from server to client
it is NotSerializableException <<
and i try to solve the error and implements the interface Serializable and same exception >> >>> >
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Haz
*/
public class Server {
boolean isRunning = true;
public static final int Port = 500;
public static final String Address = "127.0.0.1";
ObjectOutputStream outToClient;
Socket Client;
ArrayList<ConnectionHandler> Handlers;
HashSet<Socket> Callers;
public Server() throws IOException {
ServerSocket socketSer = new ServerSocket(500);
ExecutorService service = Executors.newFixedThreadPool(50);
Handlers = new ArrayList<>();
Callers = new HashSet<>();
while (isRunning) {
Client = socketSer.accept();
System.out.println("Client Connect on Sever");
ConnectionHandler handler = new ConnectionHandler(Client,socketSer);
Handlers.add(handler);
Callers.add(Client);
SendConnectToAll(Handlers);
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
new Server();
}
private void SendConnectToAll(ArrayList<ConnectionHandler> Handlers){
try {
outToClient = new ObjectOutputStream(Client.getOutputStream());
outToClient.writeObject(Handlers);
outToClient.flush();
outToClient.close();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.net.Socket;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Haz
*/
public class SocketClient {
Socket Client;
ObjectInputStream inputFromServer;
public SocketClient(String Address,int Port) {
try {
Client = new Socket(Address,Port);
} catch (IOException ex) {
Logger.getLogger(SocketClient.class.getName()).log(Level.SEVERE, null, ex);
}
new Thread(new Runnable(){
#Override
public void run() {
Object temp =null;
try {
inputFromServer = new ObjectInputStream(Client.getInputStream());
temp =inputFromServer.readObject();
while((temp)!=null){
temp = inputFromServer.readObject();
System.out.println(temp);
}
inputFromServer.close();
} catch (IOException ex) {
Logger.getLogger(SocketClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(SocketClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}).start();
}
}
and class ConnectionHandler it is empty but i implements
public class ConnectionHandler implements Runnable,Serializable {
private Socket Client;
private ServerSocket Server;
public ConnectionHandler(Socket Client, ServerSocket Server) {
this.Client = Client;
this.Server = Server;
}
ConnectionHandler is not serializable because it contains references to Socket and ServerSocket, which are not serializable. You would have to write your own serialization and deserialization methods to make it serializable.
However, it doesn't make sense to make it serializable anyway, since it doesn't have any serializable data in it to transmit over the network.

Java, using Scanner to fetch data line by line [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm basically running this code:
AddressBook.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package addressbook;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
/**
*
* #author hassan
*/
public class AddressBook extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("MainWindow.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setResizable(false);
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
new AddressBookMapper().parseDataFile();
}
}
AddressBookMapper.java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package addressbook;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
*
* #author hassan
*/
public class AddressBookMapper {
private File dataFile;
private FileWriter fileWriter;
private PrintWriter printWriter;
public ArrayList lines;
private void openDataFile() {
this.dataFile = new File("src/addressbook/datafile.txt");
}
public void writeData() {
System.out.println(this.lines);
Iterator iterator = this.lines.iterator();
System.out.println(this.lines.get(0));
while(iterator.hasNext()) {
System.out.println();
System.out.println("-----");
}
}
public void createAddress(String fullName, String email, String telephoneNumber, String mobileNumber) {
this.openDataFile();
try {
this.fileWriter = new FileWriter(this.dataFile, true);
this.printWriter = new PrintWriter(this.fileWriter);
this.printWriter.append(fullName + "," + email + "," + telephoneNumber + "," + mobileNumber + "\n");
this.printWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public int getLastId() {
return 0;
}
public void parseDataFile() {
File dataFile = new File("src/addressbook/datafile.txt");
try {
Scanner scanner = new Scanner(dataFile, "UTF-8").useDelimiter("\\n");
while(scanner.hasNext()) {
System.out.println(scanner.next());
}
} catch (IOException e) {
e.printStackTrace();
}
this.writeData();
}
private int findLastAddressId() {
return 0;
}
}
My data file text:
ff,ff,fff,ff
krfr,frffr,frfs,ff
a,a,b,c
d,a,f,e
fa,e,f,a
But, for some reason, I get this output:
ff,ff,fff,ff
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
krfr,frffr,frfs,ff
a,a,b,c
d,a,f,e
fa,e,f,a
null
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.NullPointerException
at addressbook.AddressBookMapper.writeData(AddressBookMapper.java:36)
at addressbook.AddressBookMapper.parseDataFile(AddressBookMapper.java:69)
at addressbook.AddressBook.main(AddressBook.java:36)
... 11 more
Exception running application addressbook.AddressBook
Java Result: 1
Any solution? I am basically trying to get the text from my data file line by line and stack it up into my ArrayList. Also, when writing my datafile adds a blank line in the end of the document.
Can you please try -
while(scanner.hasNext()) {
lines.add(scanner.next());
}

Sockets java - Beginner

I'm starting in java and have a problem with sockets, I wanted my server Meet and greet a value and then wanted to turn it into a String, to then include in a conditionif. However, despite the server approved the text without problem, I can not pass the value for a String.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javasockets;
import java.io.DataInputStream;
import java.io.IOException;
import static java.lang.System.exit;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
/**
*
* #author Nuno
*/
public class JavaSockets {
public static String T = "s";
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
try {
ServerSocket sckServer = new ServerSocket(5000);
System.out.println("Porta 5000 aberta!");
Socket sck;
while (true) {
sck = sckServer.accept();
try (Scanner entrada = new Scanner(sck.getInputStream())) {
while (entrada.hasNextLine()) {
System.out.println(entrada.nextLine());
}
String texto = entrada.nextLine();
System.out.println("ola" + texto);
String fnames = texto;
System.out.println("ola" + fnames);
System.out.println(texto);
if (texto.equals(T)) {
System.out.println("LOOL");
}
}
sckServer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Cliente code, send messages to the socket 127.0.0.1", 5000
package javasockets;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Nuno
*/
public class cliente {
public static void main(String[] args) throws IOException {
while (true) {
Socket cliente = new Socket("127.0.0.1", 5000);
System.out.println("O cliente se conectou ao servidor!");
Scanner teclado = new Scanner(System.in);
PrintStream saida = new PrintStream(cliente.getOutputStream());
while (teclado.hasNextLine()) {
saida.println(teclado.nextLine());
}
saida.flush();
saida.close();
teclado.close();
}
}
static Object getInetAddress() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
thanks for the help
Every call to nextLine () method, the server waits to receive a new string, but in the implementation of your client will only send a single string.
So try:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.DataInputStream;
import java.io.IOException;
import static java.lang.System.exit;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
/**
*
* #author Nuno
*/
public class JavaSockets {
public static String T = "s";
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
try {
ServerSocket sckServer = new ServerSocket(5000);
System.out.println("Porta 5000 aberta!");
Socket sck;
while (true) {
sck = sckServer.accept();
try (Scanner entrada = new Scanner(sck.getInputStream())) {
while (entrada.hasNextLine()) {
String texto = entrada.nextLine();
System.out.println(texto);
System.out.println("ola" + texto);
String fnames = texto;
System.out.println("ola" + fnames);
System.out.println(texto);
if (texto.equals(T)) {
System.out.println("LOOL");
}
}
}
sckServer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

How to create a simple Server Client Application Using RUDP in Java?

I was working on a simple application to transfer files between two machines using UDP, but that turned out to be lossy and unreliable, so while searching the Internet I found this project named Simple Reliable UDP here, but they don't have any documentation or any example code. So if there is any who can help me with this code I will be grateful because I'm newbie in Java. I started with writing simple server client app, but I got address already bind exception. To make clear I want to use UDP connections only that's why I'm trying to implement ReliableServerSocket and ReliableSocket.
package stackoverflow;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.rudp.ReliableServerSocket;
import net.rudp.ReliableSocket;
/**
*
* #author Nika
*/
public class udpServer implements Runnable{
ReliableServerSocket rss;
///ocket rs;
ReliableSocket rs;
public udpServer() throws IOException {
rss= new ReliableServerSocket(9876);
}
public void run(){
while (true){
try {
rs=(ReliableSocket)rss.accept();
System.out.println("Connection Accepted");
System.out.println(""+rs.getInetAddress());
BufferedReader inReader = new BufferedReader (new InputStreamReader (rs.getInputStream()));
//BufferedWriter outReader = new BufferedWriter (new OutputStreamWriter (rs.getOutputStream()));
String str= ""+inReader.readLine();
if(str.contains("UPLOAD")){
System.out.println("Client wants to upload file");
}else if(str.contains("D1")){
System.out.println("Client wants to download file");
}
} catch (IOException ex) {
Logger.getLogger(udpServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String args[]) throws Exception
{
System.out.println("UDP Server Executed");
Thread t= new Thread( new udpServer());
t.start();
}
}
Client Code here
package stackoverflow;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import net.rudp.ReliableSocket;
/**
*
* #author Nika
*/
public class UdpFileClient {
BufferedWriter outReader;
ReliableSocket server;
public UdpFileClient(boolean b1, boolean b2) throws IOException {
if (b1) {
server = new ReliableSocket("127.0.0.1", 9876);
outReader = new BufferedWriter(new OutputStreamWriter(server.getOutputStream()));
outReader.write("D1");
System.out.println("Download Req Sent From Client");
server.close();
outReader.flush();
outReader.close();
}
if (b2) {
server = new ReliableSocket("127.0.0.1", 9876);
outReader = new BufferedWriter(new OutputStreamWriter(server.getOutputStream()));
outReader.write("UPLOAD");
System.out.println("Upload Req Sent From Client");
server.close();
outReader.flush();
outReader.close();
}
}
public static void main(String args[]) throws Exception {
System.out.println("UDP CLient Executed");
new UdpFileClient(true, true);
}
}
I already know I can use TCP/IP, but it is kind of requirement for the project to use UDP. If any other way to send files in lossless way using UDP with good speed will also be helpful.
Thanks in advance!!
I tried RUDP and found that i was not printing my output, i know this is a silly mistake.
UDP Client
package UDPClient;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import net.rudp.ReliableSocket;
/**
*
* #author Nika
*/
public class UDPtestc {
ReliableSocket server;
public UDPtestc() throws IOException {
server = new ReliableSocket();
server.connect(new InetSocketAddress("127.0.0.1", 9876));
byte[] buffer = new byte[1024];
int count,progress=0;
InputStream in = server.getInputStream();
while((count=in.read(buffer)) >0){
progress+=count;
System.out.println(""+progress);
}
server.close();
}
public static void main(String[] args) throws IOException {
new UDPtestc();
}
}
UDPserver
package UDPServer;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.rudp.ReliableServerSocket;
import net.rudp.ReliableSocket;
/**
*
* #author Nika
*/
public class UDPtests implements Runnable {
ReliableServerSocket rss;
ReliableSocket rs;
String file;
FileInputStream bin;
public UDPtests() throws IOException {
rss = new ReliableServerSocket(9876);
Thread serverthread = new Thread(this);
serverthread.start();
}
public void run() {
while (true) {
try {
rs = (ReliableSocket)rss.accept();
System.out.println("Connection Accepted");
System.out.println("" + rs.getRemoteSocketAddress());
file = "";
Long size=0L;
file += "10MB.txt";
size+=10*1024*1024;
RandomAccessFile r1= new RandomAccessFile(file,"rw");
r1.setLength(size);
byte[] sendData = new byte[1024];
OutputStream os = rs.getOutputStream();
//FileOutputStream wr = new FileOutputStream(new File(file));
bin= new FileInputStream(file);
int bytesReceived = 0;
int progress = 0;
while ((bytesReceived = bin.read(sendData)) > 0) {
/* Write to the file */
os.write(sendData, 0, bytesReceived);
progress += bytesReceived;
System.out.println(""+progress);
}
} catch (IOException ex) {
Logger.getLogger(udpServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String[] args) throws IOException {
new UDPtests();
}
}
Soon i will post other tuts on RUDP if it will be possible.

How does HttpComponents send a response?

I'm trying to learn how to use Apache HttpComponents to send an HttpResponse. I found some examples on the Apache site but they are very confusing and unclear.
In the code below, I cannot see where the HttpResponse is generated and sent back to the client. After following along in the code, it seems that it must be happening in the HttpFileHandler class's handle() method, but it's not clear where. The class just ends with
...
response.setEntity(body);
System.out.println("File " + file.getPath() + " not found");
...
without actually sending the response. It ends with setting the Entity.
Where does the sending of the response back to the client actually happen in this code?
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.examples;
import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.Locale;
import org.apache.http.ConnectionClosedException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpServerConnection;
import org.apache.http.HttpStatus;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.entity.ContentProducer;
import org.apache.http.entity.EntityTemplate;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.DefaultHttpServerConnection;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerRegistry;
import org.apache.http.protocol.HttpService;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
import org.apache.http.util.EntityUtils;
/**
* Basic, yet fully functional and spec compliant, HTTP/1.1 file server.
* <p>
* Please note the purpose of this application is demonstrate the usage of
* HttpCore APIs. It is NOT intended to demonstrate the most efficient way of
* building an HTTP file server.
*
*
*/
public class ElementalHttpServer {
public static void main(String[] args) throws Exception {
args = new String[] { "e:/tutoring/236369/Tutorials/httpCoreExamples/" };
if (args.length < 1) {
System.err.println("Please specify document root directory");
System.exit(1);
}
Thread t = new RequestListenerThread(8080, args[0]);
t.setDaemon(false);
t.start();
}
static class HttpFileHandler implements HttpRequestHandler {
private final String docRoot;
public HttpFileHandler(final String docRoot) {
super();
this.docRoot = docRoot;
}
#Override
public void handle(final HttpRequest request,
final HttpResponse response, final HttpContext context)
throws HttpException, IOException {
String method = request.getRequestLine().getMethod()
.toUpperCase(Locale.ENGLISH);
if (!method.equals("GET") && !method.equals("HEAD")
&& !method.equals("POST")) {
throw new MethodNotSupportedException(method
+ " method not supported");
}
String target = request.getRequestLine().getUri();
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request)
.getEntity();
byte[] entityContent = EntityUtils.toByteArray(entity);
System.out.println("Incoming entity content (bytes): "
+ entityContent.length);
}
final File file = new File(this.docRoot, URLDecoder.decode(target));
if (!file.exists()) {
response.setStatusCode(HttpStatus.SC_NOT_FOUND);
EntityTemplate body = new EntityTemplate(new ContentProducer() {
#Override
public void writeTo(final OutputStream outstream)
throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(
outstream, "UTF-8");
writer.write("<html><body><h1>");
writer.write("File ");
writer.write(file.getPath());
writer.write(" not found");
writer.write("</h1></body></html>");
writer.flush();
}
});
body.setContentType("text/html; charset=UTF-8");
response.setEntity(body);
System.out.println("File " + file.getPath() + " not found");
} else if (!file.canRead() || file.isDirectory()) {
response.setStatusCode(HttpStatus.SC_FORBIDDEN);
EntityTemplate body = new EntityTemplate(new ContentProducer() {
#Override
public void writeTo(final OutputStream outstream)
throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(
outstream, "UTF-8");
writer.write("<html><body><h1>");
writer.write("Access denied");
writer.write("</h1></body></html>");
writer.flush();
}
});
body.setContentType("text/html; charset=UTF-8");
response.setEntity(body);
System.out.println("Cannot read file " + file.getPath());
} else {
response.setStatusCode(HttpStatus.SC_OK);
FileEntity body = new FileEntity(file, "text/html");
response.setEntity(body);
System.out.println("Serving file " + file.getPath());
}
}
}
static class RequestListenerThread extends Thread {
private final ServerSocket serversocket;
private final HttpParams params;
private final HttpService httpService;
public RequestListenerThread(int port, final String docroot)
throws IOException {
this.serversocket = new ServerSocket(port);
this.params = new SyncBasicHttpParams();
this.params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE,
8 * 1024)
.setBooleanParameter(
CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER,
"HttpComponents/1.1");
// Set up the HTTP protocol processor
HttpProcessor httpproc = new ImmutableHttpProcessor(
new HttpResponseInterceptor[] { new ResponseDate(),
new ResponseServer(), new ResponseContent(),
new ResponseConnControl() });
// Set up request handlers
HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("*", new HttpFileHandler(docroot));
// Set up the HTTP service
this.httpService = new HttpService(httpproc,
new DefaultConnectionReuseStrategy(),
new DefaultHttpResponseFactory(), reqistry, this.params);
}
#Override
public void run() {
System.out.println("Listening on port "
+ this.serversocket.getLocalPort());
while (!Thread.interrupted()) {
try {
// Set up HTTP connection
Socket socket = this.serversocket.accept();
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
System.out.println("Incoming connection from "
+ socket.getInetAddress());
conn.bind(socket, this.params);
// Start worker thread
Thread t = new WorkerThread(this.httpService, conn);
t.setDaemon(true);
t.start();
} catch (InterruptedIOException ex) {
break;
} catch (IOException e) {
System.err
.println("I/O error initialising connection thread: "
+ e.getMessage());
break;
}
}
}
}
static class WorkerThread extends Thread {
private final HttpService httpservice;
private final HttpServerConnection conn;
public WorkerThread(final HttpService httpservice,
final HttpServerConnection conn) {
super();
this.httpservice = httpservice;
this.conn = conn;
}
#Override
public void run() {
System.out.println("New connection thread");
HttpContext context = new BasicHttpContext(null);
try {
while (!Thread.interrupted() && this.conn.isOpen()) {
this.httpservice.handleRequest(this.conn, context);
}
} catch (ConnectionClosedException ex) {
System.err.println("Client closed connection");
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
} catch (HttpException ex) {
System.err.println("Unrecoverable HTTP protocol violation: "
+ ex.getMessage());
} finally {
try {
this.conn.shutdown();
} catch (IOException ignore) {
}
}
}
}
}
You are running a server here.
The generic code to "talk HTTP" is already implemented by the library.
You just have to plug in the "business logic" (in the form of an HTTPRequestHandler).
Your "business logic" gets an instance of HTTPResponse as a parameter. This object has already been created for you by the library. You can set parameters and write data to.
When your handler method returns (or even before that as you manipulate the response object), the library takes care of getting the data over the network.
Where does the sending of the response back to the client actually happen in this code?
As the result of method handle the response object now contains an Entity with your inner class that can write out a file. That code will be called to send the data.
It might be instructive (or possibly overwhelming) to put a breakpoint in your code and step through (including the part after handle returns) to see the control flow.

Categories

Resources