Monday, 3 January 2022

Eratosthenes Sieve - Prime numbers in Java - Algorithm Example

Eratosthenes Sieve algorithm for checking prime numbers.

Maybe we should first ask, what is prime number?

If one number can be calculated by multiplying any two different numbers then this number is not a prime number (We do not take number 1 into consideration). As example we can take few numbers 3,4,5,9,11.
Number 3 is prime as you can't multiple any other two numbers and get it.
Number 4 is not a prime number as you can get it by multiplying number 2 with 2 and get result as 4.
Number 5 is prime as well, while number 9 is not a prime, as you can get is as result 3*3.
Number 11 is prime as you can't get it as result of multiplying any other two numbers.

You can say, yes, it is easy, and sure it is for smaller numbers, but when you get into 3 digits or even 4 it is bit harder to calculate. 

So how Eratosthenes sieve works.

Lets use number 117 for checking if it is prime number or not. Algorithm starts with simple numbers and multiply them until you get to number you want.
Starts with number 2 and start to calculate, 2*2, 2*3, 2*4, 2*5, 2*6, all results of this multiply will be marked as NOT PRIME in sieve as they are result of multiplying two numbers. We do multply and increasing numbers as long result is less then 117. Then we increase first number, now it is 3, 3*3, 3*4, 3*5, result or multiply are marked as NOT PRIME in sieve... Increasing first number to number 4? Nope, it doesn't use number 4 as it is not prime, and sieve knows it, because we marked it as not prime when we calculated 2*2. Next number will be 5, so 5*2, 5*3, 5*4... and so on, until we reach first number as number 117. At this point, all numbers in seive are marked as NOT PRIME, we should now just checked the sieve and see if our number is prime or not.

Have a look at code below. Algorithm will use same approach and print out if number is prime or not, with limit that user enters.

import java.io.*;

public class EratosthensSievePrimeNumbers {

    // Start of the program
    public static void main(String args[]) throws IOException {

        
        boolean[] sieve; // array to keep track if number is prime or not
                                    //value for each number will be true or false
        int index; // index used in for loops
        int jIndex; // jIndex second index used in for loops
        int limit; // limit for sieve, provided by user
        
        // used to read input from user
        BufferedReader readUserInput = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter limit for prime number search: ");
        limit = Integer.parseInt(readUserInput.readLine());
        sieve = new boolean[limit]; // first: allocate memory

        for (index = 2; index < limit; index++) {
            sieve[index] = true; // setting all numbers as potential prime numbers
        }
        for (index = 2; index < limit; index++){
            if (sieve[index]) {
                for (jIndex = index + index; jIndex < limit; jIndex += index)
                    // exclude all numbers that we are multiplying by index from the list
                    sieve[jIndex] = false;
            } // 2 * i, 3 * i ...
        }
        // Going over list and printing out all prime numbers that still have true as value.
        for (index = 2; index < limit; index++){
            if (sieve[index]){
                System.out.println("Prime number is: " + index);
            }
        }
    }
}

I hope this will be helpful for anyone interested to see how Eratosthenes Sieve works, if you still have any doubts, add a comment with your question and I will try to answer it.

Sunday, 5 February 2017

Can we create Matrix using AI?

Would it be possible for us to create real time world simulation?

We started using super computers with few thousands of processors, unbelievable number of RAM, insane Internet speed, and all that working as one unit.

We use them for predicting climate, solving problems, do different types of simulations, but can they run Matrix?
On first look you could think, ok, how hard it can be?

Let's try to think for few minutes what we need for building Matrix.
For this purpose we will speak in OOP world, so describing what kind of "objects" we need.

First we need "World", he will be filled with "People", "Animals", "Physics rules", "Oceans", "Nature", "Rivers", "Mountains", "Threes", "Cars", "Homes", ... and many other things.
Now you can think, ok, at some point I will create all of them, then you can think what to do next...?

What is the main ingredient for life itself? It's Sun. So we need to map our whole planetary system.
On then add "Sun", "Moon", "Mars" and others...
Create them and just add basic rules, all planets are circling around soon at some speeds, they are spinning at certain speeds, and we did that, perfect.

Now we have light on our planet, hmm, so now what we need is "Climate", some times we have sunny days, some days rain, some days wind, snow,...

Let's assume we did that too, now we have day and night zones, climate, so we can work on photosynthesis because we need oxygen. We did that too, ok, at this point it started to be very complex and we just started.

Let's say everything is done, let us concentrate only at one place, one city, and then on block.
How many people live there? How many streets, shops, jobs, cars, dogs, cats are there?
And you fill all that info, what is left is our SOUL!

We still can't create that good AI to simulate our way of thinking. Our way of getting knowledge, our way of getting friends, every person has something unique and that computer can't simulate. Still...

Best companies in the world didn't even scratch the surface what is our brain capable of.

When we count all necessary things we need to create in Matrix, your brain already started imagine that in your head, all the places, streets, different people, worlds and that machine can't do...

Machines are now just capable to use our data we provide them and manipulate in some sort to get a result we think it is good.
I hope it will stay like that for a long time, because if somebody do create that good program, we will all be without job :)

Let's say in we do create that good AI, what do we need more? Can you imagine how big data centers it will require, just to store memories of 1,000 people? Matrix is still out our reach, and it will take us some time to reach that goal, maybe we will never reach it but who knows, maybe where are we now is only one big simulation...

If you did like our story, and your are looking of more, please subscribe to our blog, post some comments, like us on Facebook, share it and enjoy.

Kind regards,
M.L.

Saturday, 7 January 2017

Lotto Predictions - Java AI

Hello, we want to show you simple AI algorithm and how can he produce some lotto numbers for us.

We created small algorithm, load some numbers that happen before, do some calculations and print out the next 7 numbers winning combination.

First we need to have a way to represent this sequence of 7 numbers.
For example numbers: 37, 2, 11, 15, 14, 22, 1

What we can notice immediately is that we can sort them, it doesn't matter in witch order they arrived on screen, they will still represent combination of 7 numbers. So in our case it is: 1, 2, 11, 14, 15, 22, 37

We can create simple class for that.

Helper class:

public class Numbers {
   
    private final int num1;   private final int num2;   private final int num3;
    private final int num4;   private final int num5;   private final int num6;
    private final int num7;

    public Lotto(int num1, int num2, int num3, int num4, int num5, int num6, int num7) {
        this.num1= num1;   this.num2= num2;   this.num3= num3;
        this.num4= num4;   this.num5= num5;   this.num6= num6;
        this.num7= num7;
    }
    // some getters for this numbers
}
Now we can reuse this helper class and initialize some results we already know.

First we will create some List and some maps, in list we will collect all previous result so it would be easier for us to use them and maps will be created just to remember how many points each number have.

In our case point would be how many time he was in results from before.

Using static block we will populate result list and we can start processing.

Go over result list and populate maps with numbers.
Call print prediction that will go over maps and find best matches.

Take a look at the code:

Main class:

public class Lotto {
    // here we will store all results that we know in advance
    private static List<Lotto> results = new ArrayList<Lotto>();
   
    // we will use this maps to store info for number how many times he already were in results
    private static Map<Integer, Integer> number1 = new HashMap<>();
    private static Map<Integer, Integer> number2 = new HashMap<>();
    private static Map<Integer, Integer> number3 = new HashMap<>();
    private static Map<Integer, Integer> number4 = new HashMap<>();
    private static Map<Integer, Integer> number5 = new HashMap<>();
    private static Map<Integer, Integer> number6 = new HashMap<>();
    private static Map<Integer, Integer> number7 = new HashMap<>();
   
