Java threads notification

|
A proper way to temporarily pause the execution of a Java thread is to set a variable that the thread checks occasionally. When the thread detects that the variable is set, it calls its wait() method. The paused thread can then be woken up by another thread by calling the notify() method of the latter.

Note: Thread.suspend() and Thread.resume() provide methods have been deprecated because they are very unsafe. With the approach above, the target thread can ensure that it will be paused in an appropriate place.

// Create and start the thread to pause in a main thread
ThreadToPause threadToPause = new ThreadToPause();
threadToPause.start();

while (true) {
// Do work

// tell the thread to wait
synchronized(threadToPause) {
thread.wait = true;
}

// Do work

// Resume the thread
synchronized(thread) {
thread.pleaseWait = false;
thread.notify();
}

// Do work
}



class ThreadToPause extends Thread {
boolean wait = false;

// Implements the run method
public void run() {
while (true) {
// Do work

// Check if should wait
synchronized (this) {
while (wait) {
try {
wait();
} catch (Exception e) {
}
}
}

// Do work
}
}
}

Java pausing and resuming threads, pause and resume a thread in Java, Thread notifications in Java, waking up a thread in Java, thread wait and wake up

Java xml serialization & deserializatrion

|

Java XML Serialization

Java allow you to easily transform various xml input formats into various output formats by using the java.xml.transform package. In this example, we'll see how to parse an xml document into an array of byte.
// use this package
import javax.xml.transform.*;

// transforms xml document to byte array
// o_doc is a org.w3c.Document object
Source source = new DOMSource(o_doc);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Result result = new StreamResult(baos);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(source, result);
byte[] out = baos.toByteArray();

Java XML Deserialization

The reverse transformation allow you to build a Java Document object from a byte array.
// use this package
import javax.xml.transform.*;

// transforms byte array to xml document
// messenger is a byte array
ByteArrayInputStream bais = new ByteArrayInputStream(messenger);
Source source = new StreamSource(bais);
DOMResult result = new DOMResult();
Transformer transformer = factory.newTransformer();
transformer.transform(source,result);
Node out = result.getNode();

Document to byte array, Java Dom to byte array, Java Document serialization, XML to byte array, Byte array to XML, Byte array deserialization, Byte array to Java DOM Object

Copying nodes between XML documents with Java DOM

|
A recurent problem in Java is to copy nodes from one Document to another one ( org.w3c.dom.DOMException: WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it). This issue could be done easily by using the Document.importNode method.

bais = new ByteArrayInputStream(donnees);

Document o_doc; // original document
Document r_doc; // resulting document

DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
dfactory.setNamespaceAware(false);

// Creation du gestionnaire de DOM
DocumentBuilder builder = dfactory.newDocumentBuilder();

o_doc = builder.parse(bais);
r_doc = builder.newDocument();

Element root = r_doc.createElement("Root");
root.setAttribute("xmlns", "http://my.domain.com");
Element oneNode = r_doc.createElement("oneNode");
root.appendChild(oneNode);

r_doc.appendChild(root);

CachedXPathAPI cxpa = new CachedXPathAPI();

Node nodeToCopy = cxpa.selectSingleNode(o_doc, "XPathPathToNodeToCopy");
// use importNode to copy into another tree
oneNode.appendChild(r_doc.importNode(nodeToCopy, true));

Copy one node to one parse Tree into another, Copy a node into a new Document, Copy parts of an xml document into another, Nodes copy in Java, Copy XML nodes in Java

Multi domain & site on a single Tomcat server

|
Apache Tomcat allow you to run simple java web application. You can use it to deploy static web site or dynamic ones using jsp and servlet...
As it allow to deploy many web application archive (.war), the question is how to asign different domain to each web application archive. The answer is by tuning the server.xml file in the ROOT/conf directory of your apache distribution.

Standard configuration

