Monday, May 31, 2021

Secure code guideline

 

https://www.oracle.com/technetwork/java/seccodeguide-139067.html

The language is type-safe, and the runtime provides automatic memory management and bounds-checking on arrays. 

Java programs and libraries check for illegal state at the earliest opportunity. These features also make Java programs highly resistant to the stack-smashing [4] and buffer overflow attacks possible in the C and to a lesser extent C++ programming languages. The explicit static typing of Java makes code easy to understand (and facilitates static analysis), and the dynamic checks ensure unexpected conditions result in predictable behavior.

 

To minimize the likelihood of security vulnerabilities caused by programmer error, Java developers should adhere to recommended coding guidelines.

Effective Java [6], provide excellent guidelines related to Java software design. 

Software Security: Building Security In [7], outline guiding principles for software security.

These guidelines are of interest to all Java developers, whether they create trusted end-user applications, implement the internals of a security component, or develop shared Java class libraries that perform common programming tasks. Any implementation bug can have serious security ramifications and could appear in any layer of the software stack.

 

In order to reduce errors,

 duplication should be minimized and

resource handling concerns should be separated. 

 

4 Accessibility and Extensibility

The task of securing a system is made easier by reducing the "attack surface" of the code.

 

Guideline 4-2 / EXTEND-2: Limit the accessibility of packages

This example code demonstrates how to append to the package.access security property. Note that it is not thread-safe. This code should generally only appear once in a system.

        private static final String PACKAGE_ACCESS_KEY = "package.access";

        static {

            String packageAccess = java.security.Security.getProperty(

                PACKAGE_ACCESS_KEY

            );

            java.security.Security.setProperty(

                PACKAGE_ACCESS_KEY,

                (

                    (packageAccess == null ||

                     packageAccess.trim().isEmpty()) ?

                    "" :

                    (packageAccess + ",")

                ) +

                "xx.example.product.implementation."

            );

        }

 

When confirming an object's class type by examining the java.lang.Class instance belonging to that object, do not compare Class instances solely using class names (acquired via Class.getName), because instances are scoped both by their class name as well as the class loader that defined the class.

Guideline 6-2 / MUTABLE-2: Create copies of mutable output values

To create a copy of a trusted mutable object, call a copy constructor or the clone method:

        public class CopyOutput {
            private final java.util.Date date;
            ...
            public java.util.Date getDate() {
                return (java.util.Date)date.clone();
            }
        }

 

To create a copy of an untrusted mutable object, call a copy constructor or creation method:

        public final class CopyMutableInput {
            private final Date date;
 
            // java.util.Date is mutable
            public CopyMutableInput(Date date) {
                // create copy
                this.date = new Date(date.getTime());
            }
        }

 

 

Excel - sample tute

1.       Create Excel

2.       Add values to cell as a table

3.       Save in different formats

4.       Create a Table

5.       Sort table

6.       Reference values from a different sheet

7.       Add chart

8.       Load data from different files

9.       Formulas – create own formulas

10.   Functions

a.       Date and time Functions

                                                               i.      06-12-2016       

                                                             ii.      Take YEAR,MONTH,DAY () functions

1.       Need date to be in correct format

2.       Else won’t work

                                                           iii.      Add number of days  à Cell value +5

                                                           iv.      Add number of Years, Months, days to date . Use DATE() function

1.       =DATE(YEAR(B14)+4,MONTH(B14)+5,DAY(B14)+3)

                                                             v.      Get current date

1.       Now()

                                                           vi.      Get components of time HOUR(),MINUTE(), SECOND()

                                                          vii.      Add hour, minute, second to date or time. Use TIME() function

1.       TIME(HOUR(B24)+2,MINUTE(B24)+2,SECOND(B24+3))

11.   Print file – collate

a.       How you print , when you print few sets.

b.       Eg: let’s say you print 4 sets.

                                                               i.      Whether one after the other set or

                                                             ii.      Print page 1, 4 times and page 2 four times….. like that

12.   String manipulations

a.       Concatenate two strings , with &

b.       Extract left most , Right most characters LEFT(cell, number), RIGHT(..)