    static { // this will load some results that already were in lottery winners
        Numbers l1 = new Numbers (2, 7, 9, 13, 14, 29, 31);
        Numbers l2 = new Numbers (8, 14, 16, 22, 27, 29, 37);
        Numbers l3 = new Lotto(12, 17, 18, 19, 26, 35, 39);
        Numbers l4 = new Lotto(4, 6, 9, 10, 11, 18, 32);
        Numbers l5 = new Lotto(2, 3, 6, 7, 10, 15, 25);
        Numbers l6 = new Lotto(13, 21, 22, 28, 30, 32, 39);
        Numbers l7 = new Lotto(9, 12, 19, 22, 28, 36, 39);
        Numbers l8 = new Lotto(11, 15, 18, 22, 24, 36, 37);
        Numbers l9 = new Lotto(4, 8, 12, 18, 19, 24, 31);
        Numbers l10 = new Lotto(4, 9, 13, 14, 17, 37, 39);
        // add values to the list          
        results.add(l1);results.add(l2);results.add(l3);results.add(l4);results.add(l5);
        results.add(l6);results.add(l7);results.add(l8);results.add(l9);results.add(l10);
       
    }
   
    // our main program
    public static void main (String [] args) {
        for (Numbers l : results) {
            addNumber(l.getNum1(), number1); addNumber(l.getNum2(), number2);
            addNumber(l.getNum3(), number3); addNumber(l.getNum4(), number4);
            addNumber(l.getNum5(), number5); addNumber(l.getNum6(), number6);
            addNumber(l.getNum7(), number7);
        }
        printPrediction();
    }

    private static void printPrediction() {
        int n1Prediction = findNumber(number1);
        int n2Prediction = findNumber(number2);
        int n3Prediction = findNumber(number3);
        int n4Prediction = findNumber(number4);
        int n5Prediction = findNumber(number5);
        int n6Prediction = findNumber(number6);
        int n7Prediction = findNumber(number7);
       
        System.out.println("Prediction for new lotto result is:");
        System.out.print("Numbers: " + n1Prediction + ", " + n2Prediction
                        + ", " + n3Prediction + ", " + n4Prediction
                        + ", " + n5Prediction + ", " + n6Prediction
                        + ", " + n7Prediction);
    }
   
    // our magic goes here
    private static int findNumber(Map<Integer, Integer> map) {
        int number = -1;
        int value = -1;
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() >= value) {
                number = entry.getKey();
                value = entry.getValue();
            }
        }
        return number;
    }

    // if value exist in map then remove it and add it once again with counter + 1
    private static void addNumber(int num, Map<Integer, Integer> map) {
        if (map.containsKey(num)) {
            int exist = map.get(num).intValue();
            map.remove(num);
            map.put(num, exist + 1);
        } else {
            map.put(num, 1);
        }
    }
   
}


After running this program we get this:
Prediction for new lotto result is:
Numbers: 4, 15, 9, 22, 30, 29, 39

Why did he find that results?

He was checking witch number is most popular to happen on that place and print out that one.
Our logic is fair simple, in order to create something "smarter" you will need better algorithm for this.

Add more results, change method print prediction, count more factors not just 1 and you should get better results, and at one point hit the jackpot!

Until then, please subscribe to our blog, post some comments, like us on Facebook, share it and enjoy.

Kind regards,
M.L.


Saturday, 17 December 2016

Measure Code Speed in Java

How to measure code speed in Java

Quite often we have two solutions in our mind and we don't know which one is the best to use.
Simple way to decide that is to measure speed for executing for both code versions and use one that is faster.

So how we can actually measure the code speed? In Java it is quite easy.

You will need to recognize few key points in your code, when does it starts and when does it ends.

Before beginning your code you will add something like this:
long startTime = System.nanoTime();
This will get the current system time and put it in one variable.

At the end of code you want to measure you need to put:
long totalExecutionTime = System.nanoTime() - startTime ;
This will get current system time at the end of the code and subtract start time we created at the start of the code.

In order to see how fast is it you can just print it to console:
System.out.println("Total execution time: " + (totalExecutionTime / 1000000.0) + " ms");
This code will get the result of subtraction and divide it with 1M, this is done only to get better representation of the result we have. After we divide that, we will print the result and add "ms" at the end that we now result is in milliseconds. 1000 ms is 1 sec.

So we now know how to check the speed of our code, in order to compare it with other code you will do the same for other part:
long startTime2 = System.nanoTime();
... (code you want to measure) ...

long totalExecutionTime2 = System.nanoTime() - startTime2 ;
System.out.println("Total execution time 2: " + (totalExecutionTime2 / 1000000.0) + " ms");

Instead of just printing values you can now compare them:
if ( totalExecutionTime > totalExecutionTime2 ) {
         System.out.println("First code is faster!");
} else if ( totalExecutionTime < totalExecutionTime2 ) {
          System.out.println("Second code is faster!"); 
} else {
          System.out.println("They are equally fast!"); 
}

You can check our code example where we compare String VS String builder using this speed test: String VS StringBuilder
If this little "code" helped you, please subscribe, like us on Facebook, share it and enjoy.

Kind regards,
M.L.

Monday, 21 April 2014

Speed test: String vs StringBuilder in JAVA

We compare String with StringBuilder, run this code and see yourself, example:


public class SpeedTest
{
    public static void main(String[] args)
    {
        final String SAMPLE = "The Quick Brown Fox Jumps Over The Lazy Dog.";
        final int COUNT = 5000;

        // string
        String str = "";
        long start = System.nanoTime();
        for (int i = 0; i < COUNT; i++)
            str += SAMPLE;
        long strTotal = System.nanoTime() - start;
        if (str.length() == 123)
            System.exit(0);

        // StringBuilder
        StringBuilder builder = new StringBuilder(SAMPLE.length() * COUNT);
        start = System.nanoTime();
        for (int i = 0; i < COUNT; i++)
            builder.append(SAMPLE);
        long sbTotal = System.nanoTime() - start;

        System.out.println("String total time: " + (strTotal / 1000000.0)
                + " ms");
        System.out.println("StringBuilder total time: " + (sbTotal / 1000000.0)
                + " ms");
        System.out.println("StringBuilder vs. String: " + (strTotal / sbTotal));
    }

}


If this little "code" helped you, please subscribe, like us on facebook, share it, or do whatever you want with it

Have a good one. M.L.

Friday, 14 March 2014

PHP - Problem with "mysqli" - SQL Database

SQL works in phpmyadmin not in PHP



If your sql code works in phpmyadmin not in php probably main reason for that is in "mysqli" procedure.

"MYSQLi" don't work with "old" version's of PHP so you will not get any error everything will seem fine but nothing will happen.

You are probably connecting to database something like this:

$con=mysqli_connect("host","admin","password","name_of_database");

if (mysqli_connect_errno()) {
       echo "Error, we can't connect to database: " . mysqli_connect_error();
} else {
$sql="INSERT INTO userTable (username, password) VALUES ('$username', '$password');
}

if (!mysqli_query($con,$sql)) {
    echo "Error!";
} else {
    echo "Ok!";    
}
mysqli_close($con);  // we need to close connection to database...

And something is wrong but you don't know what?

