CLOB to String conversion + java 1.8 - java

The below program is always giving the exception
"java.sql.SQLRecoverableException: Closed Connection" in this line of " final Reader reader = clb.getCharacterStream();"
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.sql.Clob;
import java.sql.SQLException;
public class ClobStringConversion {
public static String clobStringConversion(Clob clb) throws IOException, SQLException
{
if (clb == null)
return "";
StringBuffer sb = new StringBuffer();
String strng;
try{
final Reader reader = clb.getCharacterStream();
final BufferedReader br = new BufferedReader(reader);
int b;
while(-1 != (b = br.read()))
{
sb.append((char)b);
}
br.close();
}
catch (SQLException e)
{
//log.error("SQL. Could not convert CLOB to string",e);
return e.toString();
}
catch (IOException e)
{
//log.error("IO. Could not convert CLOB to string",e);
return e.toString();
}
return sb.toString();
}
}

You are probably closing the connection before calling clobStringConversion(). Try closing the connection after reading the Clob.

Related

Trouble writing to OutputStream socket

I am writing a simple web server program for class that sends files to the web browser on request. I have written as much as I could. The difficulty is getting the data written to the OutputStream. I don't know what I am missing. I couldn't get the simple request to show up on the web browser.
I wrote it to the "name" OutputStream but when I reload the tab in the browser with the URL: "http://localhost:50505/path/file.txt" or any other like that "localhost:50505" it doesn't show up what I wrote to the OutputStream "name". It is supposed to show that.
package lab11;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketImpl;
import java.util.Scanner;
import java.io.OutputStream;
import java.io.PrintWriter;
public class main {
private static final int LISTENING_PORT = 50505;
public static void main(String[] args) {
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(LISTENING_PORT);
}
catch (Exception e) {
System.out.println("Failed to create listening socket.");
return;
}
System.out.println("Listening on port " + LISTENING_PORT);
try {
while (true) {
Socket connection = serverSocket.accept();
System.out.println("\nConnection from "
+ connection.getRemoteSocketAddress());
handleConnection(connection);
}
}
catch (Exception e) {
System.out.println("Server socket shut down unexpectedly!");
System.out.println("Error: " + e);
System.out.println("Exiting.");
}
}
public static void handleConnection(Socket sok) {
try {
// Scanner in = new Scanner(sok.getInputStream());
InputStream one = sok.getInputStream();
InputStreamReader isr = new InputStreamReader(one);
BufferedReader br = new BufferedReader(isr);
String rootDirectory = "/files";
String pathToFile;
// File file = new File(rootDirectory + pathToFile);
StringBuilder request = new StringBuilder();
String line;
line = br.readLine();
while (!line.isEmpty()) {
request.append(line + "\r\n");
line = br.readLine();
}
// System.out.print(request);
String[] splitline = request.toString().split("\n");
String get = null;
String file = null;
for (String i : splitline) {
if (i.contains("GET")) {
get = i;
String[] splitget = get.split(" ");
file = splitget[1];
}
}
}
OutputStream name = sok.getOutputStream();
Boolean doesexist = thefile.exists();
if (doesexist.equals(true)) {
PrintWriter response = new PrintWriter(System.out);
response.write("HTTP/1.1 200 OK\r\n");
response.write("Connection: close\r\n");
response.write("Content-Length: " + thefile.length() + "\r\n");
response.flush();
response.close();
sendFile(thefile, name);
} else {
System.out.print(thefile.exists() + "\n" + thefile.isDirectory() + "\n" + thefile.canRead());
}
}
catch (Exception e) {
System.out.println("Error while communicating with client: " + e);
}
finally { // make SURE connection is closed before returning!
try {
sok.close();
}
catch (Exception e) {
}
System.out.println("Connection closed.");
}
}
private static void sendFile(File file, OutputStream socketOut) throws
IOException {
InputStream in = new BufferedInputStream(new FileInputStream(file));
OutputStream out = new BufferedOutputStream(socketOut);
while (true) {
int x = in.read(); // read one byte from file
if (x < 0)
break; // end of file reached
out.write(x); // write the byte to the socket
}
out.flush();
}
}
So, I don't know what I really did wrong.
When I load the browser with localhost:50505 it just says can't connect or localhost refused to connect.
You are writing the HTTP response in System.out. You should write it in name, after the headers, in the body of the response. You probably want to describe it with a Content-Type header to make the receiver correctly show the file.

How to send data java and html

