Showing posts with label OpenSource. Show all posts
Showing posts with label OpenSource. Show all posts

Is it possible to get HTML of an iframe - CAN'T

You are trying to access content of iframe which points to webpage from another domain. You cannot access content of iframe if the src of that iframe is not pointing to the domain on which your current parent page is. This is called cross domain policy

You will have to use server side language that will grab the html of given url and return it to your index page to display in any div or whatever.

Let me give you an example to explain why javascript cannot have cross domain access.
  • Suppose i have FB like box on my website inside an iframe
  • now whenever any user comes on my website i will trigger a click to the like box which is inside the iframe of like box.
  • This way my FB page will have lakhs of likes.
  • But because of cross domain policy this cannot be done.

Deployment of Apache Tomcat 7 in Amazon server


 Before Installation Check your java Jdk installed or not.  
 Step 1:  
 Download the Apache tomcat 7 from the bellow link,  
 Step2:  
 md5sum apache-tomcat-[#].tar.gz  
 Next, extract the package:  
 tar xvzf apache-tomcat-[#].tar.gz  
 And move the extracted folder into a dedicated directory:  
 sudo mv apache-tomcat-[#] /usr/local/apache  
 Step3: Set the path   
 vi ~/.bashrc  
 export CATALINA_HOME=/usr/local/apache  
 Log out and log back into bash to have your changes take effect.  
 Step4: Start tomcat  
 sudo /usr/local/apache/bin/startup.sh  
 Step 5 : Check  
 Go to web browser and type ,  
 http://localhost:8080  

Install Apache 2 In Linux


Apache is the web server piece of our puzzle. From within your terminal window issue the command:

sudo apt-get install apache2

If, by chance, you are using a distribution that does not use Sudo, you will need su to the root user and issue the above command without the sudo command.
Depending on your OS installation, the above command might need to pick up some dependencies. If so, okay those dependencies. At the end of the installation, Apache should automatically start. If it doesn't, issue the following command:

sudo /etc/init.d/apache2 start

You can now open up a browser and point it to the IP address (or domain) of the server to get the famous "It works!" page. You are ready to move on to PHP.

Event - Driven Development


Traditional programming does input and output the same way as it does local function calls: Processing cannot continue until an operation finishes. This programming model of blocking when doing I/O operations derives from the early days of time-sharing systems in which each process corresponded to one human user.  Managing many processes places a big burden on the operating system — in memory and context switching costs — and the performance of these tasks starts to decay after a certain number is reached.

Multi-threading is one alternative to this programming model. A thread is a kind of light- weight process that shares memory with every other thread within the same process. Threads were created as an ad hoc extension of the previous model to accommodate several concurrent threads of execution. When one thread is waiting for an I/O operation, another thread can take over the CPU. When the I/O operation finishes, that thread can wake up, which means the thread that was running can be interrupted and eventually be resumed later. Furthermore, some systems allow threads to execute in parallel in different CPU cores.

This means that programmers do not know what set of threads is executing at any given time, so they must be careful with concurrent access to the shared memory state. They have to use synchronization primitives like locks and semaphores to synchronize access to some data.

The solution is, Event-driven programming is a programming style whereby the flow of execution is determined by events. Events are handled by event handlers or event callbacks. An event callback is a function that is invoked when something significant happens — such as when the result of a database query is available or when the user clicks on a button. 

This style of programming — whereby instead of using a return value you define functions that are called by the system when interesting events occur — is called event-driven or asynchronous programming. 

The event-driven programming style is accompanied by an event loop. An event loop is a construct that mainly performs two functions in a continuous loop — event detection and event handler triggering. In any run of the loop, it has to detect which events just happened. Then, when an event happens, the event loop must determine the event callback and invoke it.

Module publish in Node.js




To upload or module  to npm repository we need to create a user account
command : npm adduser

To push our own module in to npm repository  we need to create the package json file. For that we have to do some step to complete

1) Go to project folder using terminal and command
npm init

2) This will create a package.json Which contain all the details about the module. During the process fill the detail that system asks

3) After creation of the user upload using
command : npm publish

4)Tthen we can search the packate in npmjs.org location with our module name.

NOTE: The module can be updateable using the npm publish command .but now we have to change the version in package.json file. After the change of version simply update the module using npm publish

Write File with Sync and Async using Node.js