With the standard confiruation, .war archive are deploy within the ROOT/webapps directory of the apache distribution as denoted by the server.xml configuration file :
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true"
xmlValidation="false" xmlNamespaceAware="false">
All you webapps are deploy under the same domain (associated with the ROOT/webapps directory) and can be accessed by changing the URL terminaison :
  • http://www.mydomain.com/webapp1
  • http://www.mydomain.com/webapp2
  • ...

Multi domain configuration

Tomcat allow you to simply bind domain names to specific directories. Each requested made to a specific domain will be handled by the web applications deployed into the mapped directory. You have to define Host within the Engine tag of the server.xml configuration file.
<Engine name="Catalina" defaultHost="localhost">
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
resourceName="UserDatabase"/>
<!-- Domain1 -->
<Host name="www.domain1.com" appBase="domain1"
unpackWARs="true" autoDeploy="true"
xmlValidation="false" xmlNamespaceAware="false">
<Alias>fr.domain1.com</Alias>
<Alias>it.domain1.com</Alias>
<Alias>es.domain1.com</Alias>
<Alias>pt.domain1.com</Alias>
<Alias>de.domain1.com</Alias>
<Alias>nl.domain1.com</Alias>
</Host>
<!-- Domain2 -->
<Host name="www.domain2.com" appBase="domain2"
unpackWARs="true" autoDeploy="true"
xmlValidation="false" xmlNamespaceAware="false">
</Host>
<!-- Domain3 -->
<Host name="www.domain3.com" appBase="domain3"
unpackWARs="true" autoDeploy="true"
xmlValidation="false" xmlNamespaceAware="false">
</Host>
<!-- Default
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true"
xmlValidation="false" xmlNamespaceAware="false">
</Host> -->
</Engine>
Requests made to www.domain1.com and it's sub domains :
  • fr.domain1.com
  • it.domain1.com
  • ...
will be handled by the web application deployed into the ROOT/domain1 directory of the tomcat distribution.

Requests made to www.domain2.com will be handled by the web application deployed into the ROOT/domain2 directory of the tomcat distribution.

Requests made to www.domain3.com will be handled by the web application deployed into the ROOT/domain3 directory of the tomcat distribution.

Publish multiple websites using a Single Tomcat web server, Multiple domains on a single Tomcat web server, Multiple hosted sites on a Tomcat server

Number base to number base converter

|
Number base convertion is a recurent task for a programmer. Here I give you a usefull tool for converting numbers from one base to another base. Supported radix are 2 (binary), 10 (decimal), 8 (octal), 16 (hexadecimal).



Enjoy

Customizing javascript Array.sort() method

|
In Javascript, Array sort could be parametrized. You could change the behaviour of the Array.sort method by passing the comparison function to it :
var myArray=new Array(2,1,6,4,18,-1);

// Descending sort
alert(myArray.sort(function(x,y) {return y-x}));

// Ascending sort
alert(myArray.sort(function(x,y) {return x-y}));


You can setUp your own sort function for you own objects and needs...

Javascript array sort with custom comparators, Javascript sorting, Custom comparison for the javascript Array.sort method, Array.sort() with custom sorter, Descending Array.sort() in Javascript, Ascending and descending sort in javascript

Absolute position of an element using Javascript

|
In a web browser window, elements are placed according to their style and the style and the position of their parent elements. Margin, padding, floating, relative position, static position, fixed position, borders,... can affect the position of an element in the browser window. In Javascript, it is possible to get the absolute position of any element. You just need to pass an DOM element (obtain with getElementById or whatever...) and you get the result as a Javascript object.

function findXY(obj) {
if (obj==null) return {x:0,y:0};
var coords=findXY(obj.offsetParent);
return {x:obj.offsetLeft-obj.scrollLeft+coords.x,y:obj.offsetTop-obj.scrollTop+coords.y};
}

var coords=findXY(document.getElementById("myId"));

The values coords.x and coords.y gives you the position of the DOM element from the top left corner of your web page.

This function is used to display sprite in this Ajax/javascript online Game. Check the javascript source code in the web page to see how it works.

How to get the absolute position of an element using javascript, Absolute positionning in javascript, Javascript element coordinates, Absolute screen position in javascript