c.       From middle , =MID(E37,2,5) – get a range of 5 characters starting from position 2

d.       Get  length, =LEN(E37)

e.       Find the position of a string =FIND("Th",E37)

f.        Substitute =SUBSTITUTE(E37,"Tharindu","Jones")

13.   Stat functions

a.       AVERAGE, AVERAGEOF, Median,MODE, Std deviation (stddev(),

b.       min, max, large small

 








 https://www.excel-easy.com/functions.html

Sample Questions

 

Introduction to Computers

1.       What is a computer ?

2.       What are the Functionalities of a computer ?

3.       What is meant by Computer classification ? How do you classify ?  Explain with examples

4.       What are the Characteristics of  a Computer ?

5.       Explain Data, Information and Knowledge

6.       What is a computer Virus ?

7.       What is an OS and give examples of  3 familiar OS

8.       What are the functions of OS ?

9.       What are views of operating system and explain ?

10.   What is an application program and explain with classifications

11.   What is Excel and explain what you can do with that

12.   What is MSAccess and it’s Object types ?

13.   What is a number system ?

14.   Convert Below decimal values to binary, Octal, and HexaDecimal

a.       9

b.       100

c.       25

d.       72

 

15.   Convert below binary values to Octal

a.       10001

b.       11010

c.       12010

16.   What is Logic gate and list down basic logic gates.

17.   Write truth tables for the gates AND , XOR for two inputs. Take inputs as A and B

A

B

output

 0

0

0

0

1

1

1

0

1

1

1

1

 

A

B

output

 0

0

0

0

1

0

1

0

0

1

1

1

 

 

18.   Identify the gates below with respect to truth table

19.   List three basic types of Networks

20.   What is OSI model and which layer is responsible for Network ?

21.   Is LAN is faster than WAN ? Comment

22.   What is a network Topology ?

23.   List down 3 basic topologies with diagrams

24.   What is Internet ?

25.   What is the common protocols used in Internet. What’s the common name use for that

26.   What do you understand with HTTPS. Explain

27.   What is an email and list 3 advantages ?

 

Sunday, May 23, 2021

Multi thread and Concurrency - join

<p>In this coding exercise we will you all the knowledge from the previous lectures. <br>Before taking the exercise make sure you review the following topics in particular:<br>1. Thread Creation - how to create and start a thread using the <code>Thread</code> class and the <code>start()</code> method.</p>


<p>2. Thread Join - how to wait for another thread using the <code>Thread.join()</code> method.</p>


<p>In this exercise we will efficiently calculate the following <code>result = base1 ^ power1 +&nbsp;base2 ^ power2</code></p>


<p>Where <code>a^b</code> means: <em>a</em> raised to the power of <em>b. </em></p>

<p>For example <code>10^2 = 100</code></p>

<p>We know that raising a number to a power is a complex computation, so we we like to execute:</p>

<p><code>result1 = x1 ^ y1</code></p>

<p><code>result2 = x2 ^ y2</code></p>

<p>In parallel.</p>

<p>and combine the result in the end : <code>result = result1 +&nbsp;result2</code></p>

<p>This way we can speed up the entire calculation.</p>



-------------------------------------------------


package thread.example;

import java.math.BigInteger;

public class ComplexCalculation {
public static void main(String[] args) {
ComplexCalculation c = new ComplexCalculation();
BigInteger result = c.calculateResult(new BigInteger("2"),new BigInteger("2"),new BigInteger("2"),new BigInteger("3"));
System.out.println(result);
}
public BigInteger calculateResult(BigInteger base1, BigInteger power1, BigInteger base2, BigInteger power2) {
BigInteger result;
/*
Calculate result = ( base1 ^ power1 ) + (base2 ^ power2).
Where each calculation in (..) is calculated on a different thread
*/
PowerCalculatingThread one = new PowerCalculatingThread(base1, power1);
PowerCalculatingThread two = new PowerCalculatingThread(base2, power2);
one.start();
two.start();

try {
one.join();
two.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
result = one.getResult().add(two.getResult());
return result;
}

private static class PowerCalculatingThread extends Thread {
private BigInteger result = BigInteger.ONE;
private BigInteger base;
private BigInteger power;

public PowerCalculatingThread(BigInteger base, BigInteger power) {
this.base = base;
this.power = power;
}

@Override
public void run() {
/*
Implement the calculation of result = base ^ power
*/
this.result = this.base.pow(this.power.intValue());

// result = BigInteger.ONE;
//
// for(BigInteger i = BigInteger.ZERO;
// i.compareTo(power) !=0;
// i = i.add(BigInteger.ONE)) {
// result = result.multiply(base);
// }
}

public BigInteger getResult() {
return result;
}
}

} 


2. Thread Join - how to wait for another thread using the Thread.join() method.

In this exercise we will efficiently calculate the following result = base1 ^ power1 + base2 ^ power2

Where a^b means: a raised to the power of b.

For example 10^2 = 100

We know that raising a number to a power is a complex computation, so we we like to execute:

result1 = x1 ^ y1

result2 = x2 ^ y2


In parallel.

and combine the result in the end : result = result1 + result2

This way we can speed up the entire calculation.


Note :

base1 >= 0, base2 >= 0, power1 >= 0, power2 >= 0

Friday, May 21, 2021

Multi thread and Concurrency - Interruption 3 samples

 

public class Main1 {

    public static void main(String [] args) {

        Thread thread = new Thread(new BlockingTask());


        thread.start();

    }


    private static class BlockingTask implements Runnable {


        @Override

        public void run() {

            //do things

            try {

                Thread.sleep(500000);

            } catch (InterruptedException e) {

                System.out.println("Existing blocking thread");

            }

        }

    }

}

-----------------------------------


import java.math.BigInteger;


/**

 * Thread Termination & Daemon Threads

 * 

 */

public class Main2 {


    public static void main(String[] args) {

        Thread thread = new Thread(new LongComputationTask(new BigInteger("200000"), new BigInteger("100000000")));


        thread.start();

        thread.interrupt();

    }


    private static class LongComputationTask implements Runnable {

        private BigInteger base;

        private BigInteger power;


        public LongComputationTask(BigInteger base, BigInteger power) {

            this.base = base;

            this.power = power;

        }


        @Override

        public void run() {

            System.out.println(base + "^" + power + " = " + pow(base, power));

        }


        private BigInteger pow(BigInteger base, BigInteger power) {

            BigInteger result = BigInteger.ONE;


            for (BigInteger i = BigInteger.ZERO; i.compareTo(power) != 0; i = i.add(BigInteger.ONE)) {

// without this interruption, this won't be interrupt

                if (Thread.currentThread().isInterrupted()) {

                    System.out.println("Prematurely interrupted computation");

                    return BigInteger.ZERO;

                }

                result = result.multiply(base);

            }


            return result;

        }

    }

}


------------------------------------------


import java.math.BigInteger;


/**

 * Thread Termination & Daemon Threads

 * 

 */

public class Main3 {


    public static void main(String[] args) throws InterruptedException {

        Thread thread = new Thread(new LongComputationTask(new BigInteger("200000"), new BigInteger("100000000")));


// make thread deamon, run in background

        thread.setDaemon(true);

        thread.start();

        Thread.sleep(100);

        thread.interrupt();

    }


    private static class LongComputationTask implements Runnable {

        private BigInteger base;

        private BigInteger power;


        public LongComputationTask(BigInteger base, BigInteger power) {

            this.base = base;

            this.power = power;

        }


        @Override

        public void run() {

            System.out.println(base + "^" + power + " = " + pow(base, power));

        }


        private BigInteger pow(BigInteger base, BigInteger power) {

            BigInteger result = BigInteger.ONE;


            for (BigInteger i = BigInteger.ZERO; i.compareTo(power) != 0; i = i.add(BigInteger.ONE)) {

                result = result.multiply(base);

            }


            return result;

        }

    }

}


Multi thread and Concurrency - Questions

 Question 4:

Observe the following code:


    public static void main(String [] args) {

        Thread thread = new Thread(new WaitingForUserInput());

        thread.setName("InputWaitingThread");

        thread.start();

    }

 

    private static class WaitingForUserInput implements Runnable {

        @Override

        public void run() {

            try {

                while (true) {

                    char input = (char) System.in.read();

                    if(input == 'q') {

                        return;

                    }

                }

            } catch (IOException e) {

                System.out.println("An exception was caught " + e);

            };

        }

    }

Please choose the correct statement:


1. <p>We simply need to add <code>thread.interrupt();</code>&nbsp; in the end of the <code>main</code> method, which will stop the <code>"InputWaitingThread"</code> thread.</p>


2. <p>We simply need to add <code>thread.interrupt();</code>&nbsp; in the end of the <code>main</code> method, which will stop the <code>"InputWaitingThread"</code> thread.</p>

<p>And also add a new <code>catch</code> block in the <code>run</code> method inside the <code>WaitingForUserInput</code>, to handle an <code>InterruptedException</code>, and exit from the thread in that block of code.


3.

 <p>The only ways to stop the application are:</p>

 <p>1. For the user to type in the letter 'q'.</p>

    2. Set <code>thread.setDaemon(true);</code></p> in the main method, before starting the thread

 We simply need to add <code>thread.interrupt();</code> &nbsp; in the end of the<code>main</code> method, which will stop the <code>"InputWaitingThread"</code> thread.

 <p>3. Forcefully kill the application</p>

 

4. <p>The application will stop immediately, since there is no <code>Thread.sleep()</code> call in the main method. And as soon as the <code>main</code> method exits, the application terminates. </p>



Question 2:

    public static void main(String [] args) {

        Thread thread = new Thread(new SleepingThread());

        thread.start();

        thread.interrupt();

    }

 

    private static class SleepingThread implements Runnable {

        @Override

        public void run() {

            while (true) {

                try {

                    Thread.sleep(1000000);

                } catch (InterruptedException e) {

                }

            }

        }

    }

Please choose the correct statement



1. <p>The application will stop anyway, when the main thread runs out of instructions to execute.</p>

2. <p>The application will terminate as soon as the <code>thread.interrupt();</code> code is executed.</p>

3. <p>Without modifying the code, the application will not stop.<br>We need to add a <code>return;</code> statement inside the <code>catch (InterruptedException e)</code> block to stop the application.</p>

4. 



Answer

Q1 - 3

Q2 - 3


Q2

That's correct, the only way to programmatically stop the application is to make the thread a daemon. Unfortunately System.in.read() does not respond to Thread.interrupt();

Q2

That is correct. As a rule of thumb, never leave a catch block empty, and use the InterruptedException catch block to gracefully stop the current thread (by adding some print or cleaning code before returning from the run method)


Multi thread and Concurrency - Simple MultiExecutor

 Very simple code block of MultiExecutor class


package thread.example;

import java.util.ArrayList;
import java.util.List;

/**
* <p>The client of this class will create a list of <code>Runnable</code> tasks and
 provide that list into <code>MultiExecutor</code>'s constructor.</p>
* <p>When the client runs the&nbsp; <code>executeAll()</code>,&nbsp;
the <code>MultiExecutor</code>,&nbsp; will execute all the given tasks.</p>
* <p>To take full advantage of our multicore CPU, we would like the
<code>MultiExecutor</code> to execute all the tasks in parallel, 
by passing each task to a different thread.</p>
*/
public class MultiExecutor {

// Add any necessary member variables here
private final List<Runnable> tasks;

/*
* @param tasks to executed concurrently
*/
public MultiExecutor(List<Runnable> tasks) {
// Complete your code here
this.tasks = tasks;
}

/**
* Starts and executes all the tasks concurrently
*/
public void executeAll() {
// complete your code here
// create list of threads
List<Thread> threads = new ArrayList<>(tasks.size());
// for each task create a thread and add to thread list.
for (Runnable task : tasks) {
Thread thread = new Thread(task);
threads.add(thread);
}

// start each thread
for (Thread thread : threads) {
thread.start();
}
}
}