Monday, 8 April 2013
Sunday, 24 March 2013
Sunday, 17 March 2013
Google search engine
http://www.google.com/cse/tools/create_onthefly
<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form name="cse" id="searchbox_demo" action="http://www.google.com/cse">
<input type="hidden" name="cref" value="" />
<input type="hidden" name="ie" value="utf-8" />
<input type="hidden" name="hl" value="" />
<input name="q" type="text" size="40" />
<input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>
Quiz in HTML 5
http://www.questionwriter.com/
<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form name="cse" id="searchbox_demo" action="http://www.google.com/cse">
<input type="hidden" name="cref" value="" />
<input type="hidden" name="ie" value="utf-8" />
<input type="hidden" name="hl" value="" />
<input name="q" type="text" size="40" />
<input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>
Quiz in HTML 5
http://www.questionwriter.com/
Labels:
Web Programming
Friday, 8 March 2013
Useful links
JavaScript tutorial
https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript
Free SEO tools
http://tools.seobook.com/#premiumw
www.freeseoanalysis.org
PHP tutorial
http://coredogs.com/lesson/php-outputs-html
http://net.tutsplus.com/tutorials/php/how-to-create-a-phpmysql-powered-forum-from-scratch/
https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript
Free SEO tools
http://tools.seobook.com/#premiumw
www.freeseoanalysis.org
PHP tutorial
http://coredogs.com/lesson/php-outputs-html
http://net.tutsplus.com/tutorials/php/how-to-create-a-phpmysql-powered-forum-from-scratch/
Labels:
Web Programming
Monday, 4 March 2013
Wednesday, 20 February 2013
Windows commands
2.3.2 Commands and tools (Windows) :-
Commands
1)date............ Display or set the date of the system
2)time............ Display or set the time of the system
3)ver............. Display the MS-DOS version that is being used
4)dir.............. Display the list of subdirectories and files of a directory
5)cls.............. Clear the screen
6)mkdir,
md directory..Make a directory with the name “directory”
Example: md tools
7)chdir, cd directory.. Display the name or change the current directory to “directory”
Example: cd tools
8)rmdir, rd directory.. Delete the directory with the name “directory”
Example: rd tools
9)tree directory....... Display the structure of folders of a path in text-graphic format
Example: tree c:\tools
10)chkdsk......... Check a disk and show a status report
11)mem........... Show the amount of memory used and free in the system
12)rename,
ren source dest
.......Change the name of files
Example: ren oldname newname
13)copy source dest....... Copy one or more files to another location
Example: copy c:\tools\myfile.txt c:\tmp
14)move source dest....... Move files and change the name of files and directories
Example: move c:\tools c:\tmp
15)type file............. Type the content of one or more text files
Example: type c:\tools\myfile.txt
16)more file........... Display the information screen by screen
Example: more c:\tools\myfile.txt
17)delete, del file....... Delete one or more files
Example: del c:\tools\myfile.txt
you can check many commands from net
Note: The words in italics are not commands, and must be replaced by the desired
values. Some of the commands can be used by typing either their long version or short
version; for example, "delete" and "del‚" are the same command.
Tools :-
1)ping host Verify contact with the machine “host”
The command ping sends "packets" using ICMP (Internet Control
Message Protocol) to another computer, to learn whether it is
accessible through the network. In addition, it shows a statistical
summary about the percentage of packets that have not been
answered and the response time. The name of the machine can
be used directly or its IP address.
Examples: ping http://www.google.com
ping 193.145.85.2
Some options are:
- n N: send N packets
- t: ping the specified host until stopped (press CTRL+C to end)
To see more options: ping /h
2)tracert host Show the route that packets follow to reach the machine “host”
The command tracert is the abbreviation of trace route, which
allows you to learn the route that a packet follows from the origin,
(your machine) to the destination machine. It can also tell you
the time it takes to make each jump. At the most, 30 jumps will be
listed. It is sometimes interesting to observe the names of the
machines through which the packets travel.
Some options are:
- h N: to specify N, at the most, jumps.
- d: to not show the names of the machines.
To see more options: tracert
3)ipconfig Display information on the active interfaces (ethernet, ppp, etc.)
in the computer.
Some options:
/all: to show more details
/renew name: renews connection with “name” when automatic
configuration with DHCP is used.
/release name: deactivates all matching connections when
automatic configuration with DHCP is used.
To see more options: ipconfig /?
4)route print Display the routing table
The command route serves to define static routes, to erase routes
or simply to see the state of the routes.
Some options:
print: to show the list of routes.
delete: to delete a route.
add: to add a route.
To see more options: route/?
5)netstat Displays information on the status of the network and established
connections with remote machines.
Some options:
-a: To sample all the connections and listening ports
-n: to display addresses and port numbers in numeric form
-e: to sample Ethernet statistics
For example: netstat - an
To see more options: netstat/?
Commands
1)date............ Display or set the date of the system
2)time............ Display or set the time of the system
3)ver............. Display the MS-DOS version that is being used
4)dir.............. Display the list of subdirectories and files of a directory
5)cls.............. Clear the screen
6)mkdir,
md directory..Make a directory with the name “directory”
Example: md tools
7)chdir, cd directory.. Display the name or change the current directory to “directory”
Example: cd tools
8)rmdir, rd directory.. Delete the directory with the name “directory”
Example: rd tools
9)tree directory....... Display the structure of folders of a path in text-graphic format
Example: tree c:\tools
10)chkdsk......... Check a disk and show a status report
11)mem........... Show the amount of memory used and free in the system
12)rename,
ren source dest
.......Change the name of files
Example: ren oldname newname
13)copy source dest....... Copy one or more files to another location
Example: copy c:\tools\myfile.txt c:\tmp
14)move source dest....... Move files and change the name of files and directories
Example: move c:\tools c:\tmp
15)type file............. Type the content of one or more text files
Example: type c:\tools\myfile.txt
16)more file........... Display the information screen by screen
Example: more c:\tools\myfile.txt
17)delete, del file....... Delete one or more files
Example: del c:\tools\myfile.txt
you can check many commands from net
Note: The words in italics are not commands, and must be replaced by the desired
values. Some of the commands can be used by typing either their long version or short
version; for example, "delete" and "del‚" are the same command.
Tools :-
1)ping host Verify contact with the machine “host”
The command ping sends "packets" using ICMP (Internet Control
Message Protocol) to another computer, to learn whether it is
accessible through the network. In addition, it shows a statistical
summary about the percentage of packets that have not been
answered and the response time. The name of the machine can
be used directly or its IP address.
Examples: ping http://www.google.com
ping 193.145.85.2
Some options are:
- n N: send N packets
- t: ping the specified host until stopped (press CTRL+C to end)
To see more options: ping /h
2)tracert host Show the route that packets follow to reach the machine “host”
The command tracert is the abbreviation of trace route, which
allows you to learn the route that a packet follows from the origin,
(your machine) to the destination machine. It can also tell you
the time it takes to make each jump. At the most, 30 jumps will be
listed. It is sometimes interesting to observe the names of the
machines through which the packets travel.
Examples: tracert http://www.google.com
tracert 193.145.85.2Some options are:
- h N: to specify N, at the most, jumps.
- d: to not show the names of the machines.
To see more options: tracert
3)ipconfig Display information on the active interfaces (ethernet, ppp, etc.)
in the computer.
Some options:
/all: to show more details
/renew name: renews connection with “name” when automatic
configuration with DHCP is used.
/release name: deactivates all matching connections when
automatic configuration with DHCP is used.
To see more options: ipconfig /?
4)route print Display the routing table
The command route serves to define static routes, to erase routes
or simply to see the state of the routes.
Some options:
print: to show the list of routes.
delete: to delete a route.
add: to add a route.
To see more options: route/?
5)netstat Displays information on the status of the network and established
connections with remote machines.
Some options:
-a: To sample all the connections and listening ports
-n: to display addresses and port numbers in numeric form
-e: to sample Ethernet statistics
For example: netstat - an
To see more options: netstat/?
Labels:
System Administration
Tuesday, 19 February 2013
Cloud computing
Cloud computing
Introduction
Cloud
computing was and is still a much discussed subject in the field of computing
and the internet. This happens because this technology has a lot of strong
advantages but disadvantages as well. This technology enables centralized
communication with computer resources and data over the network. These
resources including computers, servers, printers, video game consoles, etc are
connected to the wider network infrastructure. Data is usually stored in
servers located in massive data centres. It is not a new concept, as its
general idea is based on an older computing model known as “Timesharing”. It is the result of more than forty years of evolution. Cloud computing nowadays, is
evolving faster than ever before, and day by day, the number of companies using
is increasing. In this article we are going to present both some of its
strengths and weaknesses and how it works.
Cloud structure
The
principal structure of Cloud computing involves two parts which are connected
to each other via a network:
The Front end
In a “Front end” example, a computer acts as a client and
includes the application needed to gain access to the back end (Cloud service).
Such applications are known as APIs (Application Programming Interface). APIs
are protocols used as user interfaces for providing various functions of
software communication.
The
best way to think about cloud computing is “Data Centre with API”. [3]
Different applications use different interfaces. Some
applications enable network connection directly through the web (e.g. e-mail)
and some others through specifically designed network interfaces.
The Back end
The Back end
In a “Back end”
example, the cloud service is communicating with a client’s computer. A cloud contains
servers, computers, network routers, database storage machines and more. Also
there are applications stored there, such as video editing, video gaming, word
processing and anything that can fit in software. These applications can be
accessed by a client computer, via communicating with the corresponding
application’s servers as shown in Figure1.
A control node,
typically a central server is used for administrating and monitoring the whole
network’s operation.
Most of services
provided, are transparently delivered, without the physical server knowing much
about where the data is actually stored. This concept is similar to
virtualization, where multiple resources seem like a single one.
In server environments,
virtualization has become the norm with hypervisors providing for increased
flexibility and improved utilization of physical assets [4].
Storage
Storing
of the data takes place in massive data centers (Figure 2). Data centers house
server machines, which act as database or application storage mediums.
As we know, servers often require maintenance or repair, and
thus it is important to store copies of the data in multiple places. This is
done or should be done to achieve redundancy
of data. Without it, a cloud service provider cannot ensure its
clients anywhere and anytime access of data. Also data is stored in servers
using different power supplies or located in different places, to overcome the sub-sequence of a power failure event.
As
we noted earlier, servers can store both data and applications. Some
applications are web-based and can access the cloud through an internet
browser. Such applications include:
- Web mail
· - Social
networking
· - Multimedia
albums
· - Video
hosting
· - Online
gaming
· - Online
documents
In
the other hand, some applications require the use of specific network enabled
interfaces. Such applications include:
· - Antivirus
software
· - Network
monitoring tools
· - Operating
system/software updating
· - Data
sharing (Drop box)
Advantages of the
Cloud
Cost
The
most important advantage is that it can reduce the cost of the infrastructure,
of a company using it. It is easier to maintain and upgrade, because network infrastructure
is centrally located and can be accessed both remotely and locally.
Storage
Storage
space in a cloud can be continuously expanded, as there is no limit in disk
sizes. Data is hosted in third party servers and it is the host’s
responsibility to take care of such issues. Such data can be accessed via a
web-based interface, e.g. Google’s “drive” feature, which enables saving files
on the cloud.
Backing
up and recovery of data is also easier to be implemented. Most third parties
will keep copies of the data, and thus it will be easier for it, to be
recovered. Furthermore, data is stored in a safer place than a local physical device,
in terms of objective loss or destruction of data. This reliable and redundant
storage of data can provide strong “Business continuity” and “Disaster recovery”.
A minor concern about storage, is that despite that most cloud services try to issue storage concerns via redundancy,
there's still the possibility that an entire system could be destroyed (e.g.
fire, flooding), and data will be lost completely. So it is important not only
to store data in different logical places but in physical too.
Subjective
loss, theft and privacy of this data issues will be discussed later.
Remote access
Data
stored in the cloud, can be accessed from anywhere at any given time, given
that a network connection is provided. This enables geographical and time
independence. An employer of a company can retrieve his office work from
whenever he wants and thus improve his productivity. Carriage of physical
storage devices is not needed, and thus possibility of physically losing it is
not present. Other people can also be enabled to access your data remotely.
Disadvantages of the
Cloud
Security
Cloud
computing means Internet computing [5].
The
biggest disadvantage of the internet today, is security. And the same happens
for the cloud services, as those reside on the internet. Cloud data, is stored
in third party servers and thus is vulnerable to loss or theft. Some hosting
providers can be more reliable than others and hence it is important to choose
the best one. As cloud service’s use
increase, more and more hackers will try to break into the system. This reveals
that strong encryption, decryption and authentication schemes need to be used. RADIUS protocol is an example of this discipline
applied to a server infrastructure, and which provides a decent level of data
protection.
Technical issues
Cloud computing need more
resources, smarter computers and thus more capable processor units. There is
also the need of excellent, 24/7 internet connection. If for any reason
connections fail, the ability to access and upload data will be hugely affected.
Also there will be times where systems will face hardware or software malfunctions,
and if not back-up plans are deployed a serious outage will be caused. A company
served by a cloud service provider, should also keep back-ups of its data
locally too. This again reveals the lack of reliability of the cloud. If so
many measures need to be taken, then what is for?
A serious service outage who I experienced myself too, was
the Playstation network’s one, which lasted for 25 days and affected millions
of users. In this case hackers attacked user accounts and the service had to
face major changes in security [6]. Users pay a lot of money to such services,
and are expecting their information to be kept securely and have 24/7 service
available.
Privacy
Nowadays
tons of user data resides on the internet. If somebody thinks that is not a
cloud service user, then he should think twice. Facebook, twitter, gmail are
only some of the web-applications that are keeping our personal information of
all sorts of things. This data is circulated and stored in unknown third party
storage places. Of course most of these provide service level agreement
contracts that will cover various privacy concerns. Personal data should be
processed in accordance to these contracts. Legal measures will be able to
cover most of these concerns, but in some cases the laws will be applied only
within the country that the company or the service resides. Legalisation of
different areas of IT is very challenging and complicated, and will always
struggle people and companies
Conclusion
Like most IT technologies, we saw that cloud computing too
carries a lot of advantages and disadvantages. While the technology is totally
evolutionary, it can also cause great harm to an amateur user, who do not
understand and use it properly.
Most of people nowadays are unaware that the whole internet
is dominated by cloud services. Therefore I believe that some computing privacy
and security issues should be taught to younger people in schools, because by
that way, they will possess a greater awareness of the dangers that surround
the current and upcoming use of the internet.
From a business perspective, we saw that a very big
opportunity is opened for smaller and bigger IT companies. The evolution of
internet and computing speeds, gives the ability for efficient virtualisation
and remote storage of data, with lots of benefits. It is up to the companies to
fulfil user needs and eliminate the presence of some disadvantages. As internet
security evolves and improves, so cloud computing will become better and more
trusted.
Nikolas Georgiou
Nikolas Georgiou
Prime number calculator
import java.util.Scanner;
//Start of class PrimeNumbers
public class PrimeNumbers {
/** Static boolean method that checks if an integer number is prime
* or not and returns true or false correspondingly
*/
static boolean checkNumber(int number){
//for loop for checking integer numbers
for(int i=2;i<number;i++){
//if statement returning false if a number
//has not a remainder after division with number 2
if(number%i==0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int num;
Scanner scanNumber= new Scanner(System.in);
System.out.print("Please enter a number: ");
//Reads an integer value
num=scanNumber.nextInt();
//if-else statement to check if the entered number is negative
if (num<0){
//if statements executed if entered number is negative
System.err.println("Error!You inserted a negative number");
System.err.println("The program will now exit");
//Terminates the program
System.exit(0);
}
//else statements executed if the entered number is not negative
else {
//Boolean variable for storing checkNumber method's variables
// and checks if a number is prime or not
boolean prime=checkNumber(num);
//if checkNumber method returns true
if (prime==true){
System.out.println("Is prime");
}
//if checkNumber method returns false
else{
System.out.println("Is not prime");
}
System.out.println("Prime numbers <= entered number are:");
//for loop for checking all entered numbers
for(int i = 2; i <= num; i++ ){
//prime variable set to true
prime = true;
//for loop for checking and printing prime
//numbers between 2 and the entered number
for(int j=2; j <= i/2; j++) {
//if statement that sets prime variable as false
//if the number is not prime
if (i%j == 0){
prime = false;
}
}
//If statement that is executed not only if a number is prime
if (prime){
//Displays numbers seperated by a comma
System.out.print(i+",");
}
}
}
}
//End of class PrimeNumbers
}
Multithreaded Web Server
import java.io.* ;
import java.net.* ;
import java.lang.*;
import java.util.* ;
//Start of class HttpRequest
final class HttpRequest implements Runnable
{
final static String CRLF = "\r\n";
public final static int SO_KEEPALIVE = 0x0008;
//Set the default homepage to "index.html"
private static final String DEFAULT_PAGE = "index.html";
Socket socket;
//Constructor
public HttpRequest(Socket socket)throws Exception
{
this.socket = socket;
}
//Implement the run()method of the Runnable interface
public void run()
{
try{
processRequest();
}
catch (Exception e){
System.out.println(e);
}
}
//processRequest() method that processes individual HTTP requests
private void processRequest() throws Exception
{
String sentence;
//Get a reference to the socket's input and output streams
DataOutputStream os = new DataOutputStream (socket.getOutputStream());
//Set up input stream filters
BufferedReader bfReader = new BufferedReader (new InputStreamReader(socket.getInputStream()));
sentence = bfReader.readLine() ;
//Get the request line of the HTTP request message.
String requestLine = sentence;
//Display the request line in a structured way
System.out.println();
System.out.println("HTTP request message:");
System.out.println("---------------------");
System.out.println(requestLine);
os.writeBytes("HTTP request message:"+CRLF);
os.writeBytes("---------------------"+CRLF);
os.writeBytes(requestLine+CRLF);
//Get and display the header lines.
String headerLine;
while ((headerLine = bfReader.readLine()).length()!= 0){
System.out.println(headerLine);
}
//Split the request line on white space
String [] tokens=requestLine.split("\\s+" ,3);
String fileName = tokens[1]; // second element is filename
//Prepend a "." so that file request is within the current directory
fileName = "."+fileName;
//Filenames values is assigned with a file in the directory
fileName = "homepage.html";
FileInputStream fis = null;
boolean fileExists=true;
try{
fis = new FileInputStream(fileName);
}
catch(FileNotFoundException e)
{fileExists = false;}
try {
boolean append=true;
//Initialise log string's value according to common log format
String log= InetAddress.getLocalHost()+" ["+(new Date()).toString()+"]" +" "+requestLine+" "+(new Integer(fis.available())).toString() ;
//Write each web log generated to a text file
BufferedWriter out = new BufferedWriter(new FileWriter("webLogs.txt",append));
out.append(log);
//Writes each log line by line in the text file
out.newLine();
//closes the stream
out.close();
}
catch (IOException |NullPointerException e)
{
System.out.println("Log File Exception");
}
//Construct the response message
String statusLine = null;
String contentTypeLine = null;
String contentLengthLine =null;
String entityBody="error";
//New string hash for storing the MD5 hash's value
String hash="";
//Password is obtained from the URL's content
String password =requestLine;
//Username is obtained from the URL's content
String user =requestLine;
//URL is splitted in parts using the = symbol as delimiter
String delimiter = "=";
//Array of string to hold the split values of the URL
String[] entry1;
//Some parts of the URL are then thrown away
user = user.replace("&pw","");
entry1 = user.split(delimiter);
// //Array of string to hold the split values of the URL
String[] entry2;
//Some parts of the URL are then thrown away
password = password.replace("&action","");
entry2 = password.split(delimiter);
//If the filename is in the linked directory return the corresponding message
if (fileExists){
statusLine = "HTTP/1.0 200 OK";
contentTypeLine = "Content-type:" + contentType(fileName);
//Return the size of the file in bytes
contentLengthLine = "Content-length:" + (new Integer(fis.available())).toString();
}
//Else if the filename is not in the linked directory return the corresponding message
else{
statusLine = "HTTP/1.0 404 Not found";
contentTypeLine="Content-type:text/html";
entityBody ="<HTML>"+
"<HEAD><TITLE>404 Not Found</TITLE></HEAD>" +
"<BODY>404 Not Found"+"</BODY></HTML>" ;
//Return the size of the file in bytes
contentLengthLine="Content-length:" +(new Integer(entityBody.length()).toString());
}
//Try catch block for displaying authentication's output if carried out
try{
//Password string is assigned with the new extracted from the URL value
password=entry2[2];
hash=MD5(password);
//Display the username,password and MD5 hash code to the system
System.out.println("----------------------");
System.out.println("Username:"+entry1[1]);
System.out.println("Password:"+entry2[2]);
System.out.println("MD5 hashcode:"+hash);
//If the URL's size is smaller than 48 bytes and credentials were not entered,
//an error that authentication was not carried out is displayed in the HTTP request.
if(requestLine.length()<48){
statusLine = "HTTP/1.0 403 Forbidden";
contentTypeLine="Content-type:text/html";
entityBody ="<HTML>" +
"<HEAD><TITLE>403 Forbidden</TITLE></HEAD>" +
"<BODY>NOT AUTHENTICATED" +
"</BODY></HTML>" ;
contentLengthLine="Content-length:" +(new Integer(entityBody.length()).toString());}
}
catch(ArrayIndexOutOfBoundsException|NullPointerException e)
{hash="";}
//Send the Status line to server
os.writeBytes(statusLine+CRLF);
os.writeBytes(contentTypeLine+CRLF);
//Send the content length line
os.writeBytes(contentLengthLine+CRLF);
//Print a timestamp of the request
os.writeBytes("Request Date:" + (new Date()).toString() + "\n");
//Send a blank line to indicate the end of the header lines.
os.writeBytes(CRLF);
//Print the lines in the system output as well
System.out.println("--------------------");
System.out.println(statusLine);
System.out.println(contentTypeLine);
System.out.println(contentLengthLine);
//Print a timestamp of the request
System.out.println("Last Modified:" + (new Date()).toString());
System.out.println("--------------------");
//Flush the output
System.out.flush();
//Send the entity body
if (fileExists){
sendBytes(fis,os);
fis.close();
}
else{
os.writeBytes(entityBody);
}
//Close streams and sockets
os.close();
bfReader.close();
socket.close();
}
//Method to calculate an MD5 checksum of the entered password String in the HTML form
private static String MD5(String password) {
try {
//Create an object from java's security library
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(password.getBytes());
StringBuilder sb = new StringBuilder();
//For loop for calculating each digit of the hash string
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
}
//returns the hash string
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {}
return null;
}
//ContentType() method that returns a String included in the content type line
private static String contentType(String fileName)
{
//if filename is of type html return the corresponding string
//and so on..
if(fileName.endsWith(".htm")|| fileName.endsWith(".html"))
{ return "text/html";}
if(fileName.endsWith(".txt")|| fileName.endsWith(".text"))
{ return "text/plain";}
if(fileName.endsWith(".gif")|| fileName.endsWith(".ico"))
{ return "image/gif";}
if(fileName.endsWith(".xml"))
{ return "text/xml";}
if(fileName.endsWith(".png"))
{ return "image/png";}
if(fileName.endsWith(".jpeg")|| fileName.endsWith(".jpg"))
{ return "image/jpeg";}
//otherwise return this string
return "application/octet-stream";
}
//Method sendBytes
private static void sendBytes(FileInputStream fis, OutputStream os)
throws Exception
{
//Construct a 1K buffer to hold bytes on their way to the socket.
byte[] buffer = new byte[1024];
int bytes = 0;
//Copy requested file into the socket's output stream.
while((bytes = fis.read(buffer))!= -1){
os.write(buffer, 0, bytes);
}
//close the file input stream
fis.close();
}
//End of class HttpRequest
}
_________________________________________________________________________________
import java.net.* ;
import java.lang.*;
import java.util.* ;
//Start of class HttpRequest
final class HttpRequest implements Runnable
{
final static String CRLF = "\r\n";
public final static int SO_KEEPALIVE = 0x0008;
//Set the default homepage to "index.html"
private static final String DEFAULT_PAGE = "index.html";
Socket socket;
//Constructor
public HttpRequest(Socket socket)throws Exception
{
this.socket = socket;
}
//Implement the run()method of the Runnable interface
public void run()
{
try{
processRequest();
}
catch (Exception e){
System.out.println(e);
}
}
//processRequest() method that processes individual HTTP requests
private void processRequest() throws Exception
{
String sentence;
//Get a reference to the socket's input and output streams
DataOutputStream os = new DataOutputStream (socket.getOutputStream());
//Set up input stream filters
BufferedReader bfReader = new BufferedReader (new InputStreamReader(socket.getInputStream()));
sentence = bfReader.readLine() ;
//Get the request line of the HTTP request message.
String requestLine = sentence;
//Display the request line in a structured way
System.out.println();
System.out.println("HTTP request message:");
System.out.println("---------------------");
System.out.println(requestLine);
os.writeBytes("HTTP request message:"+CRLF);
os.writeBytes("---------------------"+CRLF);
os.writeBytes(requestLine+CRLF);
//Get and display the header lines.
String headerLine;
while ((headerLine = bfReader.readLine()).length()!= 0){
System.out.println(headerLine);
}
//Split the request line on white space
String [] tokens=requestLine.split("\\s+" ,3);
String fileName = tokens[1]; // second element is filename
//Prepend a "." so that file request is within the current directory
fileName = "."+fileName;
//Filenames values is assigned with a file in the directory
fileName = "homepage.html";
FileInputStream fis = null;
boolean fileExists=true;
try{
fis = new FileInputStream(fileName);
}
catch(FileNotFoundException e)
{fileExists = false;}
try {
boolean append=true;
//Initialise log string's value according to common log format
String log= InetAddress.getLocalHost()+" ["+(new Date()).toString()+"]" +" "+requestLine+" "+(new Integer(fis.available())).toString() ;
//Write each web log generated to a text file
BufferedWriter out = new BufferedWriter(new FileWriter("webLogs.txt",append));
out.append(log);
//Writes each log line by line in the text file
out.newLine();
//closes the stream
out.close();
}
catch (IOException |NullPointerException e)
{
System.out.println("Log File Exception");
}
//Construct the response message
String statusLine = null;
String contentTypeLine = null;
String contentLengthLine =null;
String entityBody="error";
//New string hash for storing the MD5 hash's value
String hash="";
//Password is obtained from the URL's content
String password =requestLine;
//Username is obtained from the URL's content
String user =requestLine;
//URL is splitted in parts using the = symbol as delimiter
String delimiter = "=";
//Array of string to hold the split values of the URL
String[] entry1;
//Some parts of the URL are then thrown away
user = user.replace("&pw","");
entry1 = user.split(delimiter);
// //Array of string to hold the split values of the URL
String[] entry2;
//Some parts of the URL are then thrown away
password = password.replace("&action","");
entry2 = password.split(delimiter);
//If the filename is in the linked directory return the corresponding message
if (fileExists){
statusLine = "HTTP/1.0 200 OK";
contentTypeLine = "Content-type:" + contentType(fileName);
//Return the size of the file in bytes
contentLengthLine = "Content-length:" + (new Integer(fis.available())).toString();
}
//Else if the filename is not in the linked directory return the corresponding message
else{
statusLine = "HTTP/1.0 404 Not found";
contentTypeLine="Content-type:text/html";
entityBody ="<HTML>"+
"<HEAD><TITLE>404 Not Found</TITLE></HEAD>" +
"<BODY>404 Not Found"+"</BODY></HTML>" ;
//Return the size of the file in bytes
contentLengthLine="Content-length:" +(new Integer(entityBody.length()).toString());
}
//Try catch block for displaying authentication's output if carried out
try{
//Password string is assigned with the new extracted from the URL value
password=entry2[2];
hash=MD5(password);
//Display the username,password and MD5 hash code to the system
System.out.println("----------------------");
System.out.println("Username:"+entry1[1]);
System.out.println("Password:"+entry2[2]);
System.out.println("MD5 hashcode:"+hash);
//If the URL's size is smaller than 48 bytes and credentials were not entered,
//an error that authentication was not carried out is displayed in the HTTP request.
if(requestLine.length()<48){
statusLine = "HTTP/1.0 403 Forbidden";
contentTypeLine="Content-type:text/html";
entityBody ="<HTML>" +
"<HEAD><TITLE>403 Forbidden</TITLE></HEAD>" +
"<BODY>NOT AUTHENTICATED" +
"</BODY></HTML>" ;
contentLengthLine="Content-length:" +(new Integer(entityBody.length()).toString());}
}
catch(ArrayIndexOutOfBoundsException|NullPointerException e)
{hash="";}
//Send the Status line to server
os.writeBytes(statusLine+CRLF);
os.writeBytes(contentTypeLine+CRLF);
//Send the content length line
os.writeBytes(contentLengthLine+CRLF);
//Print a timestamp of the request
os.writeBytes("Request Date:" + (new Date()).toString() + "\n");
//Send a blank line to indicate the end of the header lines.
os.writeBytes(CRLF);
//Print the lines in the system output as well
System.out.println("--------------------");
System.out.println(statusLine);
System.out.println(contentTypeLine);
System.out.println(contentLengthLine);
//Print a timestamp of the request
System.out.println("Last Modified:" + (new Date()).toString());
System.out.println("--------------------");
//Flush the output
System.out.flush();
//Send the entity body
if (fileExists){
sendBytes(fis,os);
fis.close();
}
else{
os.writeBytes(entityBody);
}
//Close streams and sockets
os.close();
bfReader.close();
socket.close();
}
//Method to calculate an MD5 checksum of the entered password String in the HTML form
private static String MD5(String password) {
try {
//Create an object from java's security library
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(password.getBytes());
StringBuilder sb = new StringBuilder();
//For loop for calculating each digit of the hash string
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
}
//returns the hash string
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {}
return null;
}
//ContentType() method that returns a String included in the content type line
private static String contentType(String fileName)
{
//if filename is of type html return the corresponding string
//and so on..
if(fileName.endsWith(".htm")|| fileName.endsWith(".html"))
{ return "text/html";}
if(fileName.endsWith(".txt")|| fileName.endsWith(".text"))
{ return "text/plain";}
if(fileName.endsWith(".gif")|| fileName.endsWith(".ico"))
{ return "image/gif";}
if(fileName.endsWith(".xml"))
{ return "text/xml";}
if(fileName.endsWith(".png"))
{ return "image/png";}
if(fileName.endsWith(".jpeg")|| fileName.endsWith(".jpg"))
{ return "image/jpeg";}
//otherwise return this string
return "application/octet-stream";
}
//Method sendBytes
private static void sendBytes(FileInputStream fis, OutputStream os)
throws Exception
{
//Construct a 1K buffer to hold bytes on their way to the socket.
byte[] buffer = new byte[1024];
int bytes = 0;
//Copy requested file into the socket's output stream.
while((bytes = fis.read(buffer))!= -1){
os.write(buffer, 0, bytes);
}
//close the file input stream
fis.close();
}
//End of class HttpRequest
}
_________________________________________________________________________________
import java.io.* ;
import java.net.* ;
import java.lang.*;
import java.util.* ;
public final class WebServer
{
public static void main(String argv[]) throws Exception
{
//set the port number
int port = 4040;
//Establish the listen socket
ServerSocket welcomeSocket = new ServerSocket (4040) ;
//Prints a message to inform the user that the server is running and on which port
System.out.println("Web server is running on port " + port + "... (press CTRL-C to quit)");
//Prints a message about the date of the session's starting point
System.out.println("Session started on:" + (new Date()).toString());
System.out.println();
//Process HTTP service requests in an infinite loop.
while (true){
//Listen for a TCP connection request
Socket connectionSocket = welcomeSocket.accept() ;
System.out.println();
//Prints out some information about the new connection
System.out.println("NEW CONNECTION ESTABLISHED:" +
InetAddress.getLocalHost() + ":" + connectionSocket.getPort());
System.out.println("------------------------------------------------------------");
try
{
//Set keep alive to true
connectionSocket.setKeepAlive(true);
//Set timeout to 5 minutes
connectionSocket.setSoTimeout(300000);
//Prints some information about the new connection
System.out.format("Send Buffer Size: %s\n", connectionSocket.getSendBufferSize());
System.out.format("Keep-Alive: %s\n", connectionSocket.getKeepAlive());
System.out.format("Socket Timeout: %s\n", connectionSocket.getSoTimeout()/60000+" minutes");
System.out.println();
}
catch (Exception e)
{e.printStackTrace();}
try{
//Construct an object to process the HTTP request message
HttpRequest request = new HttpRequest(connectionSocket);
//Create a new thread to process the request
Thread thread = new Thread(request);
//Start the thread.
thread.start();
}
catch(Exception e)
{ e.printStackTrace();
}
}
}
//End of class WebServer
}
Nikolas Georgiou
Labels:
Java Programming
Subscribe to:
Posts (Atom)