Writing the file using file system module. we have two options to process synchronous and asynchronous. Here we are testing on synchronous of the node.js. The sequence of code should wait until we write the sample txt file. For that waiting we are using writeFileSync class from File system module.

var file = require("fs");
console.log("Starting...");

var contents = file.writeFileSync("./write_file.txt", "Text to Write");
console.log(" done ...");

Here we are testing on asynchronous of the node.js. The sequence of code should not wait until we read the sample txt file. For that we are using callback function.

var file = require("fs");

console.log("Starting...");

var contents = file.writeFile("./write_file.txt", "Text to Write",
function(error){
console.log("written file");
}
);

console.log(" done ...");

Read the file sync and async using Node.js



Reading the file using file system module. we have two options to process synchronous and asynchronous. Here we are testing on synchronous of the node.js. The sequence of code should wait until we read the file sample txt file. For that waiting we are using readFileSync class from File system module.

var file = require("fs");
console.log("Starting...");

var content = file.readFileSync("./sample.txt");
console.log("Content : " + content);
console.log("Keep going ...");

If we run the file in node. First it will print the sample txt and after that only it will print the “Keep going” String. Because it is waiting for the read command finish.

Here we are testing on asynchronous of the node.js. The sequence of code should not wait until we read the sample txt file. For that we are using callback function.

var file = require("fs");
console.log("Starting...");

file.readFile("./sample.txt",
       function (error,data){
           console.log("Contents" + data);
});
console.log("Keep going ...");

This will not wait until read the file So it will print the “Keep going” first . After that only it will return the text file content.

Express module in Node.js


Express is the high performance and high class web development module package for Node . Which will process on top of the HTTP module and call the http class. Therefore we can create website with less of an effort and clean.

To install express module,
npm install express in linux terminal.

use npm list command to check what are the module listed in your on your project. Check the update of the module because according to the update the class calling method can be vary. For example,

Express older version: var app = express.createServer();
Express newer version: var app = express();

So this kind of change mentioned in module doc.

Sample Code :

var file = require("fs");
var config = JSON.parse(file.readFileSync("config.json"));
var host = config.host;
var port = config.port;

//include the express module
var express = require('express');
var app = express();

//check the original route path
app.use(app.router);

//express the static file location (Say if we have our html file in public folder)
app.use(express.static(__dirname + "/public"));

app.get("/", function(request, response){
//Sending the response to client
response.send('hello world');
});

/*Any URl come with /hello/ then we can redirect to our public directory here we print the text which is continue with /hello/ */
app.get("/hello/:text",
   function(request,response){
       response.send("hello" + request.params.text);
   }
);
//file format similar to JSON format
var users = {
       "1" : {
               "name" : "user 1",
               "Social" : "user 1 link"
               },
       "2" : {
               "name" : "user 2",
               "Social" : "user 2 link"
               }
};

/*Getting the user by ID. Here we search in broweer as 127.1.1.1:1336/user/1 because our host is 127.1.1.1 and port is 1336*/
app.get("/user/:id",
   function(request,response){
       var user = users[request.params.id];
       if(user){
        response.send("<a href://faceboo.com>" + user.Social + "view me " + user.name+"</a>");
       }else{
           response.send("Sorry! User not found",404);
       }

   }
);


app.listen(port,host);

1)run the .js file using node extension
2) call the user id with hello/id

NOTE:config.json file contain the host and port address .see the doc

Package Manger in Node.js


The Package manager is like a library for Node.js. From this package manager the classes and function can be importable . The node has repository  www.npmjs.org to upload and download modules for Node.js. The most interesting modules are express and mongodb and more.

We have to install npm manager in our machine .usually this will automatically installed when we install the node.js. If not we can download install the npm manager using linux terminal command
sudo apt-get install npm

Also each module has it’s own website. Which describe the module functions and the classes. For example we have a module call underscore and also this has own page call www.underscore.org this supports lots fo libraries in JavaScript.

After the installation of the npm Package manager we can download the module using the linux terminal command
1) Go to project directory using linux terminal
2) In terminal command : npm install underscore ( underscore is the name of the package)
3) It will go to npm registry, fetch and download into your directory which is a node_module directory. which contain       underscore (Library ) source code
4) If you import the module into your project directory then it can be automatically importable in projects using,
var name = require(“underscore”) // underscore is just a library name

The module read the details using package.json which is in the module directory.