Try the same code just with "mysql" function and it will work, so you will need to write something like this:

$sql="INSERT INTO userTable (username, password) VALUES ('$username', '$password');

mysql_connect("host", "admin", "password") or die(mysql_error()); 

mysql_select_db("name_of_database") or die(mysql_error()); 

$data = mysql_query($sql) or die(mysql_error());

 mysql_close();

When I write my code like this, magic happen, my user is inserted to database...

Notice!
"or die(mysql_error())" will make your server to "die" so you will get error and everything will stop if you need to continue just remove that and everything will be ok.

If this little "tutorial" helped you, please subscribe, like us on facebook, share it, or do whatever you want with it. :)

Have a good one. M.L.



Saturday, 8 February 2014

Do you know how simple is programming? Try it yourself. AutoIT

You don't need to be IT expert to write a program, you can write your own programs with this script language:

 

AutoIT



There are a lot of complicated programming languages​​, but there are also simple language that everyone can use, one of them is AutoIT script language.

He is very simple and easy to learn. You can write simple and complicated programs for whatever you need.

How to start with AutoIT? You need to do 1. and 3. step on this link. After that you are ready to write your own programs.

I will show you how to make program to open your CD drive and close it in a loop every 1 minute. :D
We all wanted in some point to be a hackers, this is a closest you can be a hacker without knowing anything about programing.

So how to start? You can do like this, go to your desktop or folder you want to make programs and click right click, from menu select "New" then select AutoIT script. Name it like "CD Drive" or something like that. After you name it, you need to right click on it and click on Edit Script, by default if you just open it i will run script and nothing will be executed because you don't have any code on script.

So we click on Edit Script and now you see Script Editor, all you need to do now is to write your code and use your imagination. :)
We are building CD script, so what do we need? Script gonna be in a loop because we want that CD open's every 1 minute. So how to make a loop?

You can do a loop very easy and intuitive like this:
While 1=1

Wait! What? :D Yes this is a loop, if you think about it loop will do code while condition is correct, in our example 1 is always equal to 1 so our loop will do this always! :)

So how will the loop know where is the end of our code? We need to add this:
WEnd

W - represents while loop and End - end of the loop so every simple for now. :D

Hmm we want to do this loop every 60 second so we need to pause or "sleep" our program for 1 minute, how we gonna do that? Just add this:    sleep(time in millisecond)
So we need to our program sleeps for 60 second, 1 second has 1000 millisecond so we just add sleep method:
while 1=1

sleep(60000)
WEnd

We have our loop who will execute code in every minute in just 3 line of code's :D How cool is that? :)
Now we need to open a CD drive, you can say hmm that is hard, hmm no! Programing is simple because all you need to do is to call method who will do something that we need, so we need method to get CD Drive.

$var = DriveGetDrive( "CDROM" ) 

In this variable called "$var" we get all CD drives on computer, if you think what is this "$" sign means, that is AutoIT thing to say what is variable, you don't need to know anything about that...

So we have all drives in one variable, now we need to open it, so we need to iterate through all cd drive's and open it. We will do it like this:
If not @error Then
For $i = 1 to $var[0]
    CDTray($var[$i] , "open")
Next
EndIf

We first ask is there some kind of error in calling CD Drive's? If not we use for loop to iterate through all CD drives, so if we have 3 drives, with for we go from 1 to 3, we now use 1drive call method to open it: CDTray($var[$i] , "open")When we are finished with first drive we call method Next it will give us next drive, so for loop will now do same thing with second drive, after second is finished we call Next and call it for third drive. So with that 5 lines of codes we open all CD drives on computer. Our code look like this now:

While 1=1

$var = DriveGetDrive( "CDROM" )
If not @error Then
For $i = 1 to $var[0]
    CDTray($var[$i] , "open")
Next
EndIf

sleep(60000)
WEnd

And we finish it :D If you want to close it and after a few second you can use that same code but change "open" to "close" for operation and add sleep between open and close about 20-30 second and you are good. :D

Now we need to create executive program that we can send someone to make a joke with him. :)
In Script Editor menu you have Tools tab, open it and click "Build". That will call AutoIT function to make our program become executive or .exe file. If you don't have any mistakes with your code in your folder or desktop where did you create this script will be file NameOfTheScript.exe and all you need to do now is to zip it or rar it and send it to someone you want to go insane. :P

You can run it on your computer as well, if you want to stop it just use Ctrl+Alt+Delete and kill the program... :) 

This is a tutorial how to make CD Room open's with 10 lines of code and you don't need to be programer to do that. 
If you want to learn more try to read AutoIT documentation or just leave comment bellow and we will make new tutorial how to do similar crazy stuff with AutoIT... :)

If you like this post please like us on Facebook, subscribe, share it, do whatever you want with it... :)
Have a good one. M.L.


Sunday, 2 February 2014

Best algorithms for sorting arrays - Java

Bubble sort, Insertion sort and Selection sort



Which one you will use depends on what do you need. Bubble sort is a simplest algorithm, it will do the job but he will be slow, if you need something faster try Selection Sort and Insertion Sort.

They use different methods of sorting if you want to know how they works read it on this links:

My example of implementation this 3 algorithm's, I add speed test so you will see results which one is the best.
Notice: If you are using algorithms for different things, test it in all 3 algorithms it can give different results.


public class Example {

    public static void insertion_sort (int array[]) {
        long start = System.nanoTime();
        for (int i = 1; i < array.length; i++) {
            int j = i;
            int B = array[i];
            while ((j > 0) && (array[j-1] > B)) {
                array[j] = array[j-1];
                j--;
            }
            array[j] = B;
        }
        long total = System.nanoTime() - start;
        System.out.println("Time needed for sorting: "
                + (total / 1000000.0));
    }

    public static void selection_sort (int array[]) {
        long start = System.nanoTime();
        for (int x = 0; x < array.length; x++) {
            int index_of_min = x;
            for (int y = x; y < array.length; y++) {
                if (array[index_of_min] < array[y]) {
                    index_of_min = y;
                }
            }
            int temp = array[x];
            array[x] = array[index_of_min];
            array[index_of_min] = temp;
        }
        long total = System.nanoTime() - start;
        System.out.println("
Time needed for sorting: "
                + (total / 1000000.0));
    }


