miércoles, 23 de noviembre de 2011

Load javascript or css dynamically in javascript

Loading Javascript or CSS dynamically in a DOM with pure JavasScript

If for some reason you need to programatically load some javascript or css stylesheet in the document, here is some code that helped me and seems to work fine in most browsers.

/**
 * loads javascript file or css stylesheet in current document. Usage Examples:
 * loadFile("www.server.com/file1.js", "js", function(){ alert("file1.js
 * loaded!"); });
 * 
 * @param name :
 *            the url of the resource to load. I think there is no cross site
 *            problems here.
 * @param type :
 *            "js" or "css". if "js" then a new javascript script will be loaded
 * @param listener
 *            an optional function that will be called when loading of the
 *            resource is ready.
 * @author: sgurin
 */
var _loadF = function(name, type, listener) {
 var el = null;
 if (type == "js") {
  el = document.createElement("script");
  el.setAttribute("type", "text/javascript");
  if (listener) {
   el.onreadystatechange = function() {
    if (this.readyState == 'complete')
     listener();
   };
   el.onload = listener;
  }
  el.setAttribute("src", name);
 } else if (type == "css") {
  el = document.createElement("link");
  el.setAttribute("rel", "stylesheet");
  el.setAttribute("type", "text/css");
  el.setAttribute("href", name);
 }
 document.body.appendChild(el);
}

An example usage:

_loadF("http://code.jquery.com/jquery-2.0.0.min.js", "js", function(){
 //jquery loaded to current DOM window and ready to use
 $("p").click(function(e){
  alert("p clicked"); 
 });
}); 

Example where this can be useful

Some exentric programmers / web application need a javascript application to be loaded into the current document. This is often accomplished setting current web address to a "javascript: " prefixed address that execute some javascript code in the context of the current document or using firebug / chrome development console.

In this modality, the given javascript code will execute in the context of the current document, being able to show new visual components or even modify the current document. Here it is nice to have a short function that is capable of loading both javascript or css into the current DOM so we can use these libraries in this kind of programs.

Other example, paste the folowing into firebug/chrome devel console:

var _loadJs = function(name, listener) {
 var el = document.createElement("script");
 el.setAttribute("type", "text/javascript");
 if (listener) {
  el.onreadystatechange = function() {
   if (this.readyState == 'complete')
    listener();
  };
  el.onload = listener;
 }
 el.setAttribute("src", name);
 document.getElementsByTagName("head")[0].appendChild(el);
}; 
_loadJs("http://code.jquery.com/jquery-1.9.1.min.js", function(){
 alert("this document has "+$("p").size()+" paragraphs. "); 
}); 

jueves, 6 de octubre de 2011

Tomcat in windows logging

I work daily with tomcat in linux, and I'm used to read all tomcat logs in file logs/catalina.out. The other day, I had to tun tomcat on a windows machine, launching it from comand line, not as a windows service. To my surprise, there was no logs/catalina.out file with my logs, and any of the other files in logs folder contain useful information.

So, how to launch tomcat from windows command line and make it dump the logs to logs/catalina.out file??

This is the answer:

cd c:\tomcat\bin
call catalina run 1> ../logs/catalina.out 2<&1

this will write all tomcat logs to file c:\tomcat\logs\catalina.out

hope this can help people in the same situation.

martes, 18 de enero de 2011

ajax cross domain

i need to do ajax cross site scripting

there are several technics, all with its limitations

* flash: needs security policy file in the target server

* javascript : needs security policy file in the target server

