Allow / Deny IP access using Apache HTTP Server

No Comments »

In order to limit access to your application deployed on an Apache HTTP Server, you just have to edit one file : httpd.conf.

For example please take a look at the following settings :

<Directory "/var/www/yourapp">
Options Indexes FollowSymLinks MultiViews Includes
allowOverride All
Order allow, deny
allow from 127
allow from 192.168.1.0/24
</Directory>

This will allow access to “yourapp” only from localhost or from the network indicated (192.168.1.0). Please note that you don’t have to write the entire IP, Apache can figure out what’s missing. The most important rule is that what you don’t specify, Apache won’t allow. If you want to give access to some IP, you have to specify it, default is deny.

Take a look at the other example:

<Directory "/var/www/yourapp">
Options Indexes FollowSymLinks MultiViews Includes
allowOverride All
Order deny, allow
allow from all
deny from 123.456.(10[0-9]¦11[0-9]¦12[0-7]).
</Directory>

Note that you can use regex to define the IP rule you want to implement.

Be careful about your allow / deny rules. The order in which you define them is very important. Apache will arrange the rules based on what you have in the “Order” clause and then treat them line by line, overriding previous rules if that’s the case!

For instance this
allow 123.
Deny 134.
allow 234.
allow all
Deny 145
if the order is Deny, allow, it will be processed as:
Deny 134.
Deny 145.
allow 123.
allow 234.
allow all
With allow, Deny, it will be processed as:
allow 123.
allow 234.
allow all
Deny 134.
Deny 145.
Also, if Apache encounters overlapping rules for the same IPs, the last rule will be implemented. For instance, in the case of an Order allow, Deny, the “allow all” rule will override the deny rules.

Limit IP access to your web application using Apache Tomcat

No Comments »

It is possible that you’d like to limit access to your web application from some IPs, to enhance security. If your application is deployed on Apache Tomcat, you can do that pretty darn easy – you just have to edit the server.xml file.

For example :

<Engine name="Catalina" defaultHost="localhost">
    <Host name="localhost" appBase="webapps"
          unpackWARs="false" autoDeploy="true"
          xmlValidation="false" xmlNamespaceAware="false">
        <Valve className="org.apache.catalina.valves.AccessLogValve"
                directory="c:/Program Files/Apache Software Foundation/Tomcat 6.0/logs" prefix="localhost_access_log."
                suffix=".txt" pattern="common" resolveHosts="false"/>
	<Valve className="org.apache.catalina.valves.RemoteAddrValve"
         	allow="192.168.*.*,89.35.152.*,89.36.153.10"/>
    </Host>
</Engine>

This would limit access to the application deployed in the directory webapps in your tomcat to only the indicated IPs. Note that you can define those IPs using *.

MySQL multirow inserts

No Comments »

I was surprised to see how few people know that in MySQL you can do :

INSERT INTO tbl_01(id, name) VALUES (1, ‘One’)

INSERT INTO tbl_01(id, name) VALUES(2, ‘Two’)

But also

INSERT INT tbl_01(id, name) VALUES

(1, ‘One’), (2, ‘Two’)

In practice it is very useful.

MySQL autoincrement vs Oracle sequence

2 Comments »

In Oracle, sequences (often called autonumber) are used to maintain a unique series of numbers for an id field. Sequences are independent of any table hence they can be used to keep a value unique across a number of tables. Sequences actually do not have to be used in relationship with any table.

The syntax for creating a sequence is :

CREATE SEQUENCE sequence_name
MINVALUE value
MAXVALUE value
START WITH value
INCREMENT BY value
CACHE value;

If you omit the MAXVALUE, it will default to

MAXVALUE 999999999999999999999999999

To retrieve the next value from the sequence, nextval is to be used :

sequence_name.nextval

The nextval statement needs to be used in an SQL statement, for instance :

INSERT INTO tbl_name(tbl_id, tbl_col_name)
VALUES(sequence_name.nextval, ‘Name’);

The CACHE option specifies how many values would be stored in memory for faster access. It sounds good, but if for some reason a system failure occurs, all cached sequence values would be “lost” – when the system is be back up, the sequence will use the next value starting from MINVALUE + CACHE. NOCACHE sacrifices some performance, but you won’t get a “gap” in the values.

Oracle DOES NOT implement any column with autoincrement property. In turn, MySQL does not support sequences. MySQL uses autoincrement,applied to the primary key during table creation :

create table tbl_01 (id int primary key auto_increment, name varchar(100));

The value for the primary key will be assigned automatically, if during an insert there is no value manually assigned to the id column.

Note that the “sequence” will start from the highest value. If we manually insert a record with a number for the id higher than the maximum id in that table, the next insert with no value for the id will automatically assign that max value incremented.

For example suppose you have the following data in the table:

id name

1 One

2 Two

3 Three

You do an insert like this :

INSERT INTO tbl_01(id, name) VALUES (10, ‘Ten’);

You will end up with the following table :

id name

1 One

2 Two

3 Three