    public static void bubble_sort( int a[] ) {
        long start = System.nanoTime();
        int i, j,t=0;
        for (i = 0; i < a.length; i++) {
            for (j = 1; j < (a.length-i); j++) {
                if (a[j-1] > a[j]){
                    t = a[j-1];
                    a[j-1] = a[j];
                    a[j] = t;
                }
            }
        }
        long total = System.nanoTime() - start;
        System.out.println("
Time needed for sorting: "
                + (total / 1000000.0));
    }
   
   
    public static void main (String [] args) {
        int i;
        int array[] = {12,9,3,5,7,9,11,17,22,15,4,99,120,1,3,10};
        System.out.println();
        bubble_sort(array);
        System.out.print("After bubble sort
algorithm:\n");
        for(i = 0; i <array.length; i++)
        System.out.print(array[i]+"  ");
        System.out.println();
       
        int p;
        int array2[] = {12,9,3,5,7,9,11,17,22,15,4,99,120,1,3,10};
        System.out.println();
        selection_sort(array2);
        System.out.print("After selection sort algorithm:\n");
        for(p = 0; p < array2.length; p++)
        System.out.print(array2[p]+"  ");
        System.out.println();
       
        int c;
        int array3[] = {12,9,3,5,7,9,11,17,22,15,4,99,120,1,3,10};
        System.out.println();
        insertion_sort(array3);
        System.out.print("After insertion sort
algorithm:\n");
        for(c = 0; c < array3.length; c++)
        System.out.print(array3[c]+"  ");
        System.out.println();

    }
}


If you see this as useful please subscribe, like it, share it do whatever you want with it.
Have a good one. M.L.


Thursday, 23 January 2014

Easy way to get money with Google Adsense

Google Adsense


I started writing blog last year just for fun, but after a while a see that my audience increases from day to day, I think how can I use that and then I find out for Google AdSense.

Google AdSense is great service for you to earn some extra money. If you have a blog or even your own site you can add AdSense. Trick is that you allow Google to add ads on your website and when someone click on it Google will pay you.

Everything you need to do is to write a post and sign up for AdSense. If Google recognize your potential you can start earning money from your home right now!



You may think that is hard, I need to write post every day, NO! You don't need to write a post every day you can write it every once a week like me. You can write about football, programing, future, past or anything and still earn money.

You don't worry about ads on your website because Google will add it for you for every person who comes on your website or blog. Google analyze person who comes on site and add ads specific to that person.

So if that person are looking for hotels and visit my post about hotel Google will add ads about hotels.
If you are looking for programming code for android Google will add ads about programing, you don't need to worry about that. You just need to relax clear your mind and write.

If you have some kind of adblock you can't see ads on my blog, if you see it you can think about what did you search last 10 days on internet, because ads will be about that.

Ads have different prices it depends from ads, they can be 0.02 cents up to 2.00 euro. You can track your income with easy adsense interface integrate in blog or website.

And to see that I don't write nonsense watch this youtube video about Google Adsense.





If you like this post please subscribe for more news or just like it share it, do whatever you want with it. Have a good one. M.L. :)


Friday, 10 January 2014

Read Email in Java - Android

The easiest way to read email in Java


If you need to read email from Java app you will need mail library. Most famous library for reading email in java is javax.mail.jar and you can find it on this link. That work fine in simple Java app, but if you want to build Android app to read email you will have a big problem. 

There is a problem with mail.jar when you want to build Android app, some classes in mail.jar don't work and when you deploy your android app on phone you will get some error but code is fine. In order to solve that problem you need to use this jar files: activation.jar, additionnal.jar and mail.jar. Javax mail.jar include activation and additional jars but some classes in that jars aren't working in Android so you must download files from this link.

First you say what protocol you gonna use:
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");

Then you open a connection to your server:
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap.gmail.com", "mail@gmail.com", "password");

Open inbox with read_write mode:
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);

If you want you can see how much message you have in inbox:
inbox.getMessageCount();

Get message:
Message msg = inbox.getMessage(inbox.getMessageCount());
 
Write all address:
Address[] in = msg.getFrom();
for (Address address : in) {
    System.out.println("FROM:" + address.toString());
} 
 
Write content of message on console:
Multipart mp = (Multipart) msg.getContent();
BodyPart bp = mp.getBodyPart(0);
 
System.out.println("SENT DATE:" + msg.getSentDate());
System.out.println("SUBJECT:" + msg.getSubject());
System.out.println("CONTENT:" + bp.getContent());


You need to put all that in try block and the code will work from simple Java app to Android app.
If you have any questions or need help with coding post a comment bellow.
And if you like this post please share it. Have a good one.

Friday, 3 January 2014

Component Based Development - CBD - Java EJB 3.1 - Example

Blog platform in EJB 3.1


Assignment!
We need to create EJB layer for a blog site.

Clients communicate with stateful session bean. It is necessary to implement the method for search blogs and method for setting up a new blog.
In the case of passivation of the stateful session bean , we need just before passivation to print a message on the console about session bean is going to be pasive.
Singleton bean keeps customer information (name , username , password ... ) and data on blogs ( text, date , number of like- s) in ArrayList.
Singleton is NOT instantiated immediately upon deployment, but by the first call. By instantiate initialize ArrayList in which data need to be stored.
If we call the method that is used to search, interceptor intercepts that method and he update statistics (number of views for each blog).
Call method to set up a new blog interceptor intercepts that method and he update statistics on the number of blogs set up during the day
The statistic data is stored in the same Singleton which are stored and other information .
All interceptor's is required to be implemented in a separate class.
It is necessary to implement a timer that starting from 1.1.2014 . Every day at 00:00 timer need to print on console how many visit blog's have that day.

Please share this post if you like it.

Singleton Class

import java.util.ArrayList;
import java.util.Date;
import javax.ejb.LocalBean;
import javax.ejb.Singleton;

/**
 * Developed by codeMaker
 */

@Singleton
@LocalBean
public class Baza implements BazaLocal {

    public ArrayList<Klijent> listaKlijenata = new ArrayList<Klijent>();
    public ArrayList<Blog> listaBlogova = new ArrayList<Blog>();
   
    int brojPB = 0;
   
    public int getBrojPB() {
        return brojPB;
    }
    public void setBrojPB(int brojPB) {
        this.brojPB = brojPB;
    }

    public void setListaBlogova(ArrayList<Blog> listaBlogova) {
        this.listaBlogova = listaBlogova;
    }
    public void setListaKlijenata(ArrayList<Klijent> listaKlijenata) {
        this.listaKlijenata = listaKlijenata;
    }
    public ArrayList<Klijent> getListaKlijenata() {
        return listaKlijenata;
    }
    public ArrayList<Blog> getListaBlogova() {
        return listaBlogova;
    }
    public Baza() {
        // TODO Auto-generated constructor stub
        Klijent klijent = new Klijent("Niki", "Re", "user", "pass");
        listaKlijenata.add(klijent);
        Blog blog = new Blog("tekst", new Date());
        listaBlogova.add(blog);
    }
}


SingletonLocal interface

import java.util.ArrayList;
import javax.ejb.Local;

@Local
public interface BazaLocal {
    ArrayList<Klijent> getListaKlijenata();
    ArrayList<Blog> getListaBlogova();
    void setListaBlogova(ArrayList<Blog> lista);
    void setListaKlijenata(ArrayList<Klijent> lista);
    int getBrojPB();
    void setBrojPB(int brojPB);
}


Klijent class

import java.util.ArrayList;

public class Klijent {

    public String ime;
    public String prezime;
    public String username;
    public String pass;
   
    public ArrayList<Blog> listaBlogova;
   
    public Klijent(String ime, String prezime, String username, String pass) {
        this.ime = ime;
        this.prezime = prezime;
        this.username = username;
        this.pass = pass;
        listaBlogova = new ArrayList<Blog>();
    }

    public String getIme() {
        return ime;
    }
    public void setIme(String ime) {
        this.ime = ime;
    }
    public String getPrezime() {
        return prezime;
    }
    public void setPrezime(String prezime) {
        this.prezime = prezime;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPass() {
        return pass;
    }
    public void setPass(String pass) {
        this.pass = pass;
    }
    public ArrayList<Blog> getListaBlogova() {
        return listaBlogova;
    }
    public void setListaBlogova(ArrayList<Blog> listaBlogova) {
        this.listaBlogova = listaBlogova;
    }      
}



Blog class

import java.util.Date;

public class Blog {
  
    public String tekst;
    public Date datum;
    public int brojLajkova;
    public int brojPregleda;
   