* cssHttpRequest (http://nb.io/hacks/csshttprequest). works fine but it is considered a bug and it is fixed in new versions of some browsers like FF or webkit, so IMHO it is not recommended to use this in your products.

* using an iframe: it is tricky and didn't worked for me

* an approach like www.ajax-cross-domain.com wirks very good, but the service offered by www.ajax-cross-domain.com it's only for demo porpuses and very limited.


In this article I will examplain how to make your own www.ajax-cross-domain.com service like for free:

000webhost



file curl.php

$curl_url = $_GET["url"];
/*echo "url = " . $curl_url;*/
$curl_limit_size = 20000; /* ~20kb */
$curl_handle = curl_init($curl_url);
$data_string = "";

function write_function($handle, $data) {
global $data_string;
global $curl_limit_size;
$data_string .= $data;
if (strlen($data_string) > $curl_limit_size) {
return 0;
}
else
return strlen($data);
}

function escapeJavaScriptText($string) {
return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}


http://cancerbero.vacau.com/curl.php?url=http://www.google.com

you can disable the code here -> http://members.000webhost.com/analytics.php

viernes, 27 de agosto de 2010

Script for dynamic JavaScript and CSS loading

With the following script, you can easily load javascripts and css files dynamically and asynchronously of course:


/**javascript and css loader
* @author: sgurin
*/
(function(){

var _loadF = function(name, type, listener){
var el=null;
if (type=="js"){
el=document.createElement("script");
el.setAttribute("type","text/javascript");
if(listener) {
el.onreadystatechange = function () {
if (this.readyState == 'complete') listener();
};
el.onload=listener;
}
el.setAttribute("src", name);
}
else if (type=="css"){
el=document.createElement("link");
el.setAttribute("rel", "stylesheet");
el.setAttribute("type", "text/css");
el.setAttribute("href", name);
}
document.body.appendChild(el);
};
/**public global function
* @param css - array of css url to load. can be null
* @param js - array of javascript scripts urls to load. can be null
* @param listener function that will be called when ALL js and css files are loaded.
*/
LOADFILE = function (css, js, listener) {
css=css==null?[]:css;
js=js==null?[]:js;
var subListener=function(){
LOADFILE.counter--;
if(LOADFILE.counter==0)
listener();
};
for(var i=0; i<css.length; i++) {
_loadF(css[i], "css", subListener);
}
for(var i=0; i<js.length; i++) {
LOADFILE.counter++;
_loadF(js[i], "js", subListener);
}
};
LOADFILE.counter=0;//file load counter

})();


For example, you can dynamically load all your javascript application's javascript and css files like this:


LOADFILE(
["http://yui.yahooapis.com/2.8.1/build/slider/assets/skins/sam/slider.css",
"http://yui.yahooapis.com/2.8.1/build/fonts/fonts-min.css",
"http://yui.yahooapis.com/2.8.1/build/colorpicker/assets/skins/sam/colorpicker.css"],

["http://yui.yahooapis.com/2.8.1/build/yahoo-dom-event/yahoo-dom-event.js",
"http://yui.yahooapis.com/2.8.1/build/animation/animation-min.js",
"http://yui.yahooapis.com/2.8.1/build/dragdrop/dragdrop-min.js",
"http://yui.yahooapis.com/2.8.1/build/slider/slider-min.js",
"http://yui.yahooapis.com/2.8.1/build/element/element-min.js",
"http://yui.yahooapis.com/2.8.1/build/colorpicker/colorpicker-min.js"],

function(){
//my javascript application's code
var Event = YAHOO.util.Event,
picker;
Event.onDOMReady(function() {
YAHOO.log("Creating Color Picker.", "info", "example");
picker = new YAHOO.widget.ColorPicker("container", {
showhsvcontrols: true,
showhexcontrols: true,
images: {
PICKER_THUMB: "assets/picker_thumb.png",
HUE_THUMB: "assets/hue_thumb.png"
}
});
YAHOO.log("Finished creating Color Picker.", "info", "example");
var onRgbChange = function(o) {
YAHOO.log("The new color value is " + o.newValue, "info", "example");
}
picker.on("rgbChange", onRgbChange);
Event.on("reset", "click", function(e) {
picker.setValue([255, 255, 255], false);
});
Event.on("gethex", "click", function(e) {
alert("Current hex value: " + picker.get("hex"), "info", "example");
});
});
});


Hope this help somebody

jueves, 29 de julio de 2010

svn error (405 Method Not Allowed) in commit

If you are web developer and are trying to commit your changes via svn to sourceforge.net or google code and the commit because a (405 Method Not Allowed), the first thing you want to check is the following.

For commiting code to this kind of sites, you have to commit using the https:// direction and NOT http://. You can checkout projects using http:// but for commiting changes you must use https://. This is a common mistake that can stuck svn novices (like me)

martes, 30 de marzo de 2010

How to start publishing your project in sourceforge

How to start publishing your project in sourceforge

This article is a step/by/step guide to those who want to maintain their development projects in sourceforge.net, with svn support for sharing their source code and a project web site.

First of all I suppose you have already created a new project in sourceforge.net. The important thing to remember is the project's unix name. In the following examples, my sourceforge.net user name is cancerbero_sgx and my project unix name is yui4java. As an administrator of your new project, using a linux shell, you can do the following activities:

copy files and directories with rsync:

# rsync -avP -e ssh foo.txt cancerbero_sgx,yui4java@web.sourceforge.net:htdocs/
# rsync -avP -e ssh /home/sgurin/dir1 cancerbero_sgx,yui4java@web.sourceforge.net:htdocs/

those will copy (synchronize) the file foo.txt and the directory /home/sgurin/dir1 to project's htdocs directory.

conecting using sftp:

sftp cancerbero_sgx,yui4java@web.sourceforge.net

Getting a web shell with ssh

with this option you will have access to a remote terminal in sf.net and there execute commands, access files ,etc
for connecting I use:

ssh -t cancerbero_sgx,yui4java@shell.sourceforge.net create


Publish your source code using svn

This will create a svn repository from a local source directory. Be carefull when typing commands when creating a new repository! Once this is done, you can svn checkout your own source files. Then you can work with svn (svn update, svn commit) in your own local working copy.

first you need to create a repository. for this you have to:

1)
connect via ssh as explained beore

