Showing posts with label General Programming Topics. Show all posts
Showing posts with label General Programming Topics. Show all posts

10 April 2015

About web security (1)

We usually implement web security with Roles and Permissions.

a Database Table for users and one for Roles which users belongs and one for Permission for the roles which the users a role should have.


[Users Table]    <- Many-to-one -> [Roles Table] <-  One-to-many -> [Permissions Table]

The above model is the basic, but we can add extra relation between the Users and the Permissions to allow direct permission on the table regarding the role in which the user belongs.


The Authentication does from the Users table.. the user is there and not disabled.

The Authorization is all about answering the question of "Is the user has access to this restricted object?"

How Authorization done?

In Web - where the restricted object is all about URL resources - the autorization is done as follows:

  • Every resource (a pattern for resources) in the system (should) have a list of permissions associated (usually only one) with it.
    Usually defined in the Permissions table as URL -> PERMISSION mapping. (or in XML as of spring-security)
    ex: '/editMyProfile.html' url mapped to CAN_EDIT_PROFILE permission.
  • When the user successfully login, a list of all permission is attached to him (either role permissions or user permission as discussed before)
  • Then when the user requests some URL, The system checks if the user has some attached permission that in the list of permissions that is associated with the url. If yes then the system allows the user to access the page, otherwise HTTP 403 is returned to the user.

How to draw the menu:

First you have your structure of menu (tree menu, list menu or whatever).
Initially, get all urls from Permissions table of the database and draw this permissions as following:

for (Permission p: permissions){
     if (userHavePermission(p.getPermissionName()){
           out.println(p.getUrl());
     }
}

the above is very simple code example.
Also you can consider nesting the menus by having a self-referential relationship in the Permissions table.










22 January 2015

Two notes about Java Generic Types (Type Covariance and Type erasure)

Java Generics have two characteristics that are important when working with generics of Java.

The first one is the most important and most well-known than the other, the second is less known.

1. Generics types are not Covariant:

All of us knows that List<String> cannot substitute List<Object>; however String[] can substitute Object[]

This prevent error in Generics that happens in case of arrays.

String[] sArr = new String[] {"Hello"};
Object[] oArr = sArr;
oArr[0] = 10; // << Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer

However in case of Generic types, such error is being caught  at compile time, and this is because Type Parameters (Generics) doesn't allow type covariance.

Example:

List<String> sList = new ArrayList<>();
List<Object> oList = sList; // Type mismatch: cannot convert from List<String> to List<Object>

oList.add(10);

2.  Type parameters is being removed in generated byte code (Called Type erasure).

This is why you cannot say: T.class

Quote: 
When you compile some code against a generic type or method, the compiler works out what you really mean (i.e. what the type argument for T is) and verifies at compile time that you're doing the right thing, but the emitted code again just talks in terms of java.lang.Object - the compiler generates extra casts where necessary. At execution time, a List<String> and a List<Date>are exactly the same; the extra type information has been erased by the compiler.

09 September 2011

Dynamic Binding (Dispatch) by example

SA,
Dynamic Dispatch is the process of mapping a message to a specific sequence of code (method) at runtime. This is done to support the cases where the appropriate method cannot be determined at compile-time (i.e. statically)
The above paragraph is from Wikipedia It illustrate what is dynamic binding. It is simply that, We have a method that being called/send on some object, the actual implementation of the method to chosen is based on the runtime type of that object. It is used in Polymorphism. it can be illustrated by this example:
Class A
{
      someFunc();
}

Class B extends A
{
     someFunc();

}

A aInstance = new B();
aInstance.someFunc();
in this case, and if the language supports dynamic binding (such as Java/Ojbc).. the implementation of the subclass who will be invoked. But in C++ (I think in C# also), the dynamic dispatch is optional and non-default. so to enable it, you mark the method with the virtual keyword. From wikipedia:
Although the overhead involved in this dispatch mechanism is low, it may still be significant for some application areas that the language was designed to target. For this reason, Bjarne Stroustrup, the designer of C++, elected to make dynamic dispatch optional and non-default. Only functions declared with the virtual keyword will be dispatched based on the runtime type of the object; other functions will be dispatched based on the object's static type.
See this example in C++:
#include <iostream>

using namespace std;

class Super
{
public:
    void someFunction()
    {
        cout << " In Super function" << endl;
    }
};

class Sub : public Super
{
public:
    void someFunction()
    {
        cout << " In Sub function" << endl;
    }
};

int main(void)
{
    Super* s = new Sub;

    s->someFunction();
    
    delete s;
    
    return 0;
}
The Super class method will be invoked, but if you added the virtual keyword at the start of the super class someFuncation() to be: virtual void someFunction() The dynamic binding will be enable and the subclass's method will be invoked instead.

06 August 2011

Why C accept confusion in conditional operation while Java not

Usually, when we begun to learn Programming in C, our teachers warn us from the following Syntax:

if ( i = 30)

They said that, we have to beware cause it will lead to logical error rather thank syntax error.. ( it will be translated to if (30) )

But when we looked in higher langs like Java/C#, we found that, the compiler will issue a compilation error if he find such statement.

The difference appears because, in C/C++ there were originally bool datatype, so expressions were evaluated to zero and none-zero.
Zero for false, and non-zero for true.

So, the statement:
if (i = 30 )
Will always translated to if (30) which is a valid C/C++ statement that it understand as it were: if (true)

But in Java, relational expressions are only evaluated to Boolean types which is a completely separate type, which takes only two values, constant true and constant false.. so such statement will be always syntactically incorrect.

BTW, I could say that the following is the C implementation of true and false constants (implemented as macros):

#define FALSE 0
#define TRUE !FALSE

13 July 2011

Dynamic Programming VS Dynamic Langugage VS Dynamicly-Typed Language

Three Concepts need to be clear:
Dynamic Programming:
Is a method for solving complex problems by breaking them down into simpler subproblems. It is applicable to problems exhibiting the properties of overlapping subproblems which are only slightly smaller[1] and optimal substructure (described below). When applicable, the method takes far less time than naïve methods.

Dynamic Programming Language:
Is a term used broadly in computer science to describe a class of high-level programming languages that execute at runtime many common behaviors that other languages might perform during compilation.

Dynamic Type:
A programming language is said to be dynamically typed when the majority of its type checking is performed at run-time as opposed to at compile-time.

17 September 2010

Lined Lists vs Array Lists, a quick view

Alsalamo Alykom,

Lists in many programming languages are implemented in many ways such as linked lists, Array Lists.http://www.blogger.com/img/blank.gif

Linked lists are about nodes being linked together, and It may be single or doubly linked lists.
the insertion and deletion operations are simply done by changing the destination of some pointers. But the search is liner!.

In Array list, the Array Lists is used technique called dynamic-arrays, in which these lists is built based on arrays.
Also, you can still insert and remove elements from ArrayLists such as you done with Lined Lists, but this operation uses shifting operation as an underlying operation.
For example, in Java, java.uitl.ArrayList class uses System.arraycopy to do the shift of elements.
ArrayLists is very efficient in Random access.

thanks all folks!

02 July 2010

final varaibles in Java and its relation to const in C

Hi folks,

Java uses the keyword `final` with variables in indicate that this variable is a constant.

ex1:

final int x = 10;

The above line means x is a constant of type `int` that its value cannot be altered.

ex2:
final Employee e = new Employee("Ahmed");

The above line means e is a constant of type `Employee` that its value cannot be altered.

So, the following line will not compile:
e = new Employee("Mohammed"); // compile error

But the following line will successfully compile:
e.setName("Ali");

Let's derive something:
For primitive, final is a keyword that ensure that the value of the primitive will never change.
For references, final is a keyword that ensure that the variable name cannot be reassigned to any other objects any more.

But, In C:
When we say:

//we define a pointer of type x, that its value cannot change.
int y=100;
const int* x = NULL;
*x = 20; // will not compile
x = &y; // will compile

but, when we say:

int y=100;
int* const x = malloc(sizeof(int*));
*x = 20; // will compile
x = &y; // will not compile
we define a pointer of type x, which that address its points to cannot change.

Conclusion:
So, We can say that, `final` in java with reference types act the same behavior of constant pointers in C (not value pointers). i.e. we cannot make it to refer (point) to another object, but we can change it's value.

Java never ever uses pass by reference

Hi folks,

Java never ever never uses pass by reference!

Pass by reference requires that, whenever you change the value of the reference, the value of the original object got changed.
By "change the value of the reference" I mean, use the assignment operator to do that.

Example:

class X
{
int dataMember;

X(int n)
{
dataMember = n;
}
static void m1()
{
X x = new X(10);
System.out.println("Before: " + x.dataMember);
m2(x);
System.out.println("After: " + x.dataMember);
}

static void m2(X x)
{
x = new X(30);
System.out.println("IN: " + x.dataMember);
}

public static void main(String[] args)
{
m1();
}
}
Result:

Before: 10
IN: 30
After: 10



So, In language such as C, pass by reference uses deference Pointers:


#include <stdio.h>

void wrong_pass_by_reference(int*);
void correct_pass_by_refence(int*);

int main(void)
{
int n = 0;
int *ptr = &n;

printf("Before 1: %i\n", *ptr);
wrong_pass_by_reference(ptr);
printf("After 1: %i\n", *ptr);

printf("Before 2: %i\n", *ptr);
correct_pass_by_refence(ptr);
printf("After 2: %i\n", *ptr);

return 0;
}

void wrong_pass_by_reference(int* i)
{
int x = 10;
i = &x;
printf("IN 1: %i\n", *i);
}
void correct_pass_by_refence(int* i)
{
*i = 200;
printf("IN 2: %i\n", *i);
}
Before 1: 0
IN 1: 10
After 1: 0
Before 2: 0
IN 2: 200
After 2: 200

So, Java uses an approach similar to the one used by C, but in Java you cannot deference a reference to an object, So you cannot use call by reference!

30 June 2010

lvalue and rvalue

Alsalamo Alykom,

Any variable defined in your program has two values, the "lvalue" and the "rvalue".
lvalue is the left value, and rvalue is the right value.

suppose you have defined a variable of int type:

int x;
x = 10;

in above line, you say that, save the value 10 (rvalue) in the memory location of x (lvalue).

see this example and note the difference:

int x, y;
x=10;
y=x;

first you defined two variables of type int, then in line two you say:
save the value `10` in the memory location of variable `x`, and in the third line you say: save the value in memory location `x`, into the memory location of variable `y`.
So, `x` on the left -lvalue- (at line 2) are refereed as `the address of x`, but x on the right -rvalue- (at line 3) are refereed as `the value at the address of x`.

21 June 2010

Two ways to convert decimal numbers to binary strings

I'll show you two ways to convert decimal to binary.

First, the most basic way is apply the following pseudo-code:

int x
char[80] arr
do{
reminder = x%2;
arr[i] = reminder
}while (x/2 > 0);
reverse arr;


And the other is more advanced (and more simple), it use bitwise operations instead:

int x
while (x > 0){
arr[i] = ((x & 1) ? '1' : '0');
x >>=1;
}
reverse arr


and here's a C code for the last one:
 
//I am not the author of this function, I copied from the link below
void dec2binary(long i){

char* str = malloc(sizeof(long)*8*sizeof(char));

char* p = str;
while (i > 0){
*p++ = ((i & 1) ? '1' : '0');
i >>=1;
}

while( p-- != str ) /* print out the result backwards */
printf("%c",*p);

free(str);
}


please see:
http://www.daniweb.com/code/snippet216349.html

23 April 2009

My Programming Skills

While going through friend's blogs, I found this post.
In this post I found a tests about Programmer Personality Type , I took the quiz and here's the rest ;


Your programmer personality type is:

PHTB

You're a Planner.
You may be slow, but you'll usually find the best solution. If something's worth doing, it's worth doing right.


You like coding at a High level.
The world is made up of objects and components, you should create your programs in the same way.


You work best in a Team.
A good group is better than the sum of it's parts. The only thing better than a genius programmer is a cohesive group of genius programmers.


You are a liBeral programmer.
Programming is a complex task and you should use white space and comments as freely as possible to help simplify the task. We're not writing on paper anymore so we can take up as much room as we need.