Scanner returns null instead throwing an exception - java

I have trouble with networking in java. I have tried to read a message from a client over sockets. I use BufferedReader for reading the message.
public String read() throws IOException {
String message = reader.readLine();
return message;
}
When I am on reader.readline() method on the server, if the client kills the connection I expect an error actually. However, instead of throwing an exception, it returns NULL.

#Eray Tuncer
it depends on when the connection was closed if it is before start reading the line then yes you should expect an exception. but if it is in between reading I think you will get "null" indicating end of the stream. Please check the following implementation of readLine from BufferedReader :
String readLine(boolean ignoreLF) throws IOException {
StringBuffer s = null;
int startChar;
synchronized (lock) {
ensureOpen(); //This method ensures that the stream is open and this is called before start reading
..................
................
//----Now reading operation started if the connection is closed it will just return a null---------
bufferLoop:
for (;;) {
if (nextChar >= nChars)
fill();
if (nextChar >= nChars) { /* EOF */
if (s != null && s.length() > 0)
return s.toString();
else
return null;
}
boolean eol = false;
char c = 0;
int i;
/* Skip a leftover '\n', if necessary */
if (omitLF && (cb[nextChar] == '\n'))
nextChar++;
skipLF = false;
omitLF = false;
charLoop:
for (i = nextChar; i < nChars; i++) {
c = cb[i];
if ((c == '\n') || (c == '\r')) {
eol = true;
break charLoop;
}
}
startChar = nextChar;
nextChar = i;
if (eol) {
String str;
if (s == null) {
str = new String(cb, startChar, i - startChar);
} else {
s.append(cb, startChar, i - startChar);
str = s.toString();
}
nextChar++;
if (c == '\r') {
skipLF = true;
}
return str;
}
if (s == null)
s = new StringBuffer(defaultExpectedLineLength);
s.append(cb, startChar, i - startChar);
}
}
}
So bottom line is that you should check for null in this operation rather than relying on an IOException. I hope it will help you to fix your problem. Thank you !

You can trigger an exception manually like this:
public String read() throws IOException {
String message = reader.readLine();
if (message == null)
throw new IOException("reader.readLine() returned null");
return message;
}

Related

Java AWS Serverless Lambda [duplicate]

