├── README.md ├── src └── main │ ├── java │ ├── services │ │ ├── DataUtils.java │ │ ├── ExceptionTest.java │ │ └── ServletUtilities.java │ ├── forkjoin │ │ ├── file │ │ │ ├── WordIndex.java │ │ │ ├── ParallelStream.java │ │ │ ├── SerializeThread.java │ │ │ ├── PureForkJoin.java │ │ │ ├── example │ │ │ │ └── Split.java │ │ │ ├── QueuePool.java │ │ │ └── TestFile.java │ │ ├── prime │ │ │ ├── SerializeThread.java │ │ │ ├── ParallelStream.java │ │ │ ├── QueuePool.java │ │ │ ├── example │ │ │ │ ├── SequentialStreamPrimes.java │ │ │ │ └── ForkBlur.java │ │ │ ├── PureForkJoin.java │ │ │ └── TestPrime.java │ │ ├── StartPoint.java │ │ └── Utils.java │ └── controllers │ │ ├── speed │ │ ├── NormalSpeed.java │ │ ├── Wait100msSpeed.java │ │ └── Res1mbSpeed.java │ │ └── exception │ │ ├── ExpStackTrace.java │ │ └── ExpNormal.java │ ├── webapp │ ├── 400.json │ ├── 404.json │ └── WEB-INF │ │ └── web.xml │ └── resources │ └── log4j.properties ├── .gitignore ├── .settings └── org.eclipse.jdt.core.prefs ├── .project ├── .classpath ├── pom.xml └── test.txt /README.md: -------------------------------------------------------------------------------- 1 | # threads-benchmark 2 | Threads benchmark code for Takipi blog 3 | -------------------------------------------------------------------------------- /src/main/java/services/DataUtils.java: -------------------------------------------------------------------------------- 1 | package services; 2 | 3 | 4 | public class DataUtils { 5 | 6 | 7 | static { 8 | 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.jar 8 | *.war 9 | *.ear 10 | 11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 12 | hs_err_pid* 13 | -------------------------------------------------------------------------------- /.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | #Mon Jan 19 21:05:26 IST 2015 2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 3 | eclipse.preferences.version=1 4 | org.eclipse.jdt.core.compiler.source=1.8 5 | org.eclipse.jdt.core.compiler.compliance=1.8 6 | -------------------------------------------------------------------------------- /src/main/webapp/400.json: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | {"status":404, "Message":"This reource is not exist"} 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/main/webapp/404.json: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | {"status":404, "Message":"This reource is not exist"} 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/main/java/forkjoin/file/WordIndex.java: -------------------------------------------------------------------------------- 1 | package forkjoin.file; 2 | 3 | public class WordIndex { 4 | private long line; 5 | private int localIndex; 6 | public WordIndex(long line, int localIndex){ 7 | this.line = line; 8 | this.localIndex = localIndex; 9 | } 10 | @Override 11 | public String toString(){ 12 | return String.format("Line = %s, localIndex = %s", line, localIndex); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | TakipiAWSTest 4 | NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse. 5 | 6 | 7 | 8 | org.eclipse.jdt.core.javabuilder 9 | 10 | 11 | 12 | org.eclipse.jdt.core.javanature 13 | 14 | -------------------------------------------------------------------------------- /src/main/java/forkjoin/prime/SerializeThread.java: -------------------------------------------------------------------------------- 1 | package forkjoin.prime; 2 | 3 | import java.math.BigInteger; 4 | 5 | import forkjoin.Utils; 6 | 7 | public class SerializeThread { 8 | public boolean isprime(BigInteger n) { 9 | boolean isPrime = true; 10 | 11 | for (BigInteger i = Utils.two; i.compareTo(TestPrime.sqrt) <= 0; i = i 12 | .add(BigInteger.ONE)) { 13 | if (n.mod(i).equals(BigInteger.ZERO)) { 14 | isPrime = false; 15 | } 16 | } 17 | 18 | return isPrime; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | # LOG4J configuration 2 | log4j.rootLogger=INFO, Appender1,Appender2 3 | 4 | log4j.appender.Appender1=org.apache.log4j.ConsoleAppender 5 | log4j.appender.Appender1.layout=org.apache.log4j.PatternLayout 6 | log4j.appender.Appender1.layout.ConversionPattern=%-7p %d [%t] %c %x - %m%n 7 | 8 | log4j.appender.Appender2=org.apache.log4j.FileAppender 9 | log4j.appender.Appender2.File=/var/log/billistic.log 10 | log4j.appender.Appender2.layout=org.apache.log4j.PatternLayout 11 | log4j.appender.Appender2.layout.ConversionPattern=%-7p %d [%t] %c %x - %m%n -------------------------------------------------------------------------------- /src/main/java/forkjoin/prime/ParallelStream.java: -------------------------------------------------------------------------------- 1 | package forkjoin.prime; 2 | 3 | import java.math.BigInteger; 4 | import java.util.Set; 5 | import java.util.stream.Collectors; 6 | import java.util.stream.Stream; 7 | 8 | import forkjoin.Utils; 9 | 10 | public class ParallelStream { 11 | public boolean isPrime() { 12 | Set collect = Stream 13 | .iterate(Utils.two, n -> n.add(TestPrime.lengthForThread)) 14 | .limit(TestPrime.numberOfThread.longValue()).parallel() 15 | .filter(i -> Utils.primeProcessPart(i)) 16 | .collect(Collectors.toSet()); 17 | return collect.size() == 0; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/forkjoin/StartPoint.java: -------------------------------------------------------------------------------- 1 | package forkjoin; 2 | 3 | import forkjoin.file.TestFile; 4 | import forkjoin.prime.TestPrime; 5 | 6 | public class StartPoint { 7 | public static void main(String[] args) throws Exception { 8 | int request = Integer.parseInt(args[0]); 9 | 10 | if (request == 0) { 11 | TestFile.createTestFile(); 12 | return; 13 | } 14 | 15 | int runCase = Integer.parseInt(args[1]); 16 | 17 | if (request == 1) { 18 | long lineNum = Long.parseLong(args[2]); 19 | TestFile.testFile(runCase, lineNum); 20 | return; 21 | } 22 | 23 | if (request == 2) { 24 | TestPrime.testPrime(runCase, args[2], args[3]); 25 | return; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/main/java/controllers/speed/NormalSpeed.java: -------------------------------------------------------------------------------- 1 | package controllers.speed; 2 | 3 | import java.io.IOException; 4 | import java.io.PrintWriter; 5 | 6 | import javax.servlet.ServletException; 7 | import javax.servlet.annotation.WebServlet; 8 | import javax.servlet.http.HttpServlet; 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | 12 | @WebServlet("/speed/normal") 13 | public class NormalSpeed extends HttpServlet { 14 | private static final long serialVersionUID = -7166033569721460991L; 15 | 16 | @Override 17 | public void doGet(HttpServletRequest request, HttpServletResponse response) 18 | throws ServletException, IOException { 19 | PrintWriter out = response.getWriter(); 20 | out.println("OK"); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/forkjoin/prime/QueuePool.java: -------------------------------------------------------------------------------- 1 | package forkjoin.prime; 2 | 3 | import java.math.BigInteger; 4 | import java.util.concurrent.Callable; 5 | 6 | public class QueuePool implements Callable { 7 | 8 | private BigInteger from; 9 | private BigInteger to; 10 | private BigInteger primeNumber; 11 | 12 | public QueuePool(BigInteger primeNumber, BigInteger from, BigInteger to) { 13 | this.primeNumber = primeNumber; 14 | this.from = from; 15 | this.to = to; 16 | } 17 | 18 | @Override 19 | public Boolean call() { 20 | boolean isPrime = true; 21 | for (BigInteger i = from; i.compareTo(to) <= 0; i = i 22 | .add(BigInteger.ONE)) { 23 | if (this.primeNumber.mod(i).equals(BigInteger.ZERO)) { 24 | isPrime = false; 25 | } 26 | } 27 | return isPrime; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | Web Application 7 | 8 | 9 | 404 10 | /error/404.json 11 | 12 | 13 | 400 14 | /error/400.json 15 | 16 | 17 | 18 | java.lang.Exception 19 | /error/exception.json 20 | 21 | -------------------------------------------------------------------------------- /src/main/java/controllers/speed/Wait100msSpeed.java: -------------------------------------------------------------------------------- 1 | package controllers.speed; 2 | 3 | import java.io.IOException; 4 | import java.io.PrintWriter; 5 | 6 | import javax.servlet.ServletException; 7 | import javax.servlet.annotation.WebServlet; 8 | import javax.servlet.http.HttpServlet; 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | 12 | @WebServlet("/speed/wait100") 13 | public class Wait100msSpeed extends HttpServlet { 14 | private static final long serialVersionUID = 3490470371921661069L; 15 | 16 | @Override 17 | public void doGet(HttpServletRequest request, HttpServletResponse response) 18 | throws ServletException, IOException { 19 | PrintWriter out = response.getWriter(); 20 | try { 21 | Thread.sleep(100); 22 | } catch (InterruptedException e) { 23 | e.printStackTrace(); 24 | } 25 | out.println("OK"); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/services/ExceptionTest.java: -------------------------------------------------------------------------------- 1 | package services; 2 | 3 | 4 | /** Some simple time savers. Static methods. */ 5 | 6 | public class ExceptionTest { 7 | static int k = 0; 8 | 9 | public static void testException() throws Exception { 10 | System.out.println(k++); 11 | test1(); 12 | } 13 | 14 | public static void test1() throws Exception { 15 | try { 16 | test2(); 17 | } catch (InterruptedException e) { 18 | e.printStackTrace(); 19 | throw new Exception(); 20 | } 21 | } 22 | 23 | public static void test2() throws InterruptedException { 24 | try { 25 | test3(); 26 | } catch (ClassNotFoundException e) { 27 | e.printStackTrace(); 28 | throw new InterruptedException(); 29 | } 30 | } 31 | 32 | public static void test3() throws ClassNotFoundException { 33 | try { 34 | test4(); 35 | } catch (NoSuchFieldException e) { 36 | e.printStackTrace(); 37 | throw new ClassNotFoundException(); 38 | } 39 | } 40 | 41 | public static void test4() throws NoSuchFieldException { 42 | throw new NoSuchFieldException(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/forkjoin/prime/example/SequentialStreamPrimes.java: -------------------------------------------------------------------------------- 1 | package forkjoin.prime.example; 2 | 3 | import java.util.Set; 4 | import java.util.stream.Collectors; 5 | import java.util.stream.IntStream; 6 | 7 | public class SequentialStreamPrimes { 8 | 9 | public static boolean isPrime(int prime) { 10 | Set collect = IntStream 11 | .rangeClosed(2, (int) (Math.sqrt(prime))).parallel() 12 | .filter(j -> prime % j == 0).mapToObj(j -> Integer.valueOf(j)) 13 | .collect(Collectors.toSet()); 14 | System.out.println(collect.size()); 15 | return false; 16 | } 17 | 18 | public static Set findPrimes(int maxPrimeTry) { 19 | return IntStream 20 | .rangeClosed(2, maxPrimeTry) 21 | .map(i -> IntStream.rangeClosed(2, (int) (Math.sqrt(i))) 22 | .filter(j -> i % j == 0).map(j -> 0).findAny() 23 | .orElse(i)).filter(i -> i != 0) 24 | .mapToObj(i -> Integer.valueOf(i)).collect(Collectors.toSet()); 25 | } 26 | 27 | public static void main(String args[]) { 28 | long startTime = System.currentTimeMillis(); 29 | isPrime(3000); 30 | 31 | long timeTaken = System.currentTimeMillis() - startTime; 32 | System.out.println("Time taken: " + timeTaken); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/controllers/exception/ExpStackTrace.java: -------------------------------------------------------------------------------- 1 | package controllers.exception; 2 | 3 | import java.io.IOException; 4 | import java.io.PrintWriter; 5 | 6 | import javax.servlet.ServletException; 7 | import javax.servlet.annotation.WebServlet; 8 | import javax.servlet.http.HttpServlet; 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | 12 | import services.ServletUtilities; 13 | 14 | @WebServlet("/exception/trade") 15 | public class ExpStackTrace extends HttpServlet { 16 | private static final long serialVersionUID = -2076640996856662490L; 17 | 18 | @Override 19 | public void doGet(HttpServletRequest request, HttpServletResponse response) 20 | throws ServletException, IOException { 21 | try { 22 | ServletUtilities.testException(); 23 | } catch (Exception e) { 24 | e.printStackTrace(); 25 | } 26 | 27 | response.setContentType("text/html"); 28 | PrintWriter out = response.getWriter(); 29 | out.println("\n" + "\n" 30 | + "A Test Servlet\n" 31 | + "\n" + "

Test

\n" 32 | + "

Simple servlet for testing.

\n" + ""); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/forkjoin/prime/PureForkJoin.java: -------------------------------------------------------------------------------- 1 | package forkjoin.prime; 2 | 3 | import java.math.BigInteger; 4 | import java.util.concurrent.RecursiveTask; 5 | 6 | import forkjoin.Utils; 7 | 8 | public class PureForkJoin extends RecursiveTask { 9 | private static final long serialVersionUID = -1883115459616562727L; 10 | 11 | private BigInteger from; 12 | private BigInteger to; 13 | boolean isPrime = true; 14 | 15 | public PureForkJoin(BigInteger start, BigInteger to) { 16 | this.from = start; 17 | this.to = to; 18 | } 19 | 20 | private boolean computeDirectly() { 21 | for (BigInteger i = this.from; i.compareTo(this.to) <= 0; i = i 22 | .add(BigInteger.ONE)) { 23 | if (TestPrime.primeNumber.mod(i).equals(BigInteger.ZERO)) { 24 | isPrime = false; 25 | } 26 | } 27 | return isPrime; 28 | } 29 | 30 | @Override 31 | protected Boolean compute() { 32 | BigInteger tmp = to.subtract(from); 33 | if (tmp.compareTo(TestPrime.lengthForThread) <= 0) { 34 | return computeDirectly(); 35 | } 36 | 37 | BigInteger middle = to.add(from).divide(Utils.two); 38 | PureForkJoin leftJoin = new PureForkJoin(this.from, middle); 39 | PureForkJoin rightJoin = new PureForkJoin(middle.add(BigInteger.ONE), 40 | this.to); 41 | 42 | invokeAll(leftJoin, rightJoin); 43 | 44 | return leftJoin.isPrime && rightJoin.isPrime; 45 | } 46 | } -------------------------------------------------------------------------------- /src/main/java/controllers/speed/Res1mbSpeed.java: -------------------------------------------------------------------------------- 1 | package controllers.speed; 2 | 3 | import java.io.BufferedInputStream; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | import java.net.URL; 7 | 8 | import javax.servlet.ServletException; 9 | import javax.servlet.ServletOutputStream; 10 | import javax.servlet.annotation.WebServlet; 11 | import javax.servlet.http.HttpServlet; 12 | import javax.servlet.http.HttpServletRequest; 13 | import javax.servlet.http.HttpServletResponse; 14 | 15 | import org.apache.commons.io.IOUtils; 16 | 17 | @WebServlet(urlPatterns = "/speed/res1mb", loadOnStartup = 1) 18 | public class Res1mbSpeed extends HttpServlet { 19 | private static final long serialVersionUID = -5152808640821687260L; 20 | 21 | public byte[] retData; 22 | 23 | public void init() { 24 | InputStream in; 25 | try { 26 | in = new BufferedInputStream(new URL("http", 27 | "download.thinkbroadband.com", "/1MB.zip").openStream()); 28 | retData = IOUtils.toByteArray(in); 29 | System.out.println("Get Data OK"); 30 | 31 | } catch (Exception e) { 32 | e.printStackTrace(); 33 | } 34 | } 35 | 36 | @Override 37 | public void doGet(HttpServletRequest request, HttpServletResponse response) 38 | throws ServletException, IOException { 39 | ServletOutputStream outputStream = response.getOutputStream(); 40 | outputStream.write(retData); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/forkjoin/file/ParallelStream.java: -------------------------------------------------------------------------------- 1 | package forkjoin.file; 2 | 3 | import java.util.Calendar; 4 | import java.util.List; 5 | import java.util.Map; 6 | import java.util.stream.LongStream; 7 | 8 | import forkjoin.Utils; 9 | 10 | public class ParallelStream { 11 | long countLineNumber; 12 | 13 | public ParallelStream(long countLineNumber) { 14 | this.countLineNumber = countLineNumber; 15 | } 16 | 17 | public void process() { 18 | 19 | LongStream.range(0, countLineNumber).parallel() 20 | .filter(i -> i % Utils.numberLinePerThread == 0) 21 | .mapToObj(from -> { 22 | long to = from + Utils.numberLinePerThread - 1; 23 | Map> result = null; 24 | try { 25 | Utils.processPart(from, to); 26 | } catch (Exception e) { 27 | e.printStackTrace(); 28 | } 29 | return result; 30 | 31 | }).count(); 32 | 33 | } 34 | 35 | public static void main(String args[]) throws InterruptedException { 36 | long countLineNumber = Utils.countLineNumber(Utils.fileLocation); 37 | ParallelStream mc = new ParallelStream(countLineNumber); 38 | System.out.println("line number " + countLineNumber); 39 | for (int i = 0; i < 5; i++) { 40 | long t1 = Calendar.getInstance().getTimeInMillis(); 41 | mc.process(); 42 | long t2 = Calendar.getInstance().getTimeInMillis(); 43 | System.out.println(String.format("Time = %s ms ", (t2 - t1))); 44 | Thread.sleep(5000); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/forkjoin/file/SerializeThread.java: -------------------------------------------------------------------------------- 1 | package forkjoin.file; 2 | 3 | import java.io.FileInputStream; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | import java.util.Scanner; 8 | 9 | import forkjoin.Utils; 10 | 11 | public class SerializeThread { 12 | static Map> result = new HashMap>(); 13 | 14 | public static void main(String[] args) { 15 | try { 16 | 17 | 18 | } catch (Exception e) { 19 | e.printStackTrace(); 20 | } 21 | } 22 | 23 | public void process() throws Exception { 24 | FileInputStream inputStream = null; 25 | Scanner sc = null; 26 | try { 27 | inputStream = new FileInputStream(Utils.fileLocation); 28 | sc = new Scanner(inputStream, "UTF-8"); 29 | int line = 0; 30 | String s = ""; 31 | String[] words = null; 32 | while (sc.hasNextLine()) { 33 | s = sc.nextLine(); 34 | words = s.trim().split("\\s+"); 35 | for (int i = 0; i < words.length; i++) { 36 | if (!Utils.isEmptyString(words[i])) { 37 | //if (result.get(words[i]) == null) { 38 | // result.put(words[i], new LinkedList()); 39 | //} 40 | //result.get(words[i]).add(new WordIndex(line, i)); 41 | } 42 | } 43 | line++; 44 | } 45 | if (sc.ioException() != null) { 46 | throw sc.ioException(); 47 | } 48 | } finally { 49 | if (inputStream != null) { 50 | inputStream.close(); 51 | } 52 | if (sc != null) { 53 | sc.close(); 54 | } 55 | } 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/forkjoin/file/PureForkJoin.java: -------------------------------------------------------------------------------- 1 | package forkjoin.file; 2 | 3 | import java.util.Calendar; 4 | import java.util.concurrent.ForkJoinPool; 5 | import java.util.concurrent.RecursiveTask; 6 | 7 | import forkjoin.Utils; 8 | 9 | public class PureForkJoin extends RecursiveTask { 10 | private static final long serialVersionUID = 7926312633273843668L; 11 | 12 | private long from; 13 | private long to; 14 | 15 | public PureForkJoin(long from, long to) { 16 | this.from = from; 17 | this.to = to; 18 | } 19 | 20 | @Override 21 | protected V compute() { 22 | try { 23 | if (to - from <= Utils.numberLinePerThread) { 24 | Utils.processPart(from, to); 25 | return null; 26 | } 27 | long middle = (to + from) / 2; 28 | 29 | PureForkJoin leftJoin = new PureForkJoin(from, 30 | middle); 31 | PureForkJoin rightJoin = new PureForkJoin( 32 | middle + 1L, to); 33 | 34 | invokeAll(leftJoin, rightJoin); 35 | 36 | } catch (Exception e) { 37 | 38 | } 39 | return null; 40 | } 41 | 42 | public static void main(String[] args) { 43 | long countLineNumber = Utils.countLineNumber(Utils.fileLocation); 44 | 45 | for (int i = 0; i < 5; i++) { 46 | PureForkJoin fb = new PureForkJoin(0L, 47 | countLineNumber - 1); 48 | ForkJoinPool pool = new ForkJoinPool(); 49 | 50 | long t1 = Calendar.getInstance().getTimeInMillis(); 51 | pool.invoke(fb); 52 | long t2 = Calendar.getInstance().getTimeInMillis(); 53 | 54 | System.out.println(String.format("Time = %s ms ", (t2 - t1))); 55 | } 56 | } 57 | } -------------------------------------------------------------------------------- /src/main/java/controllers/exception/ExpNormal.java: -------------------------------------------------------------------------------- 1 | package controllers.exception; 2 | 3 | import java.io.IOException; 4 | import java.io.PrintWriter; 5 | import java.util.Random; 6 | 7 | import javax.servlet.ServletException; 8 | import javax.servlet.annotation.WebServlet; 9 | import javax.servlet.http.HttpServlet; 10 | import javax.servlet.http.HttpServletRequest; 11 | import javax.servlet.http.HttpServletResponse; 12 | 13 | @WebServlet("/exception/normal") 14 | public class ExpNormal extends HttpServlet { 15 | private static final long serialVersionUID = -3237172798612997391L; 16 | 17 | private static Random random = new Random(); 18 | 19 | @Override 20 | public void doGet(HttpServletRequest request, HttpServletResponse response) 21 | throws ServletException, IOException { 22 | int rand = random.nextInt(); 23 | int k = rand % 14; 24 | switch (k) { 25 | case 0: 26 | throw new ArithmeticException(); 27 | case 1: 28 | throw new ArrayIndexOutOfBoundsException(); 29 | case 2: 30 | throw new ArrayStoreException(); 31 | case 3: 32 | throw new ClassCastException(); 33 | case 4: 34 | throw new IllegalArgumentException(); 35 | case 5: 36 | throw new IllegalMonitorStateException(); 37 | case 6: 38 | throw new IllegalStateException(); 39 | case 7: 40 | throw new IllegalThreadStateException(); 41 | case 8: 42 | throw new IndexOutOfBoundsException(); 43 | case 9: 44 | throw new NegativeArraySizeException(); 45 | case 10: 46 | throw new NullPointerException(); 47 | case 11: 48 | throw new NumberFormatException(); 49 | case 12: 50 | throw new SecurityException(); 51 | case 13: 52 | throw new UnsupportedOperationException(); 53 | } 54 | 55 | PrintWriter out = response.getWriter(); 56 | out.println("Hello World"); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/forkjoin/file/example/Split.java: -------------------------------------------------------------------------------- 1 | package forkjoin.file.example; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileInputStream; 6 | import java.io.InputStream; 7 | import java.io.InputStreamReader; 8 | import java.util.ArrayList; 9 | import java.util.concurrent.Callable; 10 | import java.util.concurrent.ExecutorService; 11 | import java.util.concurrent.Executors; 12 | import java.util.concurrent.Future; 13 | 14 | import forkjoin.Utils; 15 | 16 | public class Split { 17 | private File file; 18 | 19 | public Split(File file) { 20 | this.file = file; 21 | } 22 | 23 | public String processPart(long start, long end) throws Exception { 24 | InputStream is = new FileInputStream(Utils.fileLocation); 25 | is.skip(start); 26 | System.out.println("Computing the part from " + start + " to " + end); 27 | BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 28 | String str = ""; 29 | while ((str = reader.readLine()) != null) { 30 | System.out.println(str); 31 | } 32 | 33 | Thread.sleep(1000); 34 | System.out.println("Finished the part from " + start + " to " + end); 35 | 36 | is.close(); 37 | return "Some result"; 38 | } 39 | 40 | public Callable processPartTask(final long start, final long end) { 41 | return new Callable() { 42 | public String call() throws Exception { 43 | return processPart(start, end); 44 | } 45 | }; 46 | } 47 | 48 | public void processAll(int noOfThreads, int chunkSize) throws Exception { 49 | int count = (int) ((file.length() + chunkSize - 1) / chunkSize); 50 | java.util.List> tasks = new ArrayList>(count); 51 | for (int i = 0; i < count; i++) 52 | tasks.add(processPartTask(i * chunkSize, Math.min(file.length(), (i + 1) * chunkSize))); 53 | ExecutorService es = Executors.newFixedThreadPool(noOfThreads); 54 | java.util.List> results = es.invokeAll(tasks); 55 | es.shutdown(); 56 | 57 | // use the results for something 58 | for (Future result : results) 59 | System.out.println(result.get()); 60 | } 61 | 62 | public static void main(String argv[]) throws Exception { 63 | Split s = new Split(new File(Utils.fileLocation)); 64 | s.processAll(8, 1024); 65 | } 66 | } -------------------------------------------------------------------------------- /src/main/java/forkjoin/file/QueuePool.java: -------------------------------------------------------------------------------- 1 | package forkjoin.file; 2 | 3 | import java.io.File; 4 | import java.util.ArrayList; 5 | import java.util.Calendar; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.concurrent.Callable; 9 | import java.util.concurrent.ExecutorService; 10 | import java.util.concurrent.Executors; 11 | import java.util.concurrent.Future; 12 | 13 | import forkjoin.Utils; 14 | 15 | public class QueuePool { 16 | private File file; 17 | private int chunkSize; 18 | private long fileLength; 19 | 20 | public QueuePool(File file, int chunkSize) { 21 | this.file = file; 22 | this.chunkSize = chunkSize; 23 | this.fileLength = file.length(); 24 | System.out.println("File length = " + this.fileLength); 25 | } 26 | 27 | public Callable>> processPartTask( 28 | final long start, final long end) { 29 | return new Callable>>() { 30 | public Map> call() throws Exception { 31 | return Utils.processPart(start, end); 32 | } 33 | }; 34 | } 35 | 36 | public Map> processAll(int noOfThreads) 37 | throws Exception { 38 | int count = (int) ((fileLength + chunkSize - 1) / chunkSize); 39 | java.util.List>>> tasks = new ArrayList>>>( 40 | count); 41 | for (int i = 0; i < count; i += Utils.numberLinePerThread) 42 | tasks.add(processPartTask(i, (i + Utils.numberLinePerThread))); 43 | ExecutorService es = Executors.newFixedThreadPool(noOfThreads); 44 | java.util.List>>> invokes = es 45 | .invokeAll(tasks); 46 | es.shutdown(); 47 | 48 | for (Future>> result : invokes) { 49 | Map> map = result.get(); 50 | } 51 | return null; 52 | } 53 | 54 | public static void main(String argv[]) throws Exception { 55 | long t1 = Calendar.getInstance().getTimeInMillis(); 56 | QueuePool s = new QueuePool(new File(Utils.fileLocation), 1024); 57 | 58 | Map> processAll = s.processAll(8); 59 | 60 | long t2 = Calendar.getInstance().getTimeInMillis(); 61 | 62 | System.out.println(String.format( 63 | "Time = %s ms ; number of words = %s, number of 'it' = %s", 64 | (t2 - t1), processAll.size(), processAll.get("it").size())); 65 | 66 | List list = processAll.get("it"); 67 | 68 | System.out.println("Data for words 'it'"); 69 | for (WordIndex wordIndex : list) { 70 | System.out.println(wordIndex.toString()); 71 | } 72 | 73 | } 74 | } -------------------------------------------------------------------------------- /src/main/java/forkjoin/prime/example/ForkBlur.java: -------------------------------------------------------------------------------- 1 | package forkjoin.prime.example; 2 | 3 | import java.util.Calendar; 4 | import java.util.Random; 5 | import java.util.concurrent.ForkJoinPool; 6 | import java.util.concurrent.RecursiveAction; 7 | 8 | public class ForkBlur extends RecursiveAction { 9 | private static final long serialVersionUID = -1029734293926194419L; 10 | 11 | private int[] mSource; 12 | private int mStart; 13 | private int mLength; 14 | private int[] mDestination; 15 | 16 | // Processing window size; should be odd. 17 | private int mBlurWidth = 3; 18 | 19 | public ForkBlur(int[] src, int start, int length, int[] dst) { 20 | mSource = src; 21 | mStart = start; 22 | mLength = length; 23 | mDestination = dst; 24 | } 25 | 26 | protected void computeDirectly() { 27 | int sidePixels = (mBlurWidth - 1) / 2; 28 | for (int index = mStart; index < mStart + mLength; index++) { 29 | // Calculate average. 30 | int total = 0, k = 0; 31 | ; 32 | for (int mi = -sidePixels; mi <= sidePixels; mi++) { 33 | k++; 34 | int mindex = Math.min(Math.max(mi + index, 0), 35 | mSource.length - 1); 36 | int pixel = mSource[mindex]; 37 | total += pixel; 38 | } 39 | 40 | // Reassemble destination pixel. 41 | int dpixel = total / k; 42 | mDestination[index] = dpixel; 43 | } 44 | } 45 | 46 | protected static int sThreshold = 5; 47 | 48 | protected void compute() { 49 | if (mLength < sThreshold) { 50 | computeDirectly(); 51 | return; 52 | } 53 | int split = mLength / 2; 54 | 55 | invokeAll(new ForkBlur(mSource, mStart, split, mDestination), 56 | new ForkBlur(mSource, mStart + split, mLength - split, 57 | mDestination)); 58 | } 59 | 60 | public static void main(String[] args) { 61 | Random tmp = new Random(); 62 | int size = 4000000; 63 | int[] src = new int[size]; 64 | StringBuffer sSrc = new StringBuffer(); 65 | StringBuffer sDsc = new StringBuffer(); 66 | for (int i = 0; i < size; i++) { 67 | int k = tmp.nextInt(100); 68 | src[i] = k; 69 | sSrc.append(k + ","); 70 | } 71 | int[] dst = new int[src.length]; 72 | ForkBlur fb = new ForkBlur(src, 0, src.length, dst); 73 | 74 | ForkJoinPool pool = new ForkJoinPool(); 75 | 76 | int parallelism = pool.getParallelism(); 77 | System.out.println("Number of " + parallelism); 78 | 79 | long t1 = Calendar.getInstance().getTimeInMillis(); 80 | pool.invoke(fb); 81 | long t2 = Calendar.getInstance().getTimeInMillis(); 82 | System.out.println("Time " + (t2 - t1)); 83 | for (int i = 0; i < size; i++) { 84 | sDsc.append(dst[i] + ","); 85 | } 86 | // System.out.println(sSrc); 87 | // System.out.println(sDsc); 88 | 89 | } 90 | } -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | com.takipi 6 | threads-benchmark 7 | war 8 | 1.0 9 | TakipiAWSTest 10 | http://maven.apache.org 11 | 12 | 13 | UTF-8 14 | 2.3 15 | 16 | 17 | 18 | 19 | 20 | org.apache.tomcat.maven 21 | tomcat7-maven-plugin 22 | 2.2 23 | 24 | /takipi-aws 25 | 8080 26 | true 27 | 28 | -Xms512m -Xmx2048m -XX:MaxPermSize=512m 29 | 30 | 31 | 32 | 33 | 34 | maven-compiler-plugin 35 | 2.3.2 36 | 37 | 1.8 38 | 1.8 39 | 40 | 41 | 42 | 43 | org.apache.maven.plugins 44 | maven-resources-plugin 45 | 2.4.3 46 | 47 | UTF-8 48 | 49 | 50 | 51 | 53 | 54 | org.apache.maven.plugins 55 | maven-surefire-plugin 56 | 2.17 57 | 58 | -Xmx2048m 59 | true 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | commons-io 68 | commons-io 69 | 2.3 70 | 71 | 72 | javax.servlet 73 | javax.servlet-api 74 | 3.0.1 75 | provided 76 | 77 | 78 | log4j 79 | log4j 80 | 1.2.17 81 | 82 | 83 | commons-logging 84 | commons-logging 85 | 1.1.1 86 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /src/main/java/forkjoin/prime/TestPrime.java: -------------------------------------------------------------------------------- 1 | package forkjoin.prime; 2 | 3 | import java.math.BigInteger; 4 | import java.util.ArrayList; 5 | import java.util.Calendar; 6 | import java.util.List; 7 | import java.util.concurrent.Callable; 8 | import java.util.concurrent.ExecutorService; 9 | import java.util.concurrent.Executors; 10 | import java.util.concurrent.ForkJoinPool; 11 | import java.util.concurrent.Future; 12 | 13 | import forkjoin.Utils; 14 | 15 | public class TestPrime { 16 | public static BigInteger primeNumber; 17 | public static BigInteger sqrt; 18 | public static BigInteger lengthForThread; 19 | public static BigInteger numberOfThread; 20 | 21 | public static void testPrime(int request, String sPrime, 22 | String sNumberOfThread) throws Exception { 23 | primeNumber = new BigInteger(sPrime); 24 | sqrt = Utils.sqrt(primeNumber); 25 | numberOfThread = new BigInteger(sNumberOfThread); 26 | lengthForThread = TestPrime.sqrt.divide(numberOfThread); 27 | System.out.println(String.format("Request: %s -- ThreadNums: %s ", 28 | request, sNumberOfThread)); 29 | 30 | for (int i = 0; i < 10; i++) { 31 | Thread.sleep(500); 32 | switch (request) { 33 | case 1: 34 | testForkJoin(); 35 | break; 36 | case 2: 37 | testParalleStreaming(); 38 | break; 39 | case 3: 40 | testLocalQueue(); 41 | break; 42 | case 4: 43 | testSingleThread(); 44 | break; 45 | } 46 | } 47 | } 48 | 49 | private static void testSingleThread() throws Exception { 50 | long t1 = Calendar.getInstance().getTimeInMillis(); 51 | SerializeThread mc = new SerializeThread(); 52 | boolean isprime = mc.isprime(primeNumber); 53 | long t2 = Calendar.getInstance().getTimeInMillis(); 54 | System.out.println(t2 - t1); 55 | } 56 | 57 | private static void testLocalQueue() throws Exception { 58 | long t1 = Calendar.getInstance().getTimeInMillis(); 59 | boolean isPrime = true; 60 | 61 | ExecutorService executor = Executors.newFixedThreadPool(numberOfThread 62 | .intValue()); 63 | List> list = new ArrayList>(); 64 | for (BigInteger i = Utils.two; i.compareTo(sqrt) <= 0; i = i 65 | .add(lengthForThread)) { 66 | Callable worker = new QueuePool(primeNumber, i, 67 | i.add(lengthForThread)); 68 | list.add(worker); 69 | } 70 | List> invokeAll = executor.invokeAll(list); 71 | executor.shutdown(); 72 | while (executor.isTerminated()) { 73 | } 74 | for (Future future : invokeAll) { 75 | isPrime &= future.get(); 76 | } 77 | long t2 = Calendar.getInstance().getTimeInMillis(); 78 | 79 | System.out.println(t2 - t1); 80 | } 81 | 82 | private static void testParalleStreaming() { 83 | ParallelStream mc = new ParallelStream(); 84 | long t1 = Calendar.getInstance().getTimeInMillis(); 85 | boolean isPrime = mc.isPrime(); 86 | long t2 = Calendar.getInstance().getTimeInMillis(); 87 | 88 | System.out.println(t2 - t1); 89 | } 90 | 91 | private static void testForkJoin() { 92 | PureForkJoin fb = new PureForkJoin(Utils.two, sqrt); 93 | ForkJoinPool pool = new ForkJoinPool(); 94 | long t1 = Calendar.getInstance().getTimeInMillis(); 95 | Boolean isPrime = pool.invoke(fb); 96 | long t2 = Calendar.getInstance().getTimeInMillis(); 97 | System.out.println(t2 - t1); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/forkjoin/Utils.java: -------------------------------------------------------------------------------- 1 | package forkjoin; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileInputStream; 6 | import java.io.FileNotFoundException; 7 | import java.io.FileReader; 8 | import java.io.IOException; 9 | import java.io.InputStream; 10 | import java.io.InputStreamReader; 11 | import java.io.LineNumberReader; 12 | import java.math.BigInteger; 13 | import java.util.HashMap; 14 | import java.util.List; 15 | import java.util.Map; 16 | import java.util.Random; 17 | 18 | import forkjoin.file.WordIndex; 19 | import forkjoin.prime.TestPrime; 20 | 21 | public class Utils { 22 | public static BigInteger two = new BigInteger("2"); 23 | public static BigInteger three = new BigInteger("3"); 24 | 25 | public static String fileLocation = "/tmp/test.txt"; 26 | public static long numberLinePerThread = 10000; 27 | public static long lineNum = 1838200; 28 | 29 | public static BigInteger sqrt(BigInteger n) { 30 | BigInteger a = BigInteger.ONE; 31 | BigInteger b = new BigInteger(n.shiftRight(5).add(new BigInteger("8")) 32 | .toString()); 33 | while (b.compareTo(a) >= 0) { 34 | BigInteger mid = new BigInteger(a.add(b).shiftRight(1).toString()); 35 | if (mid.multiply(mid).compareTo(n) > 0) 36 | b = mid.subtract(BigInteger.ONE); 37 | else 38 | a = mid.add(BigInteger.ONE); 39 | } 40 | return a.subtract(BigInteger.ONE); 41 | } 42 | 43 | public static boolean isEmptyString(String s) { 44 | return s == null || "".equals(s.trim()); 45 | } 46 | 47 | public static long countLineNumber(String fileLocation) { 48 | long lines = 0; 49 | try { 50 | File file = new File(fileLocation); 51 | LineNumberReader lineNumberReader = new LineNumberReader( 52 | new FileReader(file)); 53 | lineNumberReader.skip(Long.MAX_VALUE); 54 | lines = lineNumberReader.getLineNumber(); 55 | lineNumberReader.close(); 56 | } catch (FileNotFoundException e) { 57 | System.out 58 | .println("FileNotFoundException Occured" + e.getMessage()); 59 | } catch (IOException e) { 60 | System.out.println("IOException Occured" + e.getMessage()); 61 | } 62 | return lines; 63 | } 64 | 65 | public static Map> processPart(long from, long to) 66 | throws Exception { 67 | Map> result = new HashMap>(); 68 | InputStream is = new FileInputStream(Utils.fileLocation); 69 | is.skip(from * 1024); 70 | BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 71 | String s = ""; 72 | long line = from; 73 | while ((s = reader.readLine()) != null && line <= to) { 74 | String[] words = s.trim().split("\\s+"); 75 | for (int i = 0; i < words.length; i++) { 76 | } 77 | line++; 78 | } 79 | is.close(); 80 | return result; 81 | } 82 | 83 | public static Boolean primeProcessPart(BigInteger from) { 84 | boolean isPrime = true; 85 | BigInteger to = from.add(TestPrime.lengthForThread); 86 | for (BigInteger i = from; i.compareTo(to) <= 0; i = i 87 | .add(BigInteger.ONE)) { 88 | if (TestPrime.primeNumber.mod(i).equals(BigInteger.ZERO)) { 89 | isPrime = false; 90 | } 91 | } 92 | return isPrime; 93 | } 94 | 95 | public static void main(String[] args) { 96 | BigInteger x = new BigInteger("5"); 97 | BigInteger primeNumber = new BigInteger("10"); 98 | primeNumber = primeNumber.add(x); 99 | 100 | System.out.println(primeNumber); 101 | 102 | BigInteger probablePrime = BigInteger.probablePrime(61, new Random()); 103 | System.out.println(probablePrime); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/main/java/forkjoin/file/TestFile.java: -------------------------------------------------------------------------------- 1 | package forkjoin.file; 2 | 3 | import java.io.BufferedWriter; 4 | import java.io.File; 5 | import java.io.FileWriter; 6 | import java.io.IOException; 7 | import java.util.Calendar; 8 | import java.util.concurrent.ForkJoinPool; 9 | 10 | import forkjoin.Utils; 11 | 12 | public class TestFile { 13 | public static void testFile(int request, long lineNum) throws Exception{ 14 | Utils.lineNum = lineNum; 15 | for (int i = 0; i < 10; i++) { 16 | switch (request) { 17 | case 1: 18 | testForkJoin(); 19 | Thread.sleep(2000); 20 | break; 21 | case 2: 22 | testParalleStreaming(); 23 | Thread.sleep(2000); 24 | break; 25 | case 3: 26 | testLocalQueue(); 27 | Thread.sleep(2000); 28 | break; 29 | case 4: 30 | testSingleThread(); 31 | Thread.sleep(2000); 32 | break; 33 | 34 | } 35 | } 36 | 37 | } 38 | 39 | private static void testSingleThread() throws Exception { 40 | long t1 = Calendar.getInstance().getTimeInMillis(); 41 | SerializeThread mc = new SerializeThread(); 42 | mc.process(); 43 | long t2 = Calendar.getInstance().getTimeInMillis(); 44 | System.out.println(String.format("Time = %s ms ", (t2 - t1))); 45 | 46 | } 47 | 48 | private static void testLocalQueue() throws Exception { 49 | long t1 = Calendar.getInstance().getTimeInMillis(); 50 | QueuePool s = new QueuePool(new File(Utils.fileLocation), 1024); 51 | s.processAll(8); 52 | long t2 = Calendar.getInstance().getTimeInMillis(); 53 | System.out.println(String.format("Time = %s ms ", (t2 - t1))); 54 | } 55 | 56 | private static void testParalleStreaming() { 57 | long t1 = Calendar.getInstance().getTimeInMillis(); 58 | long countLineNumber = Utils.countLineNumber(Utils.fileLocation); 59 | ParallelStream mc = new ParallelStream(countLineNumber); 60 | mc.process(); 61 | long t2 = Calendar.getInstance().getTimeInMillis(); 62 | System.out.println(String.format("Time = %s ms ", (t2 - t1))); 63 | } 64 | 65 | private static void testForkJoin() { 66 | long t1 = Calendar.getInstance().getTimeInMillis(); 67 | long countLineNumber = Utils.countLineNumber(Utils.fileLocation); 68 | PureForkJoin fb = new PureForkJoin(0L, countLineNumber - 1); 69 | ForkJoinPool pool = new ForkJoinPool(); 70 | pool.invoke(fb); 71 | long t2 = Calendar.getInstance().getTimeInMillis(); 72 | System.out.println(String.format("Time = %s ms ", (t2 - t1))); 73 | } 74 | 75 | public static void createTestFile() { 76 | try { 77 | String data = "The Project Gutenberg EBook of The Outline of Science. This eBook is for the use of anyone anywhere at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this eBook or online at www.gutenberg.org. Was it not the great philosopher and mathematician Leibnitz who said that the more knowledge advances the more it becomes possible to condense it into little books? Now this \"Outline of Science\" is certainly not a little book, and yet it illustrates part of the meaning of Leibnitz's wise saying. For here within reasonable compass there is a library of little books--an outline of many sciences. What then is the aim of this book? It is to give the intelligent student-citizen, otherwise called \"the man in the street,\" a bunch of intellectual keys by which to open doors which have been hitherto shut to him, partly because he got no glimpse of the treasures behind the doors, and partly because the portals were win\n"; 78 | File file = new File("/tmp/test.txt"); 79 | if (!file.exists()) { 80 | file.createNewFile(); 81 | } 82 | 83 | long lineNum = Utils.countLineNumber(Utils.fileLocation); 84 | FileWriter fileWritter = new FileWriter("/tmp/test.txt", false); 85 | BufferedWriter bw = new BufferedWriter(fileWritter); 86 | for (long i = 0L; i < lineNum; i++) { 87 | bw.write(data); 88 | } 89 | bw.close(); 90 | System.out.println("Done"); 91 | 92 | } catch (IOException e) { 93 | e.printStackTrace(); 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/services/ServletUtilities.java: -------------------------------------------------------------------------------- 1 | package services; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | 5 | /** Some simple time savers. Static methods. */ 6 | 7 | public class ServletUtilities { 8 | static int k = 0; 9 | 10 | public static void testException() throws Exception { 11 | System.out.println(k++); 12 | test1(); 13 | } 14 | 15 | public static void test1() throws Exception { 16 | try { 17 | test2(); 18 | } catch (InterruptedException e) { 19 | e.printStackTrace(); 20 | throw new Exception(); 21 | } 22 | } 23 | 24 | public static void test2() throws InterruptedException { 25 | try { 26 | test3(); 27 | } catch (ClassNotFoundException e) { 28 | e.printStackTrace(); 29 | throw new InterruptedException(); 30 | } 31 | } 32 | 33 | public static void test3() throws ClassNotFoundException { 34 | try { 35 | test4(); 36 | } catch (NoSuchFieldException e) { 37 | e.printStackTrace(); 38 | throw new ClassNotFoundException(); 39 | } 40 | } 41 | 42 | public static void test4() throws NoSuchFieldException { 43 | throw new NoSuchFieldException(); 44 | } 45 | 46 | public static String headWithTitle(String title) { 47 | return ("\n" + "\n" + "" + title + "\n"); 48 | } 49 | 50 | /** 51 | * Read a parameter with the specified name, convert it to an int, and 52 | * return it. Return the designated default value if the parameter doesn't 53 | * exist or if it is an illegal integer format. 54 | */ 55 | 56 | public static int getIntParameter(HttpServletRequest request, String paramName, int defaultValue) { 57 | String paramString = request.getParameter(paramName); 58 | int paramValue; 59 | try { 60 | paramValue = Integer.parseInt(paramString); 61 | } catch (Exception nfe) { // null or bad format 62 | paramValue = defaultValue; 63 | } 64 | return (paramValue); 65 | } 66 | 67 | /** Reads param and converts to double. Default if problem. */ 68 | 69 | public static double getDoubleParameter(HttpServletRequest request, String paramName, double defaultValue) { 70 | String paramString = request.getParameter(paramName); 71 | double paramValue; 72 | try { 73 | paramValue = Double.parseDouble(paramString); 74 | } catch (Exception nfe) { // null or bad format 75 | paramValue = defaultValue; 76 | } 77 | return (paramValue); 78 | } 79 | 80 | /** Replaces characters that have special HTML meanings 81 | * with their corresponding HTML character entities. 82 | * Specifically, given a string, this method replaces all 83 | * occurrences of 84 | * {@literal 85 | * '<' with '<', all occurrences of '>' with 86 | * '>', and (to handle cases that occur inside attribute 87 | * values), all occurrences of double quotes with 88 | * '"' and all occurrences of '&' with '&'. 89 | * Without such filtering, an arbitrary string 90 | * could not safely be inserted in a Web page. 91 | * } 92 | */ 93 | 94 | public static String filter(String input) { 95 | if (!hasSpecialChars(input)) { 96 | return (input); 97 | } 98 | StringBuilder filtered = new StringBuilder(input.length()); 99 | char c; 100 | for (int i = 0; i < input.length(); i++) { 101 | c = input.charAt(i); 102 | switch (c) { 103 | case '<': 104 | filtered.append("<"); 105 | break; 106 | case '>': 107 | filtered.append(">"); 108 | break; 109 | case '"': 110 | filtered.append("""); 111 | break; 112 | case '&': 113 | filtered.append("&"); 114 | break; 115 | default: 116 | filtered.append(c); 117 | } 118 | } 119 | return (filtered.toString()); 120 | } 121 | 122 | private static boolean hasSpecialChars(String input) { 123 | boolean flag = false; 124 | if ((input != null) && (input.length() > 0)) { 125 | char c; 126 | for (int i = 0; i < input.length(); i++) { 127 | c = input.charAt(i); 128 | switch (c) { 129 | case '<': 130 | flag = true; 131 | break; 132 | case '>': 133 | flag = true; 134 | break; 135 | case '"': 136 | flag = true; 137 | break; 138 | case '&': 139 | flag = true; 140 | break; 141 | } 142 | } 143 | } 144 | return (flag); 145 | } 146 | 147 | private ServletUtilities() { 148 | } // Uninstantiatable class 149 | } 150 | -------------------------------------------------------------------------------- /test.txt: -------------------------------------------------------------------------------- 1 | The Project Gutenberg EBook of The Outline of Science. This eBook is for the use of anyone anywhere at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this eBook or online at www.gutenberg.org. Was it not the great philosopher and mathematician Leibnitz who said that the more knowledge advances the more it becomes possible to condense it into little books? Now this "Outline of Science" is certainly not a little book, and yet it illustrates part of the meaning of Leibnitz's wise saying. For here within reasonable compass there is a library of little books--an outline of many sciences. What then is the aim of this book? It is to give the intelligent student-citizen, otherwise called "the man in the street," a bunch of intellectual keys by which to open doors which have been hitherto shut to him, partly because he got no glimpse of the treasures behind the doors, and partly because the portals were win 2 | The Project Gutenberg EBook of The Outline of Science. This eBook is for the use of anyone anywhere at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this eBook or online at www.gutenberg.org. Was it not the great philosopher and mathematician Leibnitz who said that the more knowledge advances the more it becomes possible to condense it into little books? Now this "Outline of Science" is certainly not a little book, and yet it illustrates part of the meaning of Leibnitz's wise saying. For here within reasonable compass there is a library of little books--an outline of many sciences. What then is the aim of this book? It is to give the intelligent student-citizen, otherwise called "the man in the street," a bunch of intellectual keys by which to open doors which have been hitherto shut to him, partly because he got no glimpse of the treasures behind the doors, and partly because the portals were win 3 | The Project Gutenberg EBook of The Outline of Science. This eBook is for the use of anyone anywhere at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this eBook or online at www.gutenberg.org. Was it not the great philosopher and mathematician Leibnitz who said that the more knowledge advances the more it becomes possible to condense it into little books? Now this "Outline of Science" is certainly not a little book, and yet it illustrates part of the meaning of Leibnitz's wise saying. For here within reasonable compass there is a library of little books--an outline of many sciences. What then is the aim of this book? It is to give the intelligent student-citizen, otherwise called "the man in the street," a bunch of intellectual keys by which to open doors which have been hitherto shut to him, partly because he got no glimpse of the treasures behind the doors, and partly because the portals were win 4 | The Project Gutenberg EBook of The Outline of Science. This eBook is for the use of anyone anywhere at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this eBook or online at www.gutenberg.org. Was it not the great philosopher and mathematician Leibnitz who said that the more knowledge advances the more it becomes possible to condense it into little books? Now this "Outline of Science" is certainly not a little book, and yet it illustrates part of the meaning of Leibnitz's wise saying. For here within reasonable compass there is a library of little books--an outline of many sciences. What then is the aim of this book? It is to give the intelligent student-citizen, otherwise called "the man in the street," a bunch of intellectual keys by which to open doors which have been hitherto shut to him, partly because he got no glimpse of the treasures behind the doors, and partly because the portals were win 5 | The Project Gutenberg EBook of The Outline of Science. This eBook is for the use of anyone anywhere at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this eBook or online at www.gutenberg.org. Was it not the great philosopher and mathematician Leibnitz who said that the more knowledge advances the more it becomes possible to condense it into little books? Now this "Outline of Science" is certainly not a little book, and yet it illustrates part of the meaning of Leibnitz's wise saying. For here within reasonable compass there is a library of little books--an outline of many sciences. What then is the aim of this book? It is to give the intelligent student-citizen, otherwise called "the man in the street," a bunch of intellectual keys by which to open doors which have been hitherto shut to him, partly because he got no glimpse of the treasures behind the doors, and partly because the portals were win 6 | The Project Gutenberg EBook of The Outline of Science. This eBook is for the use of anyone anywhere at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this eBook or online at www.gutenberg.org. Was it not the great philosopher and mathematician Leibnitz who said that the more knowledge advances the more it becomes possible to condense it into little books? Now this "Outline of Science" is certainly not a little book, and yet it illustrates part of the meaning of Leibnitz's wise saying. For here within reasonable compass there is a library of little books--an outline of many sciences. What then is the aim of this book? It is to give the intelligent student-citizen, otherwise called "the man in the street," a bunch of intellectual keys by which to open doors which have been hitherto shut to him, partly because he got no glimpse of the treasures behind the doors, and partly because the portals were win 7 | The Project Gutenberg EBook of The Outline of Science. This eBook is for the use of anyone anywhere at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this eBook or online at www.gutenberg.org. Was it not the great philosopher and mathematician Leibnitz who said that the more knowledge advances the more it becomes possible to condense it into little books? Now this "Outline of Science" is certainly not a little book, and yet it illustrates part of the meaning of Leibnitz's wise saying. For here within reasonable compass there is a library of little books--an outline of many sciences. What then is the aim of this book? It is to give the intelligent student-citizen, otherwise called "the man in the street," a bunch of intellectual keys by which to open doors which have been hitherto shut to him, partly because he got no glimpse of the treasures behind the doors, and partly because the portals were win 8 | The Project Gutenberg EBook of The Outline of Science. This eBook is for the use of anyone anywhere at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this eBook or online at www.gutenberg.org. Was it not the great philosopher and mathematician Leibnitz who said that the more knowledge advances the more it becomes possible to condense it into little books? Now this "Outline of Science" is certainly not a little book, and yet it illustrates part of the meaning of Leibnitz's wise saying. For here within reasonable compass there is a library of little books--an outline of many sciences. What then is the aim of this book? It is to give the intelligent student-citizen, otherwise called "the man in the street," a bunch of intellectual keys by which to open doors which have been hitherto shut to him, partly because he got no glimpse of the treasures behind the doors, and partly because the portals were win 9 | The Project Gutenberg EBook of The Outline of Science. This eBook is for the use of anyone anywhere at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this eBook or online at www.gutenberg.org. Was it not the great philosopher and mathematician Leibnitz who said that the more knowledge advances the more it becomes possible to condense it into little books? Now this "Outline of Science" is certainly not a little book, and yet it illustrates part of the meaning of Leibnitz's wise saying. For here within reasonable compass there is a library of little books--an outline of many sciences. What then is the aim of this book? It is to give the intelligent student-citizen, otherwise called "the man in the street," a bunch of intellectual keys by which to open doors which have been hitherto shut to him, partly because he got no glimpse of the treasures behind the doors, and partly because the portals were win 10 | The Project Gutenberg EBook of The Outline of Science. This eBook is for the use of anyone anywhere at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this eBook or online at www.gutenberg.org. Was it not the great philosopher and mathematician Leibnitz who said that the more knowledge advances the more it becomes possible to condense it into little books? Now this "Outline of Science" is certainly not a little book, and yet it illustrates part of the meaning of Leibnitz's wise saying. For here within reasonable compass there is a library of little books--an outline of many sciences. What then is the aim of this book? It is to give the intelligent student-citizen, otherwise called "the man in the street," a bunch of intellectual keys by which to open doors which have been hitherto shut to him, partly because he got no glimpse of the treasures behind the doors, and partly because the portals were win 11 | --------------------------------------------------------------------------------