ERROR:
node.js:201
       throw e; // process.nextTick error, or 'error' event on first tick
             ^
Error: Cannot find module 'graceful-fs'
   at Function._resolveFilename (module.js:334:11)
   at Function._load (module.js:279:25)
   at Module.require (module.js:357:17)
   at require (module.js:368:17)
   at Object.<anonymous> (/usr/share/npm/lib/utils/ini.js:32:10)
   at Module._compile (module.js:432:26)
   at Object..js (module.js:450:10)
   at Module.load (module.js:351:31)
   at Function._load (module.js:310:12)
   at Module.require (module.js:357:17)
dhanushanth@ubuntu:~$

If you got any error like above . Then the problem is with the older version of node. So you need to update the node.js version or we have another solution as well.

Solution : This will install the npm according to our node.js version

git clone git://github.com/isaacs/npm.git
cd npm/scripts
chmod +x install.sh
sudo ./install.sh


Npm library global installation
Another place that we can install the node_module globally which means that we can install this once as global
To install that command in terminal,
sudo npm install underscore -g

After the installation we can update the module using below command,
npm update _PackageName_


Search for package
In www.npmjs.org we can search for packages in search package after the search we just need to get the name of the package and install the module using the same way that we have done for unsercore


Note: Always check the updates of the package doc for changes. Because according the update the classes and function calling may be chage.

Import_Config_file_NodeJs


Here we can make our work more easier because we can list our data in json file and call the needed data in application. In this example I defined the host and port address in config file and call the values in my project file. Also here we are using watch class from file system module. This is very help full in real time server management. Because without stopping the server the port and host address can be changeable. For example if we have the address for the host and port in config.json then it can be update in realtime without stopping the server.

Sample of config file
save as config.json (name can be vary)
{
"port" : 1336,
"host" : "127.1.1.1"
}


var http = require("http");

var file = require("fs");

console.log("Starting");

/* Call the JSON formatted config file to read the host and port values . Here we used the readFileSync class from File system module. The FileSync class use to make wait the bellow code until it read the config file - After Sync only the other code will proceed */
var config = JSON.parse(file.readFileSync("config.json"));

// Host and Port Address which are read from config
var host = config.host;
var port = config.port;

var server = http.createServer(
function(request,response){
console.log("Received request: " + request.url);
//here “.” space we have to define our file path Ex: ./Dir
file.readFile("." + request.url,
function(error,data){
if(error){
response.writeHead(404,{"Content-type":"text/plain"});
response.end("Sorry the page was not found");
}else{
response.writeHead(200,{"Content-type":"text/Html"});
response.end(data);
}
});
});

server.listen(port,host,
function(){
console.log("listening " + host + ":" + port);
}
);



/*The watchFile class is automatically search for any changes in config file with the frequent time interval. If it get any update from that file. Then it will return to the system with the changes*/
file.watchFile("config.json",
function(){
config = JSON.parse(file.readFileSync("config.json"));
server.close();
host = config.host;
port = config.port;
//Listen to newport when we update the config.json file
server.listen(port,host,
function(){
console.log("New listening " + host + ":" + port);
});
});



HTML or File call in Node.js


Before to Start please read the 3_Http_Request Doc. This is use to read a html file which is in our disk. push in to browser according to client request.

var http = require("http");
// Import File system module to read the file
var file = require("fs");

console.log("Starting");

var host = "127.1.1.1";
var port = 1337;

/* Creating a callback which fired every single request that contain the url from client request and response is similar as request*/
var server = http.createServer(
function(request,response){
console.log("Received request: " + request.url);

//After we receive the file then we have to read the file from the request URL
file.readFile("." + request.url,
function(error,data){
/* Here we have error object and Data Object in function. So error and data can be return to that specific variables. Therefore If we have error we have to respond to user with predefined String else we have to return the file*/
if(error){
//404 is the status code for not found
response.writeHead(404,{"Content-type":"text/plain"}); response.end("Sorry the page was not found");
}else{

//here our file system is Html so the content type is html
response.writeHead(200,{"Content-type":"text/Html"});
response.end(data);
}
});
});

server.listen(port,host,
function(){
console.log("listening " + host + ":" + port);
}
);

After the code completes,
1) Go to project directory using terminal
2) command : node fileName.js
3) If the server starts Go to web browser and  type http://127.0.0.1:1337/name.html
4) you will get the result as html page or error message depend on the request in browser.