Missing characters in string java - java

I'm trying to implement a java server with http frames, I have a couple of URI's : /login.jsp and /logout.jsp that are found in the Request URi of the http format.
When I send the logout request to the Server I send it with a header like so:
Cookie: user_auth="SomeCookie".
Here is the code:
public HttpMessage nextMessage() {
if (!isAlive()) {
try {
throw new IOException("Tokenizer is Closed");
} catch (IOException e) {
e.printStackTrace();
}
}
// Return String
HttpMessage newMessage = null;
String output = null;
StringBuilder stringBuilder = new StringBuilder();
try {
int c;
while ((c = this.fInputStream.read()) != -1) {
if (c == this.fDelimiter)
break;
else
stringBuilder.append((char) c);
}
// Create an HttpMessage from the information received
output = stringBuilder.toString();
} catch (IOException e) {
this.fClosed = true;
try {
throw new IOException("Connection is Dead");
} catch (IOException e1) {
e1.printStackTrace();
}
}
newMessage = parseHttp(output);
return newMessage;
}
The parseHttp method breaks the type, and headers apart.
But the problem is after sending the login action to the server, if I try send the logout action the parsed information stored in the string builder has missing characters(more specifically the RequestType, RequestURI and the HttpVersion ) are missing and only the header can be found.
In addition if I try to print each characters I receive from the inputStream at the time I see all the characters that are supposed to be in the frame.

Are you sure you want the break; line and not a continue; break will cause the while loop to exit while using continue will simply skip the else and run the next iteration of the while loop.

Following code prints all the missing characters in a given string by removing duplicates.
import java.util.*;
public class MissChars
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
StringBuffer sb=new StringBuffer();
char c[]=str.toCharArray();
LinkedHashSet<Character> set=new LinkedHashSet<Character>();
for(int i=0;i<c.length;i++)
set.add(c[i]);
for(char cc:set)
sb.append(cc);
String sss=new String(sb);
char arr[]=sss.toCharArray();
for(char i='a';i<='z';i++)
{
for(int j=0;j<arr.length;j++)
{
if(i!=arr[j])
count++;
if(count==arr.length)
System.out.print(i);
}
count=0;
}
}
}

Related

Reading multiple lines from server

I'm open for other ways to do this, but this is my code:
public class Client {
public static void main (String [] args) {
try(Socket socket = new Socket("localhost", 7789)) {
BufferedReader incoming = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter outgoing = new PrintWriter(socket.getOutputStream(),true);
StringBuilder sb = new StringBuilder();
Scanner scanner = new Scanner(System.in);
String send = "";
String response = "";
while (!send.equals("logout")){
System.out.println("Enter Command: ");
send = scanner.nextLine();
outgoing.println(send);
while ((response = incoming.readLine()) != null) {
System.out.println(response);
sb.append(response);
sb.append('\n');
}
}
} catch (IOException e) {
System.out.println("Client Error: "+ e.getMessage());
}
}
}
I do get response from the server, but the program is getting stuck in the inner while loop while ((response = incoming.readLine()) != null), so i can't enter a second command. how do i break the loop if the incoming response is done ?
The problem is that incoming.readLine() will only return null if the socket is closed, otherwise it will block and wait for more input from the server.
If you can change the server, you could add some marking that the request was fully processed and then check it like this while ((response = incoming.readLine()) != "--finished--").
If you cannot, try this:
while(response.isEmpty()){
if(incoming.ready()){ //check if there is stuff to read
while ((response = incoming.readLine()) != null){
System.out.println(response);
sb.append(response);
sb.append('\n');
}
}
}

How I can to skip some area of text, when reading file?

I reading a .txt file and want to skip a listing of code in this text, when putting result in StringBuilder.
The example of text:
The following Bicycle class is one possible implementation of a
bicycle:
/* The example of Bicycle class class Bicycle {
int cadence = 0;
int speed = 0; } */
So that's what I could come to:
public class Main {
public static BufferedReader in;
public static StringBuilder stringBuilder = new StringBuilder();
public static void main(String[] args) {
String input = "input_text.txt";
try {
in = new BufferedReader(new FileReader(input));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String inputText;
try {
while ((inputText = in.readLine()) != null) {
if (inputText.startsWith("/*")) {
// The problem is there:
while (!inputText.endsWith("*/")) {
int lengthLine = inputText.length();
in.skip((long)lengthLine);
}
}
stringBuilder.append(inputText);
}
} catch (IOException e) {
e.printStackTrace();
}
I got the infinity while loop and can't jump to next line.
You never reset the value of inputText in your while loop, so it will never not end with */ resulting in an infinite loop. Also you don't need to use the skip() method as simply reading the lines until you encounter a */ will work. Try changing your loop to:
while (!inputText.endsWith("*/")) {
String temp = in.readLine();
if(temp == null) {break;}
inputText = temp;
}
Output: (With printing the StringBuilder)
The following Bicycle class is one possible implementation of a bicycle:

How to 'clean' InputStream without closing it?

Client code snippet. Basically it reads from standard input and sends message to the server.
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 1200)) {
OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.US_ASCII);
Scanner scanner = new Scanner(System.in);
for (String msg = scanner.nextLine(); !msg.equals("end"); msg = scanner.nextLine()) {
writer.write(msg + "\n");
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Server code snippet. Prints a message from stream.
public void run() {
try (InputStreamReader reader = new InputStreamReader(this.socket.getInputStream(), StandardCharsets
.US_ASCII)) {
StringBuilder builder = new StringBuilder();
for (int c = reader.read(); c != -1; c = reader.read()) {
builder.append((char) c);
if ((char) c == '\n')
System.out.print(builder);
}
} catch (IOException e) {
e.printStackTrace();
}
}
Input from client:
Text1
Text2
Server output:
Text1
Text1
Text2
The problem I am facing that server prints not just received message but also all messages before it.
Question: How can I reset 'clean' InputStream without closing it. And if that is impossible what is preferred solution?
You don't need to 'clean' the stream--you just need to reset the buffer after every line. Try something like the following using StringBuilder.setLength:
if (c == '\n') {
System.out.print(builder.toString());
builder.setLength(0);
}
On the other hand, I'd strongly encourage not manually reading lines like that. Consider using a Scanner like you do in the client code or alternatively a BufferedReader.
try (final BufferedReader reader
= new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.US_ASCII))) {
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
System.out.println(line);
}
} catch (final IOException ex) {
ex.printStackTrace();
}

