Write Glassfish output into servlet html page - servlets

How to redirect Glassfish server output into HttpServletResponse.out? I am making servlet in NetBeans.

here is a working example, just expose this as a servlet
public class ReadLogs extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=UTF-8";
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
public void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.append("<html>\n<head>\n\n");
out.append("<script>function toBottom()" + "{"
+ "window.scrollTo(0, document.body.scrollHeight);" + "}");
out.append("\n</script>");
out.append("\n</head>\n<body onload=\"toBottom();\">\n<pre>\n");
try {
File file = new File("C:\\pathToServerLogFile");
BufferedReader in = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
while (in.ready()) {
String x = in.readLine();
sb.append(x).append("<br/>");
}
in.close();
out.append("\n</pre>\n</body>\n</html>");
out.close();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
UPDATE
If you need to print only the last portion of the file use this after line "in.close();"
//print only 1MB Oof data
if(sb.length()>1000000){
out.append(sb.substring(sb.length()-1000000, sb.length()));
}else{
out.append(sb.toString());
}

So.. to print only lines which appeared after invoking script I've made such code:
BufferedReader reader = new BufferedReader(new FileReader("/path/to/server/log/server.log"));
int lines = 0;
while (reader.readLine() != null) {
lines++;
}
reader.close();
BufferedReader reader2 = new BufferedReader(new FileReader("/path/to/server/log/server.log"));
String strLine;
int i = 0;
while (i != lines) {
reader2.readLine();
i++;
}
while ((strLine = reader2.readLine()) != null) {
out.println(stringToHTMLString(strLine));
out.println("<br>");
}
reader2.close();
When servlet starts it counts lines in server log (saves it in variable i), then after clicking on action form it read lines which indexes are higher than i and displays it on html page. I've used function stringToHTMLString which I found somewhere on stackoverflow.
Greets.

Related

Problem to execute https connection from a servlet: http 404 error occours

From my Tomcat's servlet I execute an https connection to an external servlet.
This is the code:
HttpsURLConnection hpcon = null;
try {
URL url = new URL(surl);
hpcon = (HttpsURLConnection) url.openConnection();
hpcon.setRequestMethod("POST");
hpcon.setDoInput(true);
hpcon.setDoOutput(true);
hpcon.setUseCaches(false);
hpcon.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
OutputStreamWriter wr = new OutputStreamWriter(hpcon.getOutputStream());
String params = "user=" + URLEncoder.encode(user, "UTF-8");
params += "&psswd=" + URLEncoder.encode(pssw, "UTF-8");
params += "&metodo=" + URLEncoder.encode(metodo, "UTF-8");
wr.write(params);
wr.flush();
wr.close();
hpcon.connect();
int respCode = hpcon.getResponseCode();
if (respCode == 200) {
BufferedReader br = new BufferedReader(new InputStreamReader(hpcon.getInputStream()));
String response = "";
String output;
while ((output = br.readLine()) != null) {
response += output;
}
if (response.indexOf("-") > 0) {
response = "-12";
System.out.println("ret = -12 - response = " + response);
}
br.close();
} else {
ret = "-11";
System.out.println("ret = -11 - respCode = " + respCode);
}
} catch (Exception e) {
e.printStackTrace();
ret = "-10";
System.out.println("ret = -10");
} finally {
if (hpcon != null) {
hpcon.disconnect();
}
}
Where surl is the full url of a servlet present in a different domain and the three parameters are read from a db table (the third really is fixed and is the operation that is make by the external servlet).
The result is:
ret = -11 - respCode = 404
Before make the connection I turn off the certificate's verify using the above code:
try {
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (Exception e) {
e.printStackTrace();
}
If I execute the same servlet manually from a browser with parameters in get mode all run correctly.
I tried to execute it on my code using the get mode and passing the three parameters in query string, but the result is the same.
How can I do to resolve the problem?

HttpServletResponse as an argument

I am pretty new to servlets and I would like to ask a kind of silly question.
I have a method that has an HttpServletResponse argument and I need to call this method from my main method to run the Java program.
The thing is I do not know what should I pass as value for this argument.
Let's say I have this class that comes from CrystalReports:
private static void exportIt(ReportClientDocument clientDoc, ExportOptions exportOptions, HttpServletResponse response, boolean attachment, String mimeType, String extension)
throws ReportSDKExceptionBase, IOException {
InputStream is = null;
try {
is = new BufferedInputStream(clientDoc.getPrintOutputController().export(exportOptions));
byte[] data = new byte[1024];
response.setContentType(mimeType);
if (attachment)
{
String name = clientDoc.getReportSource().getReportTitle();
if (name == null)
{
name = "CrystalReportViewer";
}
else
{
name = name.replaceAll("\"", "");
}
response.setHeader("Content-Disposition",
"attachment; filename=\"" + name + "."+extension+"\"");
}
OutputStream os = response.getOutputStream();
while (is.read(data) > -1) {
os.write(data);
}
} finally {
if (is != null) {
is.close();
}
}
}
When I try to call the exportIt method I need to pass something in the HTTPServletResponse but I do not know what is the exact value.
Thank you for your help,

i pass data in HttpURLConnection outputstream but HttpServletrequest inputstream is empty

Here is client code
public static void uploadFiles() {
try (DirectoryStream<Path> ds = Files.newDirectoryStream(Paths.get(Parameter.UPLOAD_FILES_DIR), "{*.dat}")) {
for (Path path : ds) {
System.out.println(path);
URL url = new URL(Parameter.UPLOAD_URL);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setConnectTimeout(1000 * 20);
conn.setReadTimeout(1000 * 20);
send(conn, path);
receive(conn);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void send(HttpURLConnection conn, Path path) throws Exception {
try (
BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());
BufferedInputStream in = new BufferedInputStream(new FileInputStream(path.toFile()))
) {
byte[] buffer = new byte[1024];
int c = 0;
while ((c = in.read(buffer)) != -1) {
out.write(buffer, 0, c);
}
out.flush();
}
}
public static void receive(HttpURLConnection conn) throws Exception {
try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
if (HttpURLConnection.HTTP_OK != conn.getResponseCode()) {
throw new Exception("Uploader response code: " + conn.getResponseCode());
}
}
}
Here is Servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Post request");
System.out.println(request.getContentLength());
try (BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
) {
String str;
while ((str = br.readLine()) != null) {
System.out.print(str);
}
} catch (Exception ex) {
ex.printStackTrace();
}
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(response.getOutputStream()))) {
bw.write("Close connection!!!");
}
}
When i run client code in server console out appears
Post refquest
-1
request.getContentLength() always return -1
Why i cant send bytes to the servlet? Here is contains of file which bytes i am trying to send
["192","2","3","4","5","6","7","8","9","US"] ["194","2","3","4","5","6","7","8","9","US"]
Resovled. Problem was in "/" symbol in the end of url. it was absent. But in this case servlet has responded.