    public Blog(String tekst, Date datum) {
        this.tekst = tekst;
        this.datum = datum;
        brojLajkova = 0;
        brojPregleda = 0;
    }
    public String getTekst() {
        return tekst;
    }
    public void setTekst(String tekst) {
        this.tekst = tekst;
    }
    public Date getDatum() {
        return datum;
    }
    public void setDatum(Date datum) {
        this.datum = datum;
    }
    public int getBrojLajkova() {
        return brojLajkova;
    }
    public void setBrojLajkova(int brojLajkova) {
        this.brojLajkova = brojLajkova;
    }
    public int getBrojPregleda() {
        return brojPregleda;
    }
    public void setBrojPregleda(int brojPregleda) {
        this.brojPregleda = brojPregleda;
    }


Stateful bean Blogovanje - Clients communicate with him

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.PrePassivate;
import javax.ejb.Stateful;
import javax.interceptor.Interceptors;

@Stateful
@LocalBean
public class Blogovanje implements BlogovanjeRemote {
   
    @EJB BazaLocal baza;
   
    public Blogovanje() {
        

    }
   
    @Interceptors(PretragaInterceptor.class)
    public String pretraga(String upit) {
        List<Blog> lista = baza.getListaBlogova();
        for (Blog b : lista) {
            String tekst = b.getTekst();
            if (tekst.equalsIgnoreCase(upit)) {
                return "Blog je pronadjen!";
            }
        }
        return "Blog nije pronadjen.";
    }
   
    @Interceptors(PretragaInterceptor.class)
    public String postaviBlog(String username, String pass, String tekstBloga) {
       
        int uspjeh = 0;
        ArrayList<Klijent> lista = baza.getListaKlijenata();
        for(Klijent k : lista) {
            String user = k.getUsername();
            String p = k.getPass();
            if((username.equalsIgnoreCase(user)) && (pass.equalsIgnoreCase(p))) {
                Blog b = new Blog(tekstBloga, new Date());
                ArrayList<Blog> listaBlogova = baza.getListaBlogova();
                listaBlogova.add(b);
                baza.setListaBlogova(listaBlogova);
                k.getListaBlogova().add(b);
                uspjeh++;
            }
        }
        baza.setListaKlijenata(lista);
        if (uspjeh > 0) {
            return "Uspeh";
        } else {
            return "Nismo uspjeli da postavimo blog, user i pass ne odgovaraju!";
        }
    }
   
    @PrePassivate
    public void prijePasiviziranja() {
        System.out.println("Jagoda u supermarketu.");
    }
}


BlogovanjeRemote interface - For session bean
Methods in this class will be visible for clients

import javax.ejb.Remote;

@Remote
public interface BlogovanjeRemote {
    String pretraga(String upit);
    String postaviBlog(String username, String pass, String tekstBloga);
}



Interceptors in one class you can build it in seperate classes.

import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

public class PretragaInterceptor {
   
    @EJB BazaLocal baza;
   
    @AroundInvoke
    public Object brojPregledaStatistika(InvocationContext ic) throws Exception {
       
        String imeMetoda = ic.getMethod().getName();
       
        if (imeMetoda.equalsIgnoreCase("pretraga")) {
        Object [] listaO = ic.getParameters();
        String upit = (String) listaO[0];
       
        List<Blog> lista = baza.getListaBlogova();
        for (Blog b : lista) {
            String tekst = b.getTekst();
            if (tekst.equalsIgnoreCase(upit)) {
                b.setBrojPregleda(b.getBrojPregleda() + 1);
            }
        }
       
        return ic.proceed();
        }
       
        if (imeMetoda.equalsIgnoreCase("postaviBlog")) {
           
            Object [] listaO = ic.getParameters();
            String username = (String) listaO[0];
            String pass = (String) listaO[1];
           
            ArrayList<Klijent> lista = baza.getListaKlijenata();
            for(Klijent k : lista) {
                String user = k.getUsername();
                String p = k.getPass();
                if((username.equalsIgnoreCase(user)) && (pass.equalsIgnoreCase(p))) {
                    baza.setBrojPB(baza.getBrojPB() + 1);
                }
            }
            return ic.proceed();
        }
        return ic.proceed();
    }   
}


Timer class

import java.text.SimpleDateFormat;
import java.util.Date;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.TimerService;

@Startup
@Singleton
@LocalBean
public class IspisTimer {

    @EJB BazaLocal baza;
    @Resource TimerService ts;
   
    @Timeout
    public void ispsi() {
        System.out.println("Danas je postavljeno: " + baza.getBrojPB() + " blogova!");
        baza.setBrojPB(0);
    }
   
    @PostConstruct
    public void startuj(){
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm");
        Date date = null;
        try {
            date = sdf.parse("31-12-2013 23:59");
        } catch (Exception e) {    }
        ts.createTimer(date, 86400000, null);
    }
}



And Klijent app, so we can test it.

import java.util.Hashtable;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import binovi.Blogovanje;
import binovi.BlogovanjeRemote;

public class Klijent {

    static Context initialContext;