Android InputStream. Read buffer until specific character

I'm handling a Bluetooth connection with Android and I'd like to read the InputStream buffer until I get some specific character like '\n' (new line) or any other character and leave the buffer as it is, then read the following bytes again until the same character is read in order to place them in separate strings. I tried several ways with no success, can anybody help me?
The code I'm using to get the data is the following
public String getData() {
try {
inStream = btSocket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
inStream.read(inString);
}
catch (IOException e){
e.printStackTrace();
}
String str= new String(inString, StandardCharsets.UTF_8);
return str;
}
If you want to read until you find a specific char,
one solution could be something like this:
public static String readUntilChar(InputStream stream, char target) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader buffer=new BufferedReader(new InputStreamReader(stream));
int r;
while ((r = buffer.read()) != -1) {
char c = (char) r;
if (c == target)
break;
sb.append(c);
}
System.out.println(sb.toString());
} catch(IOException e) {
// Error handling
}
return sb.toString();
}
Finally, I got a solution. I don't know if it's the most optimum, but it works fine. I post the code in case it's useful for someone else. Thanks for your responses.
Function to get the input stream char by char:
public char getData() {
try {
inStream = btSocket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
inStream.read(inString,0,1);
}
catch (IOException e){
e.printStackTrace();
}
String str= new String(inString, StandardCharsets.UTF_8);
inChar=str.charAt(0);
return inChar;
}
Function to get the desired strings when the character '&' appears:
public void procesChar(char inChar){
if(inChar=='&'){
String str=new String(charBuffer);
countBytes=0;
Arrays.fill(charBuffer,(char)-1);
}
else {
charBuffer[countBytes] = inChar;
countBytes++;
}
}

Converting file into hex dump

My output is reflecting the file that I am needing to process into hex values but my hex values are not being reflected in the output. Why isn't my file being converted into hex values?
public class HexUtilityDump {
public static void main(String[] args) {
FileReader myFileReader = null;
try {
myFileReader = new FileReader("src/hexUtility/test.txt");
} catch(Exception ex) {
System.out.println("Error opening file: " + ex.getLocalizedMessage());
}
BufferedReader b = null;
b = new BufferedReader(myFileReader);
//Loop through all the records in the file and print them on the console
while (true){
String myLine;
try {
myLine = b.readLine();
//check for null returned from readLine() and exit loop if so.
if (myLine ==null){break;}
System.out.println(myLine);
} catch (IOException e) {
e.printStackTrace();
//it is time to exit the while loop
break;
}
}
}
Here is the code to pull the file through the conversion
public static void convertToHex(PrintStream out, File myFileReader) throws IOException {
InputStream is = new FileInputStream(myFileReader);
int bytesCounter =0;
int value = 0;
StringBuilder sbHex = new StringBuilder();
StringBuilder sbText = new StringBuilder();
StringBuilder sbResult = new StringBuilder();
while ((value = is.read()) != -1) {
//convert to hex value with "X" formatter
sbHex.append(String.format("%02X ", value));
//If the character is not convertible, just print a dot symbol "."
if (!Character.isISOControl(value)) {
sbText.append((char)value);
} else {
sbText.append(".");
}
//if 16 bytes are read, reset the counter,
//clear the StringBuilder for formatting purpose only.
if(bytesCounter==15) {
sbResult.append(sbHex).append(" ").append(sbText).append("\n");
sbHex.setLength(0);
sbText.setLength(0);
bytesCounter=0;
}else{
bytesCounter++;
}
}
//if still got content
if(bytesCounter!=0){
//add spaces more formatting purpose only
for(; bytesCounter<16; bytesCounter++){
//1 character 3 spaces
sbHex.append(" ");
}
sbResult.append(sbHex).append(" ").append(sbText).append("\n");
}
out.print(sbResult);
is.close();
}
You never call convertToHex, remove the file reading from your main() method. It appears you wanted to do something like,
File f = new File("src/hexUtility/test.txt");
convertToHex(System.out, f);

Categories

Resources