Upload file from applet to servlet using apache fileupload

To accomplish:
Upload a file from my local to server using an applet and servlet using apache fileupload jar.
Tried:
I have used a simple jsp, with a browse button and posted the action to my servlet (where I used apache fileupload). I was successful in uploading the file to the server.
Issue:
I am trying to upload a file, from my local machine, using an applet. I do not want to manually select files, instead upload files that are present in a specific folder. For now I have hardcoded the folder. I am able to look at the folder and get the list of files I want to upload.
Also, I have successfully established a connection from my applet to servlet.
Issue arises at the upload.parseRequest(request) in the servlet. I'm thinking its because the applet cannot post to servlet's request object.
Also, I have set the request type to multipart/form-data in my applet.
Right now, I am trying to pass the absolute path of the file to servlet and upload.
I have seen other posts where byte stream data is passed from applet to servlet, but the servlet uses the traditional File.write.
For me, it is mandatory to achieve this using apache fileupload.
Please suggest on how to pass a file/file path from applet to servlet, where the upload is handled by apache fileupload.
Below are my FileUploadHandler (where the HTTP requests are handled) and FileUpload(which is my applet)
Below is my FileUpload Handler:
#WebServlet(name = "FileUploadHandler", urlPatterns = { "/upload" })
#MultipartConfig
public class FileUploadHandler extends HttpServlet {
String uploadFolder ="";
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost-servlet URL is: "
+ request.getRequestURL());
try {
uploadFolder = fileToUpload(request);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
uploadFolder = getServletContext().getRealPath("")+ File.separator;
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// process only if its multipart content
if (ServletFileUpload.isMultipartContent(request)) {
System.out.println("Yes, it is a multipart request...");
try {
List<FileItem> multiparts = upload.parseRequest(request);
System.out.println("Upload.parseRequest success !");
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
item.write(new File(uploadFolder + File.separator
+ name));
}
}
System.out.println("File uploaded to server !");
// File uploaded successfully
request.setAttribute("message", "File Uploaded Successfully");
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to "
+ ex);
}
} if(!ServletFileUpload.isMultipartContent(request)){
throw new ServletException("Content type is not multipart/form-data");
}
doGet(request, response);
//request.getRequestDispatcher("/result.jsp").forward(request, response);
OutputStream outputStream = response.getOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject("Success !");
objectOutputStream.flush();
objectOutputStream.close();
}
private String fileToUpload(HttpServletRequest request) throws IOException,
ClassNotFoundException {
ServletInputStream servletIn = request.getInputStream();
ObjectInputStream in = new ObjectInputStream(servletIn);
String uploadFile = (String) in.readObject();
System.out.println("Value in uploadFolder is: " + uploadFile);
return uploadFile;
}
Below is the fileupload applet:
public class FileUpload extends Applet {
private JButton capture;
private JTextField textField;
private final String pathDirectory = "C:\\";
private final String captureConfirmMessage = "Are you sure you want to continue?";
private final String confirmDialogTitle = "Confirm upload";
final File folder = new File(pathDirectory);
public void init() {
upload= new JButton("Upload");
textField = new JTextField();
capture.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int selection = JOptionPane.showConfirmDialog(upload,
uploadConfirmMessage, confirmDialogTitle,
JOptionPane.YES_NO_OPTION);
if (selection == JOptionPane.OK_OPTION) {
listFilesForFolder(folder);
} else if (selection == JOptionPane.CANCEL_OPTION) {
JOptionPane.showMessageDialog(upload,
"You have aborted upload", "Upload Cancelled", 2);
}
}
});
add(upload);
add(textField);
}
public void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
try {
onSendData(fileEntry.getAbsolutePath());
System.out.println(fileEntry.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private URLConnection getServletConnection() throws MalformedURLException,
IOException {
// Open the servlet connection
URL urlServlet = new URL("http://localhost:8081/UploadFile/upload");
HttpURLConnection servletConnection = (HttpURLConnection) urlServlet
.openConnection();
// Config
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
servletConnection.setUseCaches(false);
servletConnection.setDefaultUseCaches(false);
servletConnection.setRequestProperty("Content-Type", "multipart/form-data;");
servletConnection.connect();
return servletConnection;
}
private void onSendData(String fileEntry) {
try {
// Send data to the servlet
HttpURLConnection servletConnection = (HttpURLConnection) getServletConnection();
OutputStream outstream = servletConnection.getOutputStream();
ObjectOutputStream objectOutputStream= new ObjectOutputStream(
outstream);
objectOutputStream.writeObject(fileEntry);
// Receive result from servlet
InputStream inputStream = servletconnection.getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(
inputStream);
String result = (String) objectInputStream.readObject();
objectInputStream.close();
inputStream.close();
out.flush();
out.close();
// Display result on the applet
textField.setText(result);
} catch (java.net.MalformedURLException mue) {
mue.printStackTrace();
textField.setText("Invalid serlvetUrl, error: " + mue.getMessage());
} catch (java.io.IOException ioe) {
ioe.printStackTrace();
textField.setText("Couldn't open a URLConnection, error: "
+ ioe.getMessage());
} catch (Exception e) {
e.printStackTrace();
textField.setText("Exception caught, error: " + e.getMessage());
}
}
public void paint(Graphics g) {
g.drawString("Click the button above to capture", 5, 50);
}
I could finally succeed posting the request to the servlet from the applet.
It was a simple logic that I was missing. I did not add the header and trailer while posting to the servlet, which was the key, in the servlet to identify the incoming request as a multipart data.
FileInputStream fileInputStream = new FileInputStream(new File(
fileEntry));
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream
.writeBytes("Content-Disposition: form-data; name=\"upload\";"
+ " filename=\"" + fileEntry + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
System.out.println(fileEntry + " uploaded.");
}
// send multipart form data necesssary after file data
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
I added the header and trailer and also used this to create the URL connection.
private URLConnection getServletConnection() throws MalformedURLException,
IOException {
// Open the servlet connection
URL urlServlet = new URL("http://localhost:8083/UploadFile/upload");
HttpURLConnection servletConnection = (HttpURLConnection) urlServlet
.openConnection();
// Config
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
servletConnection.setUseCaches(false);
servletConnection.setDefaultUseCaches(false);
servletConnection.setRequestMethod("POST");
servletConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + this.boundary);
servletConnection.setRequestProperty("Connection", "Keep-Alive");
servletConnection.connect();
return servletConnection;
}
Then, in the servlet, I was just reading the data using upload.ParseRequest(request).
Thank you for the help.

How to create a web server? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I understand that there are already alot of web server out there.
But i feel like creating one for learning purpose.
Is it something i should try to figure out and any guides or tutorials on this?
In java:
Create a ServerSocket and have this continually listen for connections - when a connection request comes in handle it by by parsing the HTTP request header, get the resource indicated and add some header information before sending back to the client. eg.
public class Server implements Runnable {
protected volatile boolean keepProcessing = true;
protected ServerSocket serverSocket;
protected static final int DEFAULT_TIMEOUT = 100000;
protected ExecutorService executor = Executors.newCachedThreadPool();
public Server(int port) throws IOException {
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(DEFAULT_TIMEOUT);
}
#Override
public void run() {
while (keepProcessing) {
try {
Socket socket = serverSocket.accept();
System.out.println("client accepted");
executor.execute(new HttpRequest(socket));
} catch (Exception e) {
}
}
closeIgnoringException(serverSocket);
}
protected void closeIgnoringException(ServerSocket serverSocket) {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException ignore) {
}
}
}
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
try {
executor.execute(new WebServer(6789));
} catch (Exception e) {
e.printStackTrace();
}
}
}
final class HttpRequest implements Runnable {
final static String CRLF = "\r\n";
private Socket socket;
public HttpRequest(Socket socket) {
this.socket = socket;
}
public void run() {
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
}
}
private void processRequest() throws Exception {
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
String requestLine = br.readLine();
System.out.println();
System.out.println(requestLine);
List<String> tokens = Arrays.asList(requestLine.split(" "));
Iterator<String> it = tokens.iterator();
it.next(); // skip over the method, which should be "GET"
String fileName = it.next();
fileName = "." + fileName;
FileInputStream fis = null;
boolean fileExists = true;
try {
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
fileExists = false;
}
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
String contentType = null;
if (fileExists) {
statusLine = "HTTP/1.0 200 OK";
contentType = contentType(fileName);
contentTypeLine = "Content-type: " + contentType + CRLF;
} else {
statusLine = "HTTP/1.0 404 NOT FOUND";
contentType = "text/html";
contentTypeLine = "Content-type: " + contentType + CRLF;
entityBody = "<HTML>" + "<HEAD><TITLE>Not Found</TITLE></HEAD>"
+ "<BODY>" + statusLine + " Not Found</BODY></HTML>";
}
os.writeBytes(statusLine);
os.writeBytes(contentTypeLine);
os.writeBytes(CRLF);
if (fileExists) {
sendBytes(fis, os);
fis.close();
} else {
os.writeBytes(entityBody);
}
String headerLine = null;
while ((headerLine = br.readLine()).length() != 0) {
System.out.println(headerLine);
}
os.close();
br.close();
socket.close();
}
private static void sendBytes(InputStream fis, DataOutputStream os)
throws Exception {
byte[] buffer = new byte[1024];
int bytes = 0;
while ((bytes = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytes);
}
}
private static String contentType(String fileName) {
if (fileName.endsWith(".htm") || fileName.endsWith(".html")) {
return "text/html";
}
if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
return "image/jpeg";
}
if (fileName.endsWith(".gif")) {
return "image/gif";
}
if (fileName.endsWith(".txt")) {
return "text/plain";
}
if (fileName.endsWith(".pdf")) {
return "application/pdf";
}
return "application/octet-stream";
}
}
A Simple Webserver in C++ for Windows
Hope this helps you ; )
Alternatives
This project contains a modular web server in CodePlex
This article explains how to write a simple web server application using C# from CodeGuru
Start with understanding TCP/IP and the whole Internet protocol suite.
Then learn the HTTP 1.0 and 1.1 protocols.
That should start you on the way to understanding what you need to write in order to create a webserver from scratch.
Try asio from boost!
Boost.Asio is a cross-platform C++ library for network and low-level I/O programming that provides developers with a consistent asynchronous model using a modern C++ approach.
Most scripting language are capable and have plenty of examples on writing web servers. This route will give you a gentle introduction.

Resources