    public static void main(String[] args) {
        try {
            Context context = getInitialContext();
            String name = getLookUpName();
            BlogovanjeRemote bean = (BlogovanjeRemote) context.lookup(name);
            System.out.println();
            System.out.println(bean.postaviBlog("user", "pass", "text"));
            System.out.println(bean.postaviBlog("ssa2", "agawa", "text"));
            System.out.println(bean.pretraga("text"));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getLookUpName() {

        String appName = "";
        String moduleName = "Blogovanje";
        String distinctName = "";
        String beanName = Blogovanje.class.getSimpleName();
        String interfaceName = BlogovanjeRemote.class.getName();

        String name = "ejb:" + appName + "/" + moduleName + "/" + distinctName
                + "/" + beanName + "!" + interfaceName+"?stateful";

        System.out.println(name);

        return name;
    }

    public static Context getInitialContext() {
           if (initialContext == null) {
            try {
                final Hashtable jndiProperties = new Hashtable();
                jndiProperties.put(Context.URL_PKG_PREFIXES,
                        "org.jboss.ejb.client.naming");
                initialContext = new InitialContext(jndiProperties);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return initialContext;
    }
}


If you have any questions or need help with coding post a comment bellow.
Please share this post if you like it.

Thursday, 2 January 2014

Fast screen capture in Java - Example

 Read pixels from screen in Java


If you want to fast read pixels from screen you will need Java class called Robot.
The main purpose of class Robot is to generate native system inputs (mouse, keyboard inputs) for the purpose of test automation. 

If you need to read pixels from screen you can use Robot method called getPixelColor(int x, int y) x and y represents coordinates of pixels you want to grab. Method getPixelColor(...) returns object Color so if you need to now RGB you must use color.getBlue(), color.getGreen(), color.getRed();

This method is good if you want to read 2-3 pixels but if you need to reed a 10x10 pixels from screen i don't recommend using it. Main reason is because getPixelColor is slow, first you read pixel that you create object Color and then you can work with that pixel.

If you want to read 10x10 pixels from screen or more you can use Robot's method called createScreenCapture(Rectangle r); that method returns BufferedImage. First you may think why is he taking Rectangle and returns a image? Method createScreenCapture(...) need to know from which coordinates he must start (x,y) and how much weight and height go right and down.

So you get something like this:
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(new Rectangle(100, 100, 10, 10));

So you can easy capture 10x10 pixels from screen in one line of code, if you want to use getPixelColor in a loop to do that you will need 2 or 3 second for that. (that's a lot!!!)

When you have BufferedImage you can easy save it like "bmp":
ImageIO.write(image, "bmp", new File("Image.bmp"));

If you want to work with pixels you get in BufferedImage you can do it like this:
boolean fail = false;
for (int x = 0; !fail  && x < image.getHeight();  x++) {
                for (int y = 0; !fail  &&  y <
image.getWidth(); y++) {
                    if ( image.getRGB(x, y) != color.getRGB() ) {
                        System.out.println("Pixels are different stop!");
                        fail = true;
                        }
                    }
           }

}
color.getRGB() returns just one color if you need to check are two pictures the same you can use:
if ( image.getRGB(x, y) != image2.getRGB(x, y) 
So if pixels on x, y position on image and image2 are different we stop and write message for that, if we don't get that message fail will stay on false and we can after all this add this:
if (!fail) {
  System.out.println("Pictures are equal!");
}

Robot is powerful class, you can click mouse, keyboard or read pixels from screen.
If you want to learn more about Robot class you can read Java documentation on this link.

If you have any questions or need help with coding post a comment bellow.
And if you like this post please share it. :)

Sunday, 19 May 2013

IS2 - JSP Pages and Servlet - Examples

Napomena!
JSP stranice zbog ustede na prostoru ubacicemo samo tag "body", jedan primjer zaglavlja i kod nece biti fino formatiran

Iz servleta cemo izbaciti import i dio generickog koda

Zaglavlje JSP stranica...
If you want to translate this code to HTML 5 you need to write Docture type like this <!DOCTYPE html> 

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" %>
    <%@ page isELIgnored="false"  %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>

ZADUZENJE CLANA JSP

 <body>
<c:if test="${!empty clan}">
<form action="/library/GetSlobodniPrimerciZaNaslov">
<table>
<tr><td>Clanski broj:</td><td>${clan.clanskiBroj}</td></tr>
<tr><td>Ime:</td><td>${clan.ime}</td></tr>
<tr><td>Prezime:</td><td>${clan.prezime}</td></tr>
<tr><td>Kategorija:</td><td>${clan.kategorija.nazivkategorije}</td></tr>
</table>
<br><br><br>
Naslov knjige za zaduzenje: <input name="naslovFind" type="text"> <input type="submit" value="Nadji">
</form>
<c:if test="${!empty primerci}">
<table>
<thead><td>Naslov</td><td>Autor</td><td>Godina izdanja</td><td>Inventarni broj</td><td>Zaduzi</td></thead>
<c:forEach var="primerak" items="${primerci}">
<tr><td>${primerak.knjiga.naslov}</td><td>${primerak.knjiga.autor}</td><td>${primerak.knjiga.godinaIzdanja}</td>
<td>${primerak.invBroj}</td><td><a href="/library/ZaduziClana?invBroj=${primerak.invBroj}">Zaduzi</a></td></tr>
</c:forEach </table> </c:if> </c:if> </body>

RAZDUZI CLANA JSP

<body>
<c:if test="${!empty clan}">
<table>
<tr><td>Clanski broj:</td><td>${clan.clanskiBroj}</td></tr>
<tr><td>Ime:</td><td>${clan.ime}</td></tr>
<tr><td>Prezime:</td><td>${clan.prezime}</td></tr>
<tr><td>Kategorija:</td><td>${clan.kategorija.nazivkategorije}</td></tr>
</table> <br> Nerazduzena zaduzenja <br><br>
<table border=1>
<thead><td>Datum zaduzenja</td><td>Inventarni broj</td><td>Naslov knjige</td></thead>
<c:forEach var="zaduzenje" items="${clan.zaduzenjes}" >
<c:if test="${empty zaduzenje.datumVracanja}">
<tr><td>${zaduzenje.datumZaduzenja}</td><td>${zaduzenje.primerak.invBroj}</td>
<td>${zaduzenje.primerak.knjiga.naslov}</td><td><a href="/library/RazduziClana?idZad=${zaduzenje.id}">Razduzi</a></td></tr>
</c:if> </c:forEach> </table> </c:if> </body>

FIND CLANA JSP

<body>
<form action="/library/ReturnClanForClanskiBroj?action=zaduzi" method="post">
Clanski broj: <input name="clanskiBroj" type="text">
<input type="submit">
</form> </body>

SHOW SVE KNJIGE JSP

<body>
<table border=1>
<thead><td>Naslov</td><td>Autor</td><td>Izdavac</td><td>Godina</td></thead>
<c:forEach var="knjiga" items="${sveKnjige}">
<tr><td>${knjiga.naslov}</td>
    <td>${knjiga.autor}</td>
    <td>${knjiga.izdavac}</td>
    <td>${knjiga.godinaIzdanja}</td></tr>
</c:forEach> </table> </body>

PRINT MESSAGE JSP

<html> <head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head> <body>
${poruka}
</body> </html>

SHOW ZADUZENJA JSP

<body> <table>
    <tr><td>ID Clana</td><td><input value="${clbroj}" name="id2" type="text"></td></tr>
    <tr><td>Ime</td><td><input value="${ime}" name="ime" type="text"></td></tr>
    <tr><td>Prezime</td><td><input value="${prz}" name="prezime" type="text"></td></tr>
</table> ${poruka} <table>
    <tr><td>Inv. Broj</td><td>Naslov</td><td>Autor</td><td>Razduzi</td><tr>
    <c:forEach var="zad" items="${zaduzenja}">
    <tr><td><div>${zad.primerak.invBroj}</div></td><td><div>${zad.primerak.knjiga.naslov}</div></td><td><div>${zad.primerak.knjiga.autor}</div></td><td><a href="/library/RazduziClana?id=${zad.id}">Link</a></td><tr>
    </c:forEach> </table> </body>


SERVLET


GET SVE KNJIGE / GET BOOKS

@WebServlet("/GetSveKnjigeServlet")

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        KnjigaManager kmg = new KnjigaManager();
        List<Knjiga> sveKnjige = kmg.listKnjige();
        request.setAttribute("sveKnjige", sveKnjige);
        RequestDispatcher rd = getServletContext().getRequestDispatcher("/izvestaji/prikaziSveKnjige.jsp");
        rd.forward(request, response);       
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

RAZDUZI CLANA

@WebServlet("/RazduziClana")

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idZaduzenja = request.getParameter("idZad");
        ZaduzenjeManager zm = new ZaduzenjeManager();
        Zaduzenje z = zm.getZaduzenjeForId(Integer.parseInt(idZaduzenja));       
        boolean ok = zm.razduziZaduzenje(z);
        ClanManager cmg = new ClanManager();
        Clan clan = cmg.getClanAndZaduzenjesForId(z.getClan().getClanskiBroj());
        request.setAttribute("clan", clan);
        RequestDispatcher rd = getServletContext().getRequestDispatcher("/zaduzenja/RazduzivanjeClana.jsp");
        rd.forward(request, response);
  }



SNIMANJE CLANA / SAVE CLAN (USER)

 @WebServlet("/SnimanjeClanaServlet")

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String clanskiBroj = request.getParameter("clanskiBroj");
        String ime = request.getParameter("ime");
        String prezime = request.getParameter("prezime");
        String adresa = request.getParameter("adresa");
        //datumi
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String datumRodjenjaStr = request.getParameter("datumRodjenja");
        String datumUpisaStr = request.getParameter("datumUpisa");
        String idKategorije = request.getParameter("kategorija");
        KategorijaManager kmg = (KategorijaManager)request.getSession().getAttribute("kategorijaManager");
           String poruka;
            try {
            Date datumRodjenja = sdf.parse(datumRodjenjaStr);
            Date datumUpisa = sdf.parse(datumUpisaStr);
            ClanManager cmg = new ClanManager();
            Kategorija kat = kmg.getKategorijaForId(Integer.parseInt(idKategorije));
            boolean ok = cmg.saveClan(Integer.parseInt(clanskiBroj), ime, prezime, adresa, datumRodjenja, datumUpisa, kat);
            if(ok)
                poruka = "Clan je uspesno sacuvan.";
            else
                poruka = "Doslo je do greske. Clan nije sacuvan.";           
          } catch (ParseException e) {
            poruka="Clan nije sacuvan. Neispravan format datuma.";
        }catch(NumberFormatException ex){
            poruka = "Clan nije sacuvan. Neispravan format broja.";
        }
        request.setAttribute("poruka", poruka);
        RequestDispatcher rd = getServletContext().getRequestDispatcher("/unos/unosClana.jsp");
        rd.forward(request, response);
    }

SNIMANJE KNJIGE / SAVE BOOK IN DATABASE

@WebServlet("/SnimanjeKnjigeServlet")

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idKnjige = request.getParameter("idKnjige");
        String naslov = request.getParameter("naslov");
        String autor = request.getParameter("autor");       
        String izdavac = request.getParameter("izdavac");
        String godinaIzdanja = request.getParameter("godinaIzdanja");
        KnjigaManager kmg = new KnjigaManager();
        Knjiga k = kmg.createAndStoreKnjiga(Integer.parseInt(idKnjige), naslov, autor, godinaIzdanja, izdavac);       
        String forwardPageURL= "/unos/unosKnjigeJSP.jsp";;
        if(k!=null){
            request.setAttribute("poruka", "Knjiga je uspesno sacuvana.");           
          }else{           
            request.setAttribute("poruka","Doslo je do greske, knjiga nije sacuvana.");
          }
         RequestDispatcher rd = getServletContext().getRequestDispatcher(forwardPageURL);
        rd.forward(request, response);   
        }

UNOS PRIMJERKA / INSERT NEW COPY OF SINGLE BOOK

@WebServlet("/UnesiPrimjerak")

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String broj = request.getParameter("broj");
        int idK = (int) request.getSession().getAttribute("idKnjige");
        int br = Integer.parseInt(broj);
        KnjigaManager k = new KnjigaManager();
        List p = k.addPrimeraks(idK, br);
        String poruka = "";
        if (p.size() > 0) {
            poruka = "Success...";
        }
        else {
            poruka = "Error";
        }
        request.setAttribute("poruka", poruka);
        request.setAttribute("lista", p);
        request.setAttribute("brojInv", p.size());
        RequestDispatcher rd = getServletContext().getRequestDispatcher("/UnosPodataka/Izvjestaj.jsp");
        rd.forward(request, response);
    }



NOVI KOD