code JAVA
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class test{
public static void main (String[] args)throws Exception{
demoReadall();
}
public static void demoReadall(){
String dates;
String res;
String status;
try{
FileInputStream fstream = new FileInputStream("RunningSystem.log");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
String[] LineArray = strLine.split("\\|");
if("BATCH_PAYMENT".equals(LineArray[1])){
dates = LineArray[2];
res = LineArray[3];
status = LineArray[4];
System.out.println(dates);
System.out.println (res);
System.out.println (status);
}
}
fstream.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
How do you write the front-end code to retrieve information about this code? Please bother me.
I would like to know how to send java and html data, please advise writing and sending data.
Read about .jsp, servlets or Spring framework ;-)

Java: Multi line output via Socket

i got some struggle with my code. I have to send some commands via client to a server (create a file or list files in the directory) the server should create the files or send a list of existing files back to the client. It worked, but i guess the while loop for output on client side never stops and the client cant input new commands. I dont get the problem :(. Many thanks in advance.
Server:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.File;
import java.io.FileWriter;
public class MyServer {
private final static String DIRECTORYLISTING = "directoryListing";
private final static String ADDFILE = "addFile";
private static String path = "/home/christoph/eclipse-workspace/Distributed Systems Ex 01/Work_Folder";
private static PrintWriter pw = null;
private static File file = null;
private static String command1 = null; // Command
private static String command2 = null; // File name
private static String command3 = null; // File content
private static ArrayList<File> files = new ArrayList<>(); //
public static void splitClientInput(String clientInput) {
try {
String [] splittedInput = clientInput.split(";");
command1=splittedInput[0];
command2=splittedInput[1];
command3=splittedInput[2];
} catch(ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
}
public static void directoryListing() {
try {
File[] s = file.listFiles();
for(int i = 0; i<s.length;i++) {
pw.println(s[i].getName());
}
pw.flush();
}catch(NullPointerException e) {
e.printStackTrace();
}
}
public static void addFile(String command2,String command3) throws IOException {
file = new File(path +"/" +command2);
if(file.isFile()) {
pw.println("This Filename "+command2+" already exists.");
} else {
try {
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(command3);
files.add(file);
pw.println(file.getName()+" created");
if(command3.equals(null)) {
pw.println("Your created file is empty");
}
fileWriter.close();
}catch(IOException e) {
pw.println("Error by creating file");
}catch (NullPointerException e) {
pw.println("Your created file is empty");
}
}
}
public static void checkInputCommand(String command1, String command2, String command3) throws IOException {
switch(command1) {
case DIRECTORYLISTING:
directoryListing();
break;
case ADDFILE:
addFile(command2, command3);
break;
}
}
public static void main(String[] args) {
try {
file = new File(path);
files = new ArrayList<File>(Arrays.asList(file.listFiles()));
ServerSocket ss = new ServerSocket(1118);
System.out.println("Server Started...");
Socket socket = ss.accept();
OutputStream os = socket.getOutputStream();
pw=new PrintWriter(os);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String clientInput = null;
while((clientInput = br.readLine()) != null) {
splitClientInput(clientInput);
checkInputCommand(command1, command2, command3);
pw.flush();
}
pw.flush();
br.close();
isr.close();
is.close();
pw.close();
os.close();
socket.close();
ss.close();
System.out.println("Server closed");
}catch(BindException e) {
e.printStackTrace();
}catch(SocketException e) {
e.printStackTrace();
}catch(java.lang.NullPointerException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}
Client:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class MyClient {
public static void main(String[] args) throws Exception{
try {
Scanner sc = new Scanner(System.in);
Socket s = new Socket("127.0.0.1", 1118);
System.out.println("Client started");
InputStream is = s.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os);
String str= null;
while(true){
System.out.print("Client input: ");
pw.println(sc.nextLine());
pw.flush();
// System.out.println(br.readLine());
/*
* dont get out of the loop?
*/
while((str=br.readLine())!=null) {
System.out.println(str);
}
br.close();
isr.close();
is.close();
s.close();
}
} catch(NullPointerException e) {
e.printStackTrace();
} catch(ConnectException e) {
e.printStackTrace();
}catch(UnknownHostException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}

Exception in readObject of String

I'm trying to read a text file from the server string by string (line by line from the file).
It works good until readObject in the client side has nothing to read and than I get exception and going to "client error".
I have tried to close streams and sockets, ask questions and also I have tried to use scanner but none of the options above helped me.
Can u help me?
client side:
package hit.model;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class MMUClient {
private ArrayList<String> userDetails;
private String fileFromServer =null;
private ObjectOutputStream outToServer;
private ObjectInputStream inFromServer;
private String fileName;
private boolean ERROR = true;
private String messageError = "No Errors";
private PrintWriter printerWriter;
public MMUClient(ArrayList<String> userParameters){
userDetails = userParameters;
};
public MMUClient(String filePath){
fileName = filePath;
};
public ArrayList<String> getUserDetails() {
return userDetails;
}
public void setUserDetails(ArrayList<String> userDetails) {
this.userDetails = userDetails;
clientAuthenticate();
}
public void clientAuthenticate(){
try{
Socket myServer = null;
try {
//1. creating a socket to connect to the server
myServer = new Socket("localhost", 12345);
System.out.println("Connected to localhost in port 12345");
//2. get Input and Output streams
outToServer = new ObjectOutputStream(myServer.getOutputStream());
inFromServer=new ObjectInputStream(myServer.getInputStream());
//3: Communicating with the server
outToServer.writeObject(userDetails);
//4. get server answer
fileFromServer = (String) inFromServer.readObject();
printerWriter = new PrintWriter("logClient.txt");
if(fileFromServer.contains("Error")){
messageError = "Error";
ERROR = true;
}
else{
if (fileFromServer.contains("Wrong")){
messageError = "Wrong";
ERROR = true;
}
else
while(fileFromServer != null){
// messageError = "No Errors";
// ERROR = false;
System.out.println(fileFromServer);
printerWriter.println(fileFromServer);
// writeData(fileFromServer);
fileFromServer = (String) inFromServer.readObject();
}
printerWriter.close();
}
} catch (IOException e) {
System.out.println("Client error");
}finally{
inFromServer.close();
outToServer.close();
myServer.close();
}
}catch (Exception e) {
System.out.println("Client error Details");
}
}
//**********************write into text file from server***************************
/* private void writeData(String lineToWrite) {
FileWriter fileWriter = null;
String filetowrite = "logClient.txt";
try {
PrintWriter printerWriter = new PrintWriter(filetowrite);
printerWriter.println(lineToWrite);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
*/
//************************if there is any error with the client******************************
public boolean getError(){
return ERROR;
}
public String getMessageError() {
return messageError;
}
public void setMessageError(String messageError) {
this.messageError = messageError;
}
}
server side:
package hit.applicationservice;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import hit.login.AuthenticationManager;
public class MMULogFileApplicationService implements Runnable {
//MMULogService logService;
AuthenticationManager authenticateDetails;
MMULogFileBrowsing browsing;
ArrayList<String> userDetails;
private Socket someClient = null;
private ObjectOutputStream outToClient;
private ObjectInputStream inFromClient;
String filePath = "/Users/oferg/Desktop/lastVirsion/MMUProject/log.txt";
public MMULogFileApplicationService (Socket socket ){
someClient = socket;
};
#Override
public void run() {
//3. get Input and Output streams
try{
outToClient = new ObjectOutputStream(someClient.getOutputStream());
inFromClient = new ObjectInputStream(someClient.getInputStream());
userDetails = (ArrayList<String>) inFromClient.readObject();
System.out.println("Connection successful ");
}catch(IOException | ClassNotFoundException ioException){
ioException.printStackTrace();
}
boolean userFound = false;
try {
authenticateDetails = new AuthenticationManager();
userFound = authenticateDetails.authenticate(userDetails.get(0), userDetails.get(1));
if(userFound)
{
browsing = new MMULogFileBrowsing(someClient, userDetails.get(2), filePath);
if(!browsing.searchIfFileExist()){
//write object to Socket
String sendMessage = "Wrong FileName the file isn't found";
outToClient.writeObject(sendMessage);
}
else{
getFileToClient();
}
}
else
{
//write object to Socket
String sendMessage = "Error - the user isn't exist";
outToClient.writeObject(sendMessage);
}
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
inFromClient.close();
outToClient.close();
someClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void getFileToClient() throws IOException {
FileReader fileReader = null;
String currentLine = null;
try {
fileReader = new FileReader(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((currentLine = bufferedReader.readLine())!= null){
if (currentLine.isEmpty() == false ){
outToClient.writeObject(currentLine);
outToClient.flush();
}
}
outToClient.close();
bufferedReader.close();
fileReader.close();
}
}
tnx everybody for their answers.
i think i found the way to pass al the text file by the next simple loop code:
String currentLine = "";
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((tempLine = bufferedReader.readLine())!= null){
if (tempLine.isEmpty() == false ){
currentLine = currentLine+tempLine+"\n";
}
}
in that way i'm copying the text file line by line and send it to the client by 1 string and than i can do whatever i want.
tnx every1.
peace

Call static String onCreate from other Class

How can I call "getContent" inside "onCreate"?
I am getting errors like
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity: android.os.NetworkOnMainThreadException
Caused by: android.os.NetworkOnMainThreadException
main.java
protected void onCreate(Bundle savedInstanceState) {
Log.d("URL", HttpUtils.getContents("http://google.com"));
}
HttpUtils.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class HttpUtils {
public static String getContents(String url) {
String contents ="";
try {
URLConnection conn = new URL(url).openConnection();
InputStream in = conn.getInputStream();
contents = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.v("MALFORMED URL EXCEPTION");
} catch (IOException e) {
Log.e(e.getMessage(), e);
}
return contents;
}
private static String convertStreamToString(InputStream is) throws UnsupportedEncodingException {
BufferedReader reader = new BufferedReader(new
InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
In android you cann't perform any networking task on UI thread. so you will have perform Networking task on a Different thread. For this you can use normal java Threads but this is not a good approach in android. you should use Async Task.
You can follow any good tutorial on google.

Categories

Resources