10 Ten

When you execute the following SQL:

INSERT INTO TABLE tbl_01(name) VALUES (‘Next’);

You will end up with :

id name

1 One

2 Two

3 Three

10 Ten

11 Next

You can insert record with a value for the id lower than the MAX(id) and that will not affect the next autoincrement value. It just has to follow the normal rules for the primary key (no duplicates).

Also if all the records are deleted from the table, the autoincrement is not affected (it will continue to assign the incremented MAX(id) based on the values that were previously in the table). In order to “reset the sequence” a the table must be truncated :

truncate table tbl_01

Now the first automatically generated value for the id will be 1. You can achieve the same by :

ALTER TABLE tbl_01 auto_increment=value

Compared to Oracle, MySQL is pretty straightforward, but does have its [big] limitations: it cannot be used across multiple tables and you cannot set different increment values.

MySQL case sensitivity

No Comments »

Consider a table tbl_01 containing a column Name and consider the following query :

SELECT * FROM tbl_01 WHERE name = ‘paul’

In Oracle this query would return only the rows containing ‘paul’ in the column name, because Oracle is case sensitive.

MySQL is not, so the same query would return rows containing ‘Paul’, ‘paul’, ‘pAul’, etc. In order to force MySQL to check for the exact case, the keyword binary has to be used :

SELECT * FROM tbl_01 WHERE binary name = “paul”

There is also an alternative to this – making a column case sensitive on table creation:

CREATE TABLE tbl_01 (name varchar(100) binary);

Now the select on name cares for the way the name is written.

Wicketing Javascript through AJAX

No Comments »

Communication between Java and Javascript cannot be done easier than with Wicket framework, by far the best helper if you’re in Java based web development.

html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns:wicket>
<head>
<script type="text/javascript" >
function callWicket() {
	wicketAjaxGet(callback + '&parameter=value', function() {}, function() {});
}
</script>
</head>

<body>
	<div wicket:id = "div"></div>
	<span wicket:id = "wicketAnswer">[]</span>
</body>
</html>

Java – or should I say the magic of Wicket?

package com.somepackage;

import org.apache.wicket.PageParameters;
import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.AjaxSelfUpdatingTimerBehavior;
import org.apache.wicket.markup.html.IHeaderContributor;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.util.time.Duration;

@SuppressWarnings("serial")
public class BasePage extends WebPage {
	private WebMarkupContainer dummyDiv;
	private Label label;

	public BasePage() {
		this(null);
	}

	public BasePage(final PageParameters parameters) {
		//handle js call to wicket
		final AbstractDefaultAjaxBehavior behavior = new AbstractDefaultAjaxBehavior() {
		    protected void respond(final AjaxRequestTarget target) {
		    	label.setModelObject("Yeah I was just called from Javascript!");
		        target.addComponent(label);
		    }
		};
		add(dummyDiv = new MyWebMarkupContainer("div", behavior));
		//handle wicket call to js
		dummyDiv.add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(1)) {
			@Override
			protected void onPostProcessTarget(AjaxRequestTarget target) {
				target.appendJavascript("callWicket();");
			}
		});
		dummyDiv.add(behavior);

    	add(label = new Label("wicketAnswer", "Look here to see when wicket is called from javascript"));
    	label.setOutputMarkupId(true);
	}
}

@SuppressWarnings("serial")
class MyWebMarkupContainer extends WebMarkupContainer implements IHeaderContributor {
	AbstractDefaultAjaxBehavior behavior;

	public MyWebMarkupContainer(String id, AbstractDefaultAjaxBehavior behavior) {
		super(id);
		this.behavior = behavior;
	}

	@Override
	public void renderHead(IHeaderResponse response) {
		response.renderJavascript("var callback = '" + behavior.getCallbackUrl() + "';", "insertedjavascript");
	}
}

I don’t think anyone needs explanation about how this works since it’s THAT easy. Only one more thing to add:

Map map = ((WebRequestCycle) RequestCycle.get()).getRequest().getParameterMap();

- this to get the parameters map.

Javascript inheritance

No Comments »

When it comes to web development, Javascript is the best client-side programming language. It has come a long way in the last years. It’s no longer just a simple scripting language. These days a lot of Javascript libraries are available to be used freely and they are incredibly powerful: Script.aculo.us, DOJO, YUI, jQuery, Prototype, to name just a few.

I am personally not very found of Javascript because of its loosely typed nature. I consider it harder to develop a large framework in Javascript compared to say, Java, because the compiler/interpreter cannot always come to your rescue as you’d expect if you’re coming from a strongly typed language.

But a lot of its strength comes from the fact that it’s loosely typed. You also feel the sense of freedom that only these kind of languages (like Ruby) can offer. Types help you a lot to avoid errors and to give you important structure, but also constrain your ability to do more with your code.

Javascript is (or can act like) a(n almost) full fledged object oriented language. Let’s try inheritance:

This is the method that simulates inheritance in Javascript:

function inherit(child, parent) {
    var sConstructor = parent.toString();
    var aMatch = sConstructor.match( /\s*function (.*)\(/ );
    if ( aMatch != null ) { child.prototype[aMatch[1]] = parent; }
    for (var m in parent.prototype) {
        child.prototype[m] = parent.prototype[m];
    }
};

Let’s define some Javascript objects:

function Element() {
	this.location = null;
	this.type = "Element";
	this.selected = false;
	this.zIndex = 0;
}
Element.prototype.isInside = function(rectangle){
        dosomething;
}

function Item() {
	this.Element(); //calling the constructor of the base class

	this.lastValidLocation = null; //a rectangle
	this.type = "Item";
	this.selectorItem = null;
	this.zIndex = 1;
}
inherit(Item, Element);
Item.prototype.getSelectorItem = function() {
	return this.selectorItem;
}
Item.prototype.draw = function() {
       dosomething;
}
Item.prototype.deleteItem = function() {
       dosomething;
}

function SelectorItem() {
	this.Element();

	this.items = new Array();
	this.type = "SelectorItem";
	this.zIndex = 0;
}
inherit(SelectorItem, Element);
SelectorItem.prototype.getSelectorItem = function() {
	return this;
}
SelectorItem.prototype.createNewItem = function(onItem) {
       dosomething;
}
SelectorItem.prototype.draw = function() {
       dosomething;
}

It is very important when you call “inherit”. That’s because Javascript does not support method override/overload, but you can also simulate this. When executing “inherit”, the prototype of the base class will be copied to the child. Then, if needed, redefine some methods so that when you call them, the new ones will get executed.

Using a static image map with Wicket

No Comments »

On one of my projects I had to implement an image and link the image area to wicket.

This is how I did it:

html

<div>
   <map name="themap">
       <area shape="rect" coords="a1,b1,c1,d1" href="#"
           wicket:id="wicket1" title="Title1" />
       <area shape="rect" coords="a2,b2,c2,d2" href="#"
           wicket:id="wicket2" title="Title2" />
   </map>
   <br/>
   Some text here
</div>

Java

       add(new PageLink("wicket1", SomeWicketClass1.class));
       add(new PageLink("wicket2", SomeWicketClass2.class));

Wicket is the best framework for web development.

Javascript – how to make something happen after some time

No Comments »

I’m writing this post because I’ve been asked a million times about this and it’s easier to point someone to a link than to explain it again :-) .

In Javascript, executing something after a specified time couldn’t be easier – you’ve got the setTimeout method. Just be careful to call it the right way. It takes two arguments:

-> the method to be called after the specified time passed. I repeat, a method, not a method call.
-> the amount of time, specified in milliseconds.

For example, using script.aculo.us, I can make the “feedback” div fade away in 10 seconds after rendering like this:

window.setTimeout(function() {Effect.Fade(‘feedback’);}, 10000);

(and NOT window.setTimeout(Effect.Fade(‘feedback’), 10000}; – also keep in mind Javascript is case sensitive)

Javascript variables scope

No Comments »

A variable can be defined as a segment of memory which holds some kind of value. The programmer can reference that segment of memory by using the name of the variable in order to assign it a value or to read it and use it.

In Javascript, the scope of the variable is the area of the script where that variable is valid to be used. The scope of the global variable is the entire script. That means you can access it anywhere between the <script> and </script> tags and in other scripts that are executed after the variable definition.

A global variable is a variable defined in the main part of the script (not inside a function for instance). It makes no difference if you define it using the keyword var or without it. It does make all the difference in the world if you use it inside a function.

A local variable is a variable that is defined inside a function. It is only available to be used inside that function. Javascript allows you to use the same name for a global variable and for a local one, but when used inside that function, the local variable will be evaluated. A local variable is defined only by using the keyword var. If the keyword is omitted, the variable is defined as global.

Local variables are temporary. Global variables are permanent. Permanent variables exist throughout the execution of all the scripts, until being discarded when the page unloads. Temporary variables are allocated on the stack every time the function is called and deallocated when the execution of the function ends. Large local chunk of data causes the stack to overflow, so data structures like large arrays declared inside a function (as local) or passed to the function (as arguments) should be avoided. Use global variables for such tasks.

Variables in Javascript can only be of 4 types: number (there is no distinction between integer and real-valued numbers), string, Boolean and null values. Remember that Javascript is a “loosely typed language”, which means the type of the variable is not declared explicitly. Javascript implicitly determines the type of the variable based on the initial value that is assigned to it.

The null value is automatically converted to the initial values of other data types once that variable is initialized to a different type – when used as a number, it becomes 0, when used as a string it becomes “” and when used as a boolean it becomes false.

Data types are automatically converted as needed throughout the execution of the script. For instance, when an expression containing a number and a string (like a sum) is evaluated, the value returned is a string. Also, keep in mind that in Javascript evaluation is done from left to right and only paranthesys can change the order of the evaluation:
10 + 10 will return 20
10 + “10″ will return “1010″
10 + 10 + “10″ will return “2010″.