2)
type the command :
adminrepo --checkout svn
(this will create a clone copy of your repository in /svnroot/yui4java.
* Use adminrepo --help for further information.)

3)
type the following commands (be carefull!)
rm -rf /svnroot/yui4java/*
# (Remove the clone copy of your repo)
create /svnroot/PROJECT
# (Create a new repository)

4)
type the following commands
cd
adminrepo --save svn


that operation can take some seconds... Once it is done, you can use your new svn repository. With the following command we will import a local source code directory into the svn repository:

svn import /home/sgurin/my/local/src/folder https://yui4java.svn.sourceforge.net/svnroot/yui4java/trunk

web page

The last thing we will create for our new project is its web page in sourceforge.net. In our project's main folder, we have the directory htdocs and this is the directory that is exposed to the web. In my example, this diretory is located at /home/groups/y/yu/yui4java/htdocs. This means that a file there, for example, /home/groups/y/yu/yui4java/htdocs/example.html can be navigated from http://yui4java.sourceforge.net/example.html.

it is important that all directory accesible from the web (for example, directories with javascript, css, images, etc), to contain a file .htaccess with the following content:

Options +Indexes
that's all. I hope this can be usefull to new sourceforge users.

miércoles, 3 de marzo de 2010

Problem with SVG feConvolveMatrix filter with kernel which sum is zero

Here I will document an issue that I had working with SVG feConvolveMatrix primitive filter that was a really pain for me but has a simple solution.

My problem was using feConvolveMatrix filter primitive to apply operations like blur, sharp, edge detection, etc to images. Everything works OK, except for kernel matrix which elements sum equals 0.

For example, the following filters works as spected:


<filter id="vstripe">
<feConvolveMatrix order="3"
kernelMatrix="
2 -1 2
-1 2 -1
2 -1 2"
/>
</filter>


but the following filter (with a kernel which elements sum equals 0) won't work ( will show an empty rectangle):


<filter id="vstripe">
<feConvolveMatrix order="3"
kernelMatrix="
-1 -1 -1
-1 8 -1
-1 -1 -1"
/>
</filter>


This problem manifest only for svg elements and in all svg user agents (mozilla, webkit, opera, inskape, etc). This problem is very frustrating because, there are a lot of convolution filters that use kernels which element sum must be 0 (specially edge detector filters).

The problem was because of the alpha channel of images. In most images, the alpha channel has a constant value for all pixels in a region and so, a convolution using these kernels will give 0 (totally transparent) and that is the reason for the empty rectangle.

The solution is setting the parameter preserveAlpha="true" so the alpha channel is not processed in the convolution:


<filter id="vstripe">
<feConvolveMatrix order="3" preserveAlpha="true"
kernelMatrix="
-1 -1 -1
-1 8 -1
-1 -1 -1"
/>
</filter>


I hope this article can help those poor souls that, like me, are stagnant with this problem.