Java code to filter Cross site scripting
Filter intercepts every request sent to your web application and then cleans any potential script injection. This code remove all suspicious strings from request parameters before returning them to the application.
private String cleanXSS(final String paramString) {
if (paramString == null)
return "";
String str = paramString;
str = str.replaceAll("", "");
Pattern localPattern = Pattern.compile("<script>(.*?)</script>", 2);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("src[rn]*=[rn]*'(.*?)'", 42);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("src[rn]*=[rn]*\"(.*?)\"", 42);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("</script>", 2);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("<script(.*?)>", 42);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("eval\((.*?)\)", 42);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("expression\((.*?)\)", 42);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("javascript:", 2);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("vbscript:", 2);
str = localPattern.matcher(str).replaceAll("");
localPattern = Pattern.compile("onload(.*?)=", 42);
str = localPattern.matcher(str).replaceAll("");
str = str.replaceAll("\(", "(").replaceAll("\)", ")");
str = str.replaceAll("'", "'");
str = str.replaceAll("<", "<").replaceAll(">", ">");
return str;
}
Read More
Debugging java application in Eclipse
Debugging java application locally on any IDE like Eclipse or Netbeans it’s very simple, just select the project and click debug or use debug shortcut provided by IDE. You can also debug a single java class with main method. In Eclipse just right click and select “Debug as Java Application”.
5 practical Java debugging tips
Now let’s see some java debugging tips which I used while doing debugging in Java in eclipse.
1) Use conditional breakpoint
Eclipse allows you to setup conditional break point for debugging java program, which is a breakpoint with condition and your thread will only stop at specified line if condition matches instead of just stopping on that line like in case of line breakpoint. To setup a conditional breakpoint just double click on any line where you want to setup a breakpoint and then right click –> properties and then insert the condition. Now program will only stop when that particular condition is true and program is running on debug mode.
2) Use Exception breakpoint
How many times you have frustrated with a NullPointerException and you don’t know the source from where the exception is coming. Exception breakpoints are just made for such situation. Both Eclipse and Netbeans allows you to setup Exception breakpoint. You can setup Exception breakpoint based on java exception like NullPointerException or ArrayIndexOutOfBoundException. You can setup Exception breakpoint from breakpoint window and your program will stop when you start it on debug mode and exception occurs.
3 ) Inspect and Watch
These are two menu options which I use to see the value of expression during debugging java program. I just select the statement, right click and inspect and it will show you the value of that statement at debugging time. You can also put watch on that and that condition and its value will appear on watch window.
4) Step over, Step Into
These are simply great debugging options available in any Java IDE, extremely useful if you are debugging multi-threaded application and want to navigate step by step.
5) Suspending and resuming thread
You can suspend and resume any thread while debugging java program from debug window. Just right click on any thread and select either suspends or resume. This is also very useful while debugging multi-threading program and simulating race conditions.
lastly java debugging is real fun so definitely try it few times to get hold of it and please share some other java debugging tips you use on your daily life.
Read More
Using -Xss to adjust Java default thread stack size to prevent StackOverflowError and OutOfMemoryError
Every thread created in a Java program has its own stack space. The stack space used is not allocated from the heap. Infact if you look at the OS report on the memory used by your JVM, you may notice that it is more than what -Xmx parameter specifies. This is because, beside other things, memory is used for the thread stacks too. And this memory is not included in the heap specified by the -Xms and -Xmx switches.
The thread stack is used to push stacks frames in nested method calls. If the nesting is so deep that the thread runs out of space, the thread dies with a StackOverflowError.
The default thread stack size varies with JVM, OS and environment variables. A typical value is 512k. It is generally larger for 64bit JVMs because references are 8 bytes rather than 4 bytes in size. This means that if your app uses 150 threads, 75MB will be used for thread stacks. In some environments the defaults stack may be as large as 2MB. With a large number of threads, this can consume a significant amount of memory which could otherwise be used by your application or OS.
In most applications, 128k happens to be enough for the stack. What you really need to do is adjust and observe. If you don’t see your app running out of stack space, use the -Xss JVM parameter to specify a smaller stack (-Xss128k).
Note that it is entirely possible that your OS rounds up values for stack size specified by your -Xss parameter. Watch out for that.
Using the program below, you can see how stack space is used up by methods with varying number of arguments. You’ll get the StackOverflowError with fewer nested method calls for a smaller stack. You could try adjusting the number of arguments and even the type of arguments for different behaviour.
By adjusting the stack size, and keeping the code the same, you can see the JVM dying at different points in the recursive call.
package com.simplecode.com;
public class MemoryTest {
private static long count = 0;
public static void main(String[] arg) {
infiniteMethod(1);
}
public static void infiniteMethod(int value) {
System.out.println(count++);
infiniteMethod(value);
}
}
Read More
Java code to convert xlsx & xls to csv
import java.io.*;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
class ExceltoCSV {
static void xlsx(File inputFile, File outputFile) {
// For storing data into CSV files
StringBuffer data = new StringBuffer();
try {
FileOutputStream fos = new FileOutputStream(outputFile);
// Get the workbook object for XLSX file
XSSFWorkbook wBook = new XSSFWorkbook
(new FileInputStream(inputFile));
// Get first sheet from the workbook
XSSFSheet sheet = wBook.getSheetAt(0);
Row row;
Cell cell;
// Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
row = rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
data.append(cell.getBooleanCellValue() + ",");
break;
case Cell.CELL_TYPE_NUMERIC:
data.append(cell.getNumericCellValue() + ",");
break;
case Cell.CELL_TYPE_STRING:
data.append(cell.getStringCellValue() + ",");
break;
case Cell.CELL_TYPE_BLANK:
data.append("" + ",");
break;
default:
data.append("" + ",");
}
}
}
fos.write(data.toString().getBytes());
fos.close();
} catch (Exception ioe) {
ioe.printStackTrace();
}
}
static void xls(File inputFile, File outputFile) {
// For storing data into CSV files
StringBuffer data = new StringBuffer();
try {
FileOutputStream fos = new FileOutputStream(outputFile);
// Get the workbook object for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(
inputFile));
// Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
Cell cell;
Row row;
// Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
row = rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
data.append(cell.getBooleanCellValue() + ",");
break;
case Cell.CELL_TYPE_NUMERIC:
data.append(cell.getNumericCellValue() + ",");
break;
case Cell.CELL_TYPE_STRING:
data.append(cell.getStringCellValue() + ",");
break;
case Cell.CELL_TYPE_BLANK:
data.append("" + ",");
break;
default:
data.append("" + ",");
}
}
}
fos.write(data.toString().getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
File inputFile = new File("C:\test.xls");
File outputFile = new File("C:\output.csv");
File inputFile2 = new File("C:\test.xlsx");
File outputFile2 = new File("C:\output2.csv");
xls(inputFile, outputFile);
xlsx(inputFile2, outputFile2);
}
}
To execute the above code you must have the following libraries
- dom4j-1.1.jar
- poi-3.7-20101029.jar
- poi-ooxml-3.7-20101029.jar
- poi-ooxml-schemas-3.7-20101029.jar
- xmlbeans-2.3.0.jar
![]() |
|