 JavaBEAN - Vraca sve kategorije / GET ALL CATEGORIES

public class SveKategorijeBean  {
    private List<Kategorija> sveKategorije = null;
    public SveKategorijeBean() {
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();
            sveKategorije = session.createQuery("from Kategorija").list();
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }    public List<Kategorija> getSveKategorije() {
        return sveKategorije;
    } public void setSveKategorije(List<Kategorija> sveKategorije) {
        this.sveKategorije = sveKategorije;
    }
}

PRIMJER HTML - 5 Komponenta za DATUM ujedno i UNOS CLANA JSP stranica, Poziv SveKateforijeBEAN klasa koju smo napravili da bi njenim pozivom vec iz baze izvadili sve kategorije...
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Unos Clana</title>
</head>
<jsp:useBean id="sveKategorije" class="rs.ac.uns.dmi.is2.managers.SveKategorijeBean" scope="session"></jsp:useBean>
<body>
<form action="../SnimajClana" method="post">
<table>
    <tr><td>Ime</td><td><input name="ime" type="text"></td></tr>
    <tr><td>Prezime</td><td><input name="prezime" type="text"></td></tr>
    <tr><td>Adresa</td><td><input name="adresa" type="text"></td></tr>
    <tr><td>Kategorija</td>
        <td><select name="Kategorije">
        <c:forEach items="${sveKategorije.sveKategorije}" var="kat">
        <option value="${kat.idkategorije}">${kat.nazivkategorije} </option>
        </c:forEach>
        </select></td></tr>
    <tr><td>Datum upisa</td><td><input type="date" name="datumUpisa"></input> </td></tr>
    <tr><td>Datum rodjenja</td><td><input type="date" name="datumRodjenja"></input> </td></tr>
</table>
<input type="submit" value="Sacuvaj">
</form> ${poruka} </body> </html>


 INSERT NEW BOOK JSP

<body>
<form action="../SnimanjeKnjige" method="post">
    <table> <tr>
    <td>Naslov</td><td><input name="naslov" type="text"></td></tr>
    <tr><td>Autor</td><td><input name="autor" type="text"></td></tr>
    <tr><td>Izdavac</td><td><input name="izdavac" type="text"></td></tr>
    <tr><td>Godina Izdanja</td><td><input name="godinaIzdanja" type="text"></td></tr>
    </table>    <input type="submit" value="Sacuvaj">
</form> </body>

 SERVLET

AZURIRAJ CLANA Servlet

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idString = request.getParameter("id");
        int id = Integer.parseInt(idString);
        ClanManager cr = new ClanManager();
        Clan c = cr.getClan(id);
        request.setAttribute("clbroj", id);
        request.setAttribute("clan", c);
        RequestDispatcher rd = getServletContext().getRequestDispatcher("/UnosPodataka/AzurirajClana.jsp");
        rd.forward(request, response);
    }

Example using SESSION! // EXAMPLE HOW TO USE SESSION

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idString = request.getParameter("id");
        int clBr = Integer.parseInt(idString);
        ClanManager cm = new ClanManager();
        List<Zaduzenje> lista = cm.getNerazduzenaZaClanskiBroj(clBr);
        Clan c = cm.getClan(clBr);
        request.getSession().setAttribute("clbroj", clBr);
        request.getSession().setAttribute("ime", c.getIme());
        request.getSession().setAttribute("prz", c.getPrezime());   
        request.setAttribute("zaduzenja", lista);
        RequestDispatcher rd = getServletContext().getRequestDispatcher("/UnosPodataka/PrikazZaduzenja.jsp");
        rd.forward(request, response);     
    }

UPDATA CLANA // UPDATE USER

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String cl = request.getParameter("id2");
        int clanskiBroj = Integer.parseInt(cl);
        String Ime = request.getParameter("ime");
        String Prezime = request.getParameter("prezime");
        String Adresa = request.getParameter("adresa");
        String kat = request.getParameter("Kategorije");
        int br = Integer.parseInt(kat);
        String datumcic = request.getParameter("datumRodjenja");
        System.out.println(datumcic);
        Date datum1 = null;
        try {
            datum1 = sdf.parse(datumcic);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        ClanManager cc = new ClanManager();
        Kategorija kategorija = cc.getKategorija(br);
        int rez = cc.updateClan(clanskiBroj, Ime, Prezime, Adresa, kategorija, datum1);
        String poruka = "";
        if (rez == 0) {
            poruka = "Clan nije updejtovan";
        }
        else {
            poruka = "Clan je updejtovan!";
        }
        request.setAttribute("poruka", poruka);
        RequestDispatcher rd = getServletContext().getRequestDispatcher("/UnosPodataka/AzurirajClana.jsp");
        rd.forward(request, response);
    }