I am using Jackson version 2.4.3 for converting my complex Java object into a String object, so below is what I'm getting in output. The output is like below (Fyi - I just printed some part of the output)
"{\"FirstName\":\"John \",\"LastName\":cena,\"salary\":7500,\"skills\":[\"java\",\"python\"]}";
Here is my code (PaymentTnx is a complex Java object)
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
String lpTransactionJSON = mapper.writeValueAsString(paymentTxn);
I don't want to see \ slashes in my JSON string. What do I need to do to get a string like below:
"{"FirstName":"John ","LastName":cena,"salary":7500,"skills":["java","python"]}";
String test = "{\"FirstName\":\"John \",\"LastName\":cena,\"salary\":7500,\"skills\":[\"java\",\"python\"]}";
System.out.println(StringEscapeUtils.unescapeJava(test));
This might help you.
I have not tried Jackson. I just have similar situation.
I used org.apache.commons.text.StringEscapeUtils.unescapeJson but it's not working for malformed JSON format like {\"name\": \"john\"}
So, I used this class. Perfectly working fine.
https://gist.githubusercontent.com/jjfiv/2ac5c081e088779f49aa/raw/8bda15d27c73047621a94359492a5a9433f497b2/JSONUtil.java
// BSD License (http://lemurproject.org/galago-license)
package org.lemurproject.galago.utility.json;
public class JSONUtil {
public static String escape(String input) {
StringBuilder output = new StringBuilder();
for(int i=0; i<input.length(); i++) {
char ch = input.charAt(i);
int chx = (int) ch;
// let's not put any nulls in our strings
assert(chx != 0);
if(ch == '\n') {
output.append("\\n");
} else if(ch == '\t') {
output.append("\\t");
} else if(ch == '\r') {
output.append("\\r");
} else if(ch == '\\') {
output.append("\\\\");
} else if(ch == '"') {
output.append("\\\"");
} else if(ch == '\b') {
output.append("\\b");
} else if(ch == '\f') {
output.append("\\f");
} else if(chx >= 0x10000) {
assert false : "Java stores as u16, so it should never give us a character that's bigger than 2 bytes. It literally can't.";
} else if(chx > 127) {
output.append(String.format("\\u%04x", chx));
} else {
output.append(ch);
}
}
return output.toString();
}
public static String unescape(String input) {
StringBuilder builder = new StringBuilder();
int i = 0;
while (i < input.length()) {
char delimiter = input.charAt(i); i++; // consume letter or backslash
if(delimiter == '\\' && i < input.length()) {
// consume first after backslash
char ch = input.charAt(i); i++;
if(ch == '\\' || ch == '/' || ch == '"' || ch == '\'') {
builder.append(ch);
}
else if(ch == 'n') builder.append('\n');
else if(ch == 'r') builder.append('\r');
else if(ch == 't') builder.append('\t');
else if(ch == 'b') builder.append('\b');
else if(ch == 'f') builder.append('\f');
else if(ch == 'u') {
StringBuilder hex = new StringBuilder();
// expect 4 digits
if (i+4 > input.length()) {
throw new RuntimeException("Not enough unicode digits! ");
}
for (char x : input.substring(i, i + 4).toCharArray()) {
if(!Character.isLetterOrDigit(x)) {
throw new RuntimeException("Bad character in unicode escape.");
}
hex.append(Character.toLowerCase(x));
}
i+=4; // consume those four digits.
int code = Integer.parseInt(hex.toString(), 16);
builder.append((char) code);
} else {
throw new RuntimeException("Illegal escape sequence: \\"+ch);
}
} else { // it's not a backslash, or it's the last character.
builder.append(delimiter);
}
}
return builder.toString();
}
}
With Jackson do:
toString(paymentTxn);
with
public String toString(Object obj) {
try (StringWriter w = new StringWriter();) {
new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true).writeValue(w, obj);
return w.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
This here is not valid JSON:
"{"FirstName":"John ","LastName":cena,"salary":7500,"skills":["java","python"]}";
This here is valid JSON, specifically a single string value:
"{\"FirstName\":\"John \",\"LastName\":cena,\"salary\":7500,\"skills\":[\"java\",\"python\"]}";
Given that you're calling writeValueAsString, this is the correct behaviour. I would suggest writeValue, perhaps?

check if char[] contains only one letter and one int

I have no idea how to check if char[] contains only one letter (a or b) on the first position and only one int (0-8) on the second position. for example a2, b2
I have some this, but I do not know, what should be instead of digital +=1;
private boolean isStringValidFormat(String s) {
boolean ret = false;
if (s == null) return false;
int digitCounter = 0;
char first = s.charAt(0);
char second = s.charAt(1);
if (first == 'a' || first == 'b') {
if (second >= 0 && second <= '8') {
digitCounter +=1;
}
}
ret = digitCounter == 2; //only two position
return ret;
}
` public char[] readFormat() {
char[] ret = null;
while (ret == null) {
String s = this.readString();
if (isStringValidFormat(s)) {
ret = s.toCharArray();
}else {
System.out.println("Incorrect. Values must be between 'a0 - a8' and 'b0 - b8'");
}
}
return new char[0];
}`
First, I would test for null and that there are two characters in the String. Then you can use a simple boolean check to test if first is a or b and the second is between 0 and 8 inclusive. Like,
private boolean isStringValidFormat(String s) {
if (s == null || s.length() != 2) {
return false;
}
char first = s.charAt(0);
char second = s.charAt(1);
return (first == 'a' || first == 'b') && (second >= '0' && second <= '8');
}
For a well understood pattern, use Regex:
private static final Pattern pattern = Pattern.compile("^[ab][0-8]$")
public boolean isStringValidFormat(String input) {
if (input != null) {
return pattern.matcher(input).matches();
}
return false;
}

Java Stack Evaluation from TXT file

In this assignment, I need to read a .txt file and determine if the expressions are correct or "Balanced". The first problem I got correct but for the second problem I am getting more output than I want. Here is the problem for #2:
Write a stack-based algorithm that evaluates a post-fixed expression. Your program needs to read its input from a file called “problem2.txt”. This file contains one expression per line.
For each expression output its value to the standard output. If an expression is ill-formed print “Ill-formed”.
The Problem2.txt is as follows:
3 2 + 5 6 8 2 / + + * 1 +
8 * 2 3 + + - 9 1 +
1 4 + 9 4 - * 2 *
// For my output I need to get:
76
Ill-formed
50
// With my code I am getting:
76
Ill-formatted
Ill-formatted
Ill-formatted
10
50
// and I’m not sure why I’m getting extra ill-formatted and a 10 in there
Below is my code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Stack;
import java.util.EmptyStackException;
public class Eval {
public static void main(String args[]) throws IOException {
//driver
try (BufferedReader filereader = new BufferedReader(new FileReader("Problem1.txt"))) {
while (true) {
String line = filereader.readLine();
if (line == null) {
break;
}
System.out.println(balancedP(line));
}
}
System.out.println("\n");
try (BufferedReader filereader2 = new BufferedReader(new FileReader("Problem2.txt"))) {
while (true) {
String line = filereader2.readLine();
if (line == null) {
break;
}
System.out.println(evaluatePostfix(line));
}
}
}
public static boolean balancedP (String s) {
Stack<Character> stackEval = new Stack<Character>();
for(int i = 0; i < s.length(); i++) {
char token = s.charAt(i);
if(token == '[' || token == '(' || token == '{' ) {
stackEval.push(token);
} else if(token == ']') {
if(stackEval.isEmpty() || stackEval.pop() != '[') {
return false;
}
} else if(token == ')') {
if(stackEval.isEmpty() || stackEval.pop() != '(') {
return false;
}
} else if(token == '}') {
if(stackEval.isEmpty() || stackEval.pop() != '{') {
return false;
}
}
}
return stackEval.isEmpty();
}
//problem 2 algo to evaluate a post-fixed expression
static int evaluatePostfix(String exp) throws EmptyStackException
{
Stack<Integer> stackEval2 = new Stack<>();
for(int i = 0; i < exp.length(); i++)
{
char c = exp.charAt(i);
if(c == ' ')
continue;
else if(Character.isDigit(c)) {
int n = 0;
while(Character.isDigit(c)) {
n = n*10 + (int)(c-'0');
i++;
c = exp.charAt(i);
}
i--;
stackEval2.push(n);
}
else {
try {
//if operand pops two values to do the calculation through the switch statement
int val1 = stackEval2.pop();
int val2 = stackEval2.pop();
//operands in a switch to test and do the operator's function each value grabbed and tested
switch(c) {
case '+':
stackEval2.push(val2 + val1);
break;
case '-':
stackEval2.push(val2 - val1);
break;
case '/':
stackEval2.push(val2 / val1);
break;
case '*':
stackEval2.push(val2 * val1);
break;
}
} catch (EmptyStackException e) {
System.out.println("Ill-formatted");
}
}
}
return stackEval2.pop();
}
}
A simple way to have the output formatted how you want is to just put the try-catch block around where you are calling the evaluatePostfix() method (make sure to delete the try-catch block that is inside the evaluatePostfix() method):
System.out.println("\n");
try (BufferedReader filereader2 = new BufferedReader(new FileReader("Problem2.txt"))) {
while (true) {
String line = filereader2.readLine();
if (line == null) {
break;
}
try {
System.out.println(evaluatePostfix(line));
} catch (EmptyStackException e) {
System.out.println("Ill-formatted");
}
}
}
This way, when an exception occurs inside the evaluatePostfix() method, the method will throw the exception and the exception will be dealt with outside of the looping, thus, avoiding duplicate error messages and other unwanted effects.

Creating a Lexer that implements Iterator<Lexeme>

I'm new to programming and I have an assignment that asks us to make a Lexer that implements Iterator (in java). We are given Strings of equations with variable white spaces and we have to produce Lexemes for a variety of types. This is what I have so far but when I run it, I get an OutOfMemoryError: Java heap space. I have no idea what is causing this error or if I am even on the right track with my code. Any suggestions?
Thanks
public enum LexemeType {
LEFT_PAREN, RIGHT_PAREN, OPERATOR, NUMBER, VARIABLE, EQUALS, SEMICOLON, USER_INPUT;
}
import java.io.*;
import java.util.*;
public class Lexer implements Iterator<Lexeme> {
Lexeme token = null; // last token recognized
boolean eof = false; // reached end of file
private Reader reader = null; // input stream
private int lookahead = 0; // lookahead, if any
private int[] buffer = new int[100]; // lexeme buffer
private int index = 0; // length of lexeme
public Lexer(String toLex) {
this.reader = new StringReader(toLex);
}
// Extract lexeme from buffer
public String getLexeme() {
return new String(buffer,0,index);
}
// Reset state to begin new token
private void reset() throws IOException {
if (eof)
throw new IllegalStateException();
index = 0;
token = null;
if (lookahead==0)
read();
}
// Read one more char.
// Add previous char, if any, to the buffer.
private void read() throws IOException {
if (eof)
throw new IllegalStateException();
if (lookahead != 0) {
buffer[index] = lookahead;
index++;
}
lookahead = reader.read();
}
// Recognize a token
public void lex() throws IOException {
reset();
// Skip whitespace
while (Character.isWhitespace(lookahead)) {
read();
}
reset();
// Recognize (
if (lookahead == '(') {
token = new Lexeme(LexemeType.LEFT_PAREN, "(");
read();
return;
}
// Recognize )
if (lookahead == ')') {
token = new Lexeme(LexemeType.RIGHT_PAREN, "(");
read();
return;
}
// Recognize ;
if (lookahead == ';') {
token = new Lexeme(LexemeType.SEMICOLON, ";");
read();
return;
}
// Recognize =
if (lookahead == '=') {
token = new Lexeme(LexemeType.EQUALS, "=");
read();
return;
}
// Recognize ?
if (lookahead == '?') {
token = new Lexeme(LexemeType.USER_INPUT, "?");
read();
return;
}
// Recognize float
if (Character.isDigit(lookahead)) {
do {
read();
} while (Character.isDigit(lookahead));
if (lookahead=='.') {
read();
while (Character.isDigit(lookahead))
read();
}
token = new Lexeme(LexemeType.NUMBER, ("-?[0-9]+"));
return;
}
// Recognize string
if (lookahead=='"') {
do {
read();
} while (lookahead!='"');
read();
token = new Lexeme(LexemeType.VARIABLE, ("^[a-zA-Z]*$"));
return;
}
}
#Override
public boolean hasNext() {
if (token!=null)
return true;
if (eof)
return false;
try {
lex();
} catch (IOException e) {
}
return true;
}
#Override
public Lexeme next() {
if (hasNext()) {
Lexeme result = token;
token = null;
return result;
}
else
throw new IllegalStateException();
}
}

Fast way to compare inputstreams

I have a problem, I need to compare two inputstreams fast.
Today I have a function like this:
private boolean isEqual(InputStream i1, InputStream i2) throws IOException {
try {
// do the compare
while (true) {
int fr = i1.read();
int tr = i2.read();
if (fr != tr)
return false;
if (fr == -1)
return true;
}
} finally {
if (i1 != null)
i1.close();
if (i2 != null)
i2.close();
}
}
But it's really slow. I want to use buffered reads but have not come up with a good way of doing it.
Some extra stuff that makes it harder:
I don't want to read one of the input streams into memory (the whole one)
I don't want to use a third party library
I need a practial solution - code! :)
By far my favorite is to use the org.apache.commons.io.IOUtils helper class from the Apache Commons IO library:
IOUtils.contentEquals( is1, is2 );
Something like this may do:
private static boolean isEqual(InputStream i1, InputStream i2)
throws IOException {
ReadableByteChannel ch1 = Channels.newChannel(i1);
ReadableByteChannel ch2 = Channels.newChannel(i2);
ByteBuffer buf1 = ByteBuffer.allocateDirect(1024);
ByteBuffer buf2 = ByteBuffer.allocateDirect(1024);
try {
while (true) {
int n1 = ch1.read(buf1);
int n2 = ch2.read(buf2);
if (n1 == -1 || n2 == -1) return n1 == n2;
buf1.flip();
buf2.flip();
for (int i = 0; i < Math.min(n1, n2); i++)
if (buf1.get() != buf2.get())
return false;
buf1.compact();
buf2.compact();
}
} finally {
if (i1 != null) i1.close();
if (i2 != null) i2.close();
}
}
Using buffered reads is just a matter of wrapping the InputStreams with BufferedInputStreams. However you are likely to get the best performance reading large blocks at a time.
private boolean isEqual(InputStream i1, InputStream i2) throws IOException {
byte[] buf1 = new byte[64 *1024];
byte[] buf2 = new byte[64 *1024];
try {
DataInputStream d2 = new DataInputStream(i2);
int len;
while ((len = i1.read(buf1)) > 0) {
d2.readFully(buf2,0,len);
for(int i=0;i<len;i++)
if(buf1[i] != buf2[i]) return false;
}
return d2.read() < 0; // is the end of the second file also.
} catch(EOFException ioe) {
return false;
} finally {
i1.close();
i2.close();
}
}
why not simply wrap both streams at the very beginning of your method:
i1 = new BufferedInputStream(i1);
i2 = new BufferedInputStream(i2);
Alternatively, you could simply try reading both streams into a buffer:
public static boolean equals(InputStream i1, InputStream i2, int buf) throws IOException {
try {
// do the compare
while (true) {
byte[] b1 = new byte[buf];
byte[] b2 = new byte[buf];
int length = i1.read(b1);
if (length == -1) {
return i2.read(b2, 0, 1) == -1;
}
try {
StreamUtils.readFully(i2, b2, 0, length);
} catch (EOFException e) {
// i2 is shorter than i1
return false;
}
if (!ArrayUtils.equals(b1, b2, 0, length)) {
return false;
}
}
} finally {
// simply close streams and ignore (log) exceptions
StreamUtils.close(i1, i2);
}
}
// StreamUtils.readFully(..)
public static void readFully(InputStream in, byte[] b, int off, int len) throws EOFException, IOException {
while (len > 0) {
int read = in.read(b, off, len);
if (read == -1) {
throw new EOFException();
}
off += read;
len -= read;
}
}
// ArrayUtils.equals(..)
public static boolean equals(byte[] a, byte[] a2, int off, int len) {
if (off < 0 || len < 0 || len > a.length - off || len > a2.length - off) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return true;
}
if (a == a2) {
return true;
}
if (a == null || a2 == null) {
return false;
}
for (int i = off; i < off + len; i++) {
if (a[i] != a2[i]) {
return false;
}
}
return true;
}
EDIT: I've fixed my implementation now. That's how it looks like without DataInputStream or NIO. Code is available at GitHub or from Sonatype's OSS Snapshot Repository Maven:
<dependency>
<groupId>at.molindo</groupId>
<artifactId>molindo-utils</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>

Categories