Pages

Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Thursday, 28 March 2013

Dispatch depending on the condition (JSP. Servlet)

The idea is easy: if condition is true - to show first JSP-page, otherwise - to show second JSP-page.
First of all i have index.jsp which makes a request to a servlet. Then that servlet uses class Client to keep all incoming information and transfers the instance of this Client class as a session's or request's attribute.

Displaying dynamically generated images in a JSP document

My small web application contains 1 java bean - helper class (Model), 2 JSP-pages (Views), 2 servlets (Controlers). First page index.jsp contains the html form to send a request with all requested information to a servlet.

Thursday, 21 March 2013

Servlet: HTML filtering

I took this instance from "Core Servlets and JavaServer Pages" book by Marty Hall and Larry Brown.
This is my text book at the moment.
Here is some code:
The main problem is html-tags.. If you try to print out "a<b" (a less than b) - you will not see any text after < symbol. But the method filter() can replace "<" symbol with "&lt;"  (predefined letters combination):



/** <b - as a html tag:
     if (a<b) {
        doThis();
     } else {
        doThat();
     }
     */
    public static String filter(String input) {
        StringBuilder filtered = new StringBuilder(input.length());
        char c;
        for(int i=0; i<input.length(); i++) {
            c = input.charAt(i);
            if (c == '<') {
                filtered.append("&lt;");
            } else if (c == '>') {
                filtered.append("&gt;");
            } else if (c == '"') {
                filtered.append("&quot;");
            } else if (c == '&') {
                filtered.append("&amp;");
            } else {
                filtered.append(c);
            }
        }
        return(filtered.toString());
    } 

Thursday, 7 March 2013

Servlet. Reading All Request Parameters

Using request.getParameterNames() to get all parameter names.
Using request.getParameterValues(paramName) to get all (multiple) parameter values.

Enumeration paramNames = request.getParameterNames(); //All parameters
while(paramNames.hasMoreElements()) {
                String paramName = (String)paramNames.nextElement();
                String[] paramValues = request.getParameterValues(paramName); //All values
....
}

If the paramValues array has only one entry and contains only one empty string, then the parameter had no values. If the array has more than one entry, then the parameter had multiple values.










An empty String is returned if the parameter exists but has no value, and null is returned if there was no such parameter which name you asked.

Wednesday, 6 March 2013

Servlet. Race condition.


Somewhere in html:

form action="SynchTest" method="POST" name="form1"
input name="SubmitBtn" type="submit" value="SUBMIT"

_______________
public class SynchTest extends HttpServlet {
        Asynch a = new Asynch();

    protected void processRequest(HttpServletRequest request, 
                                  HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        try {
            String title = "SynchTest";
            int y = 40;
            if(a.getValue() > y) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException ex) {
                    out.print(ex.toString());
                }
                a.subtract(y);
            }
            String value = "Value is: " 
                            + String.valueOf(a.getValue()); 
            
            String threadInfo = Thread.currentThread().getName();
            value = value +"\n" + "Thread name is: " + threadInfo;
            out.println(MyHTML_util.getHTML(title,value));
        } finally {            
            out.close();
        }
    }
_____________________

Friday, 22 February 2013

Using enum

All in one place. My examples.

package enumtest;
import java.util.Random;

/**
 * @author Alex Pilugin
 */

enum Numbers{
    ONE,
    TWO,
    THREE,
    FOUR,
    FIVE,
    SIX,
    SEVEN
}

enum Deadlines{
    HOUR,
    DAY,
    WEEK,
    MONTH,
    YEAR;
    int count = 0;
    Deadlines(){
        count++;
    }
}

Thursday, 21 February 2013

SCJP exam. The most common "Compilation fails" questions-2

no default constructor in a superclass

class One{
    String s;
    One(String s){
        this.s = s;
    }
}
class Two extends One{
    Two(String s){
                   // problem 
        this.s = s;
    }
}
interface implementation (method signature)
class Persons{
    String name;
    Persons(String name){
        this.name = name;
    }
    public String toString() {
        return this.name;
    }
}
interface Personable {
    Persons getPerson(String name);
}
class MyPerson implements Personable{
    Persons getPerson(String name) { // problem (must be public)
        return new Persons(name);
    } 
    public static void main(String[] args){
        List ps = new ArrayList();
        MyPerson m = new MyPerson();
        for (int i = 100; i++ < 102; ps.add(m.getPerson("" + i)));
        for(Object o:ps) System.out.println(o);
    }
}

Wednesday, 20 February 2013

SCJP exam. The most common "Compilation fails" questions


Illegal package declaration (looks like import statement).

package com.mypackage.classes.*;  // problem

Out of scope of visibility

class OutOfScopeTest{
    static int x;
    public static void main(String[] args){
        for(int i = 0; i < 10; i++){
            x++;
        }
        System.out.println(x + i); // problem
    }
}

All local variables must be initialized before using.

class LocalVariableTest{
    public static void main(String[] args){
        Boolean b;
        if(b == null){ // problem
            b = false;
        }else{
            b = true;
        }    
    }
}

No enum declaration within any method's scope. 
Enum types must not be local.

class A {
    public static void doStuff(){
        enum Sex {MALE, FEMALE, SHEMALE}; // problem
        Sex sex = Sex.MALE;
    }
}

Sunday, 10 February 2013

Technical Test for PPS applicants. (My own solution)

This is only a task from a recruitment agency.

Technical Test for PPS applicants.

The PPS processor is a simple processing engine that takes a list of numeric instructions processing them and manipulating a stack. The engine processes a list of instructions which form a PPS task. The engine will execute the program and place the results on the stack. The PPS team is very interested in performance so the PPS engine can perform multiple tasks in parallel and has some special instructions to facilitate this.

Instruction Code Number Arguments Description
PUSH 1 1 Pushes the single argument onto the stack
POP 2 0 Removes the value at the top of the stack
DUP 3 0 Duplicates the value at the top of the stack
ADD 4 0 Removes the top two numbers from the stack, adds them and places the result on the stack.
SUBTRACT 5 0 Removes the top two numbers from the stack , Subtracts the top number on the stack from the second number on the stack, placing the result on the stack.
MULTIPLY 6 0 Removes the top two numbers from the stack, multiplies them and places the result on the stack.
DIVIDE 7 0 Removes the top two numbers from the stack , Divides the top number on the stack from the second number on the stack, placing the result on the stack.
ASSIGN_ID 8 0 Take the top value on the stack, removes it and assigns it as an ID to the whole routine. Once given an ID other tasks can reference the result.
PUSH_TASK 9 0 Takes the top number on the stack, removes it and uses it as an identifier to retrieve the result of the task with that identifier, waiting if necessary for the dependant task to complete if not already complete.


Examples
Code sequence gives 
the result
1 2 1 3 4 5
1 5 1 3 5 2
1 20 1 30 6 600
1 20 1 5 7 4

Instruction sequences like the above examples can be batched as parallel tasks and should execute in parallel. This is accomplished by naming tasks with a numeric identifier and referencing them from another task via this identifier. So one sequence or task can take the result of another. It should be possible for a task that uses the output from another to be submitted before its dependency such that it will have to wait until its dependant task is complete before completing.

Parallel Example 
Code sequence gives 
the result
1 100 8 1 2 1 3 4 5
1 200 8 1 4 1 5 4 9
1 100 9 1 200 9 4 14

Write an implementation of the PPS Engine in Java. Your solution should easy to extend as we plan to add new instructions in the future.

 

My solution

According to requirement of good OO design calls to high cohesion i had to create my own classes hierarchy to fulfil this task. It means each class should fulfil its own particular task.

Friday, 8 February 2013

MasterExam (SCJP 6). Sorting with a Comparator

From first attempt I didn't answer correctly. I leave this question for my memories.
Original code example:

package mastertest.sort;
import java.util.Arrays;
import java.util.Comparator;

public class Sort {

    public static void main(String[] args) {
        String [] words = {"Good","Bad", "Ugly"};
        java.util.Comparator<String> best = new Comparator<String>(){
            public int compare(String s1, String s2){
                return s2.charAt(1) - s1.charAt(1);
            }
        };
        Arrays.sort(words,best);
        System.out.println(words[0]);
    }
}

Wednesday, 6 February 2013

My own TableModel (swing)

I think every java beginner encounters with this problem. How to create and to edit a JTable instance. I met this challenge as well. My first approach was simple. It was easy to choose DefaultTableModel 

 
   private static void createTable(){
       DefaultTableModel model = new DefaultTableModel();
       JTable table = new JTable(model);  
       //#1st - table constructor with a TableModel argument 
       //table = new JTable();  
       //#2 - i can add a TableModel later  
       //using setModel(model) method
       //table.setModel(model);

       Vector column1 = new Vector(); /Vector as a table column
       column1.add("data1");
       column1.add(" "); //column1 has two rows
       
       Vector column2 = new Vector();
       column2.add("data2"); //column2 has two rows
       
       model.addColumn("First", column1); 
       //model has maximum number of columns (two) 
       model.addColumn("Second", column2); 
       model.setValueAt("Change", 1, 1);
       
       table.setAutoCreateRowSorter(true); //autosorting
       //table.setSelectionMode(0);
       
   }
 
 

Tuesday, 29 January 2013

my Collections test and something else (key features of Java)

I study and test some basic technologies. I created a few enums with default access modifiers (they can be used in scope of the current package only).

enum Sex {MALE, FEMALE, SHEMALE}
This Sex enum is used to hold the gender of a Person. Of course, it's a only joke.

enum Employment {EMPLOYED, SELFEMPLOYED, UNEMPLOYED};
This enum is used to hold the employment status of a Person.

My public class Person definition:

public class Person implements Serializable, Comparable {
    private long ID;
    private String name;
    private String surname;
    private int age;
    private Sex sex = Sex.FEMALE;
    private Employment vocation = Employment.UNEMPLOYED;
    private File userPic;
...

Thursday, 24 January 2013

Search (metacharacters)

The searching with metacharacters.
/*
 * API: regular-expression constructs 
 * docs.oracle.com
 */

Wednesday, 23 January 2013

Regex - Quantifiers

Quantifiers:
? - zero or one
* - zero or more
+ - one ore more

Regex - Regular Expressions. This is one of the difficult topics for me. Here is one program to show work with quantifiers.

Tuesday, 22 January 2013

My Synchronised Queue

I received this task from one recruiter. His client was looking for a java programmer and they wanted to check my knowledge of Java. I should to create a class that represents a synchronised queue.

Here is my version of a linked synchronised queue. I had to create to inner classes as well.

Friday, 11 January 2013

Thursday, 10 January 2013

my main useful links for Java programmers

http://stackoverflow.com/
http://www.javaranch.com/
http://www.java2s.com/
Java Book: http://www.java2s.com/Book/Java/CatalogJava.htm

SCJP mock test online: http://scjptest.com/
Java Tutorials - Table of Contents: cogeco.ca
Java Examples:  http://www.java-examples.com/

Russians:
http://javatalks.ru/
http://habrahabr.ru/hub/java/

Book publisher:
http://www.apress.com/
http://www.manning.com/
http://oreilly.com/

P.s I am just a newbie for Java programming, and at the moment I spend the most of my spare time to prepare for SCJP. Here are only the main but excellent websites. I'd like to pass the exam and to find work as a java programmer. I help to my friend to solve some tasks in java at times, but at the moment i can solve only 50% of exam's questions.