COMBO BOX!!! Profesorica je rekla da moze da dodje nesto da moramo da stavimo npr. da je nesto oznaceno u Combo Box-u i evo jedan primjer JSP stranice koja to radi...
Pitamo da li je to sto nama treba ako jeste postavi ga na selected.

<body>
<form action="/library/AzurirajClana" method="post">
<table>
<tr><td>ID Clana</td><td><input name="id" type="text"></td></tr>
</table>
<input type="submit" value="Uzmi Clana">
</form>
<form action="/library/UpdateClana" method="post">
<table>
    <tr><td>ID Clana</td><td><input value="${clbroj}" name="id2" type="text"></td></tr>
    <tr><td>Ime</td><td><input value="${clan.ime }" name="ime" type="text"></td></tr>
    <tr><td>Prezime</td><td><input value="${clan.prezime }" name="prezime" type="text"></td></tr>
    <tr><td>Adresa</td><td><input value="${clan.adresa }" name="adresa" type="text"></td></tr>
    <tr><td>Kategorija</td>
        <td><select name="Kategorije">
        <c:forEach items="${sveKategorije.sveKategorije}" var="kat">
        <c:choose>
              <c:when test="${clan.kategorija.idkategorije == kat.idkategorije}">
                <option selected="selected" value="${kat.idkategorije}">${kat.nazivkategorije} </option>
              </c:when>
              <c:otherwise>
                  <option value="${kat.idkategorije}">${kat.nazivkategorije} </option>
              </c:otherwise>
        </c:choose>
        </c:forEach>
        </select></td></tr>

    <tr><td>Datum upisa</td><td><input value="${clan.datumUpisa}" type="date" name="datumUpisa"></input> </td></tr>
    <tr><td>Datum rodjenja</td><td><input value="${clan.datumRodjenja}" type="date" name="datumRodjenja"></input> </td></tr>
</table>
<input type="submit" value="Sacuvajte Clana">
</form>
${poruka}
</body>




Novi DIO



<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="/library/GetZaduzenje?by=invBroj">
<input type="text" name="invBroj">
<input type="submit" value="Ucitaj">
</form>
<c:if test="${!empty zaduzenja}">
<table border=1>
<thead><td>Datum zaduzenja</td><td>Inventarni broj</td><td>Naslov</td><td>Ime i prezime</td></thead>
<c:forEach var="zad" items="${zaduzenja}">
<tr><td>${zad.datumZaduzenja}</td><td>${zad.primerak.invBroj}</td><td>${zad.primerak.knjiga.naslov}</td>
<td>${zad.clan.ime} ${zad.clan.prezime}</td></tr>
</c:forEach>
</table>
<br><br>
<form action="/library/RazduziZaduzenja">
<input type="text" name="datumRazduzenja" value='<fmt:formatDate pattern="yyyy-MM-dd" value="<%= new java.util.Date() %>"/>'>
<input type="submit" value="Razduzi">
</form>
</c:if>
</body>
</html>


JOS JEDAN


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" isELIgnored="false"%>
 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 <jsp:useBean id="kategorijaManager" class="rs.ac.uns.dmi.is2.manager.KategorijaManager" scope="session"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="/library/ReturnClanForClanskiBroj?action=promenaKategorije" method="post">
Clanski broj: <input name="clanskiBroj" type="text">
<input type="submit" value="Nadji clana">
</form>
Selektovani clanovi: <br><br>
<table border=1>
<thead><td>Ime</td><td>Prezime</td><td>Kategorija</td></thead>
<c:forEach var="clan" items="${clanovi}">
<tr><td>${clan.ime}</td><td>${clan.prezime}</td><td>${clan.kategorija.nazivkategorije}</td></tr>
</c:forEach>
</table>
<br>
Nova kategorija: <br>
<form action="/library/PromenaKategorija">
<select name="kategorija">
<c:forEach var="kat" items="${kategorijaManager.sveKategorije}">
<option value="${kat.idkategorije}" >${kat.nazivkategorije}</option>
</c:forEach>
</select>
<input type="submit" value="Promeni">
</form>

</body>
</html>


JOS JEDAN


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>  
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sve knjige</title>
</head>
<body>
<table border=1>
<thead><td>Naslov</td><td>Autor</td><td>Izdavac</td><td>Godina</td></thead>
<c:forEach var="knjiga" items="${sveKnjige}">
<tr><td>${knjiga.naslov}</td>
<td>${knjiga.autor}</td>
<td>${knjiga.izdavac}</td>
<td>${knjiga.godinaIzdanja}</td></tr>
</c:forEach>
</table>
</body>
</html>

NOVI


<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
Primerci:<br>
<c:forEach var="primerak" items="${knjiga.primeraks}">
${primerak.invBroj}<br>

</c:forEach>

</body>
</html>

UNOS PRIMJERKA


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page isELIgnored="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Unos primeraka knjige</title>
</head>
<body>
${message}
<table>
<tr><td>Naslov:</td><td>${knjiga.naslov}</td></tr>
<tr><td>Autor:</td><td>${knjiga.autor}</td></tr>
<tr><td>Izdavanje:</td><td>${knjiga.izdavac} (${knjiga.godinaIzdanja})</td></tr>
</table>
<br>

<form action="/library/DodajPrimerakKnjiga" method="post">
Dodaj primerak <br><br>
Inventarni broj <input name="invBroj" type="text">
<input type="submit" value="Dodaj">
</form>
<br><br>
<%@ include file="../izvestaji/prikaziPrimerkeKnjige.jsp" %>
</body>
</html>

NADJI CLANA



<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" isELIgnored="false"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="/library/ReturnClanForClanskiBroj?action=${param.action}" method="post">
Clanski broj: <input name="clanskiBroj" type="text">
<input type="submit">
</form>

</body>
</html>


Servlet for Jasper reports!

// This is a list of values that I want to send to servlet
List<Radnik> radnici = RadnikManager.getSviRadnici();
        HashMap<String, Object> params = new HashMap<String, Object>();
        ServletContext context = this.getServletContext();       
        String reportsDirectory = context.getRealPath("/") + "/WEB-INF/classes/reports/";
        String jasperFile = reportsDirectory+"SviRadnici.jasper";
        JasperPrint jasperPrint = null;
        try{
        if(radnici.size()==0){ // ask is list have nothing inside
            JREmptyDataSource dataSource = new JREmptyDataSource();
            jasperPrint = JasperFillManager.fillReport(jasperFile,params, dataSource);
        }else{ // create a repoert
            JRDataSource dataSource = new JRBeanCollectionDataSource(radnici);
            jasperPrint = JasperFillManager.fillReport(jasperFile,params, dataSource);
        }
        ServletOutputStream servletOutputStream = response.getOutputStream();
// this will create pdf report
        JRPdfExporter pdfExporter = new JRPdfExporter();
           
        pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        pdfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM,servletOutputStream);
           
           
        pdfExporter.exportReport();
           
            response.setContentType("application/pdf");
           
            servletOutputStream.flush();
            servletOutputStream.close();
        }catch(Exception e){
            e.printStackTrace();
        }