A Finalll Project Report On
A Finalll Project Report On
Bachelor of Technology
In
Computer Science and Technology
1|Page
Certificate
This is to certify that the project report entitled
“HTTP CACHING PROXY SERVER” submitted in partial fulfillment of the
requirements for the degree of Bachelor of the Technology in Computer
Science and Engineering done by Mr. Ranvijai Singh, Roll No. 0710410042
and Mr. Vijay Krishan Yadav, Roll No. 0710410057 is an authentic work
carried out by him at Department of Computer Science and Engineering under
my guidance. The matter embodied in this project has not been submitted earlier
for the award of any degree or diploma to the best of my knowledge and belief.
2|Page
ACKNOWLEDGEMENT
My foremost and profound gratitude goes to Mr. D.L. Gupta for his
proficient and enthusiastic guidance and encouragement. The suggestions given
undoubtedly helped in supplementing my thoughts in the right direction for
attaining the desired objective.
My heartfelt gratitude also goes to all the faculty members and Staff of
Kamla Nehru Institute of Technology, Gautam Buddha Technical University
who have contributed directly or indirectly towards the successful completion of
this report.
Ranvijai Singh(0710410042)
Vijay Krishan Yadav(0710410057)
3|Page
Content and order of the Project report:
1) Introduction……………………………………………………6
3.1 Objective
3.2 Scope
3.3 Motivation
3.4 Problem Definition
3.5 Technologies Used
3.6 Organization of the Report
2) Background……………………………………………………
3) Project Description
3.1 SRS…………………………………………………….
1. Product Perspective
2. User Interfaces
3. Hardware Requirements of User
4. Software Requirements of User
5. Operations
6. Product Functions
7. User Characteristics
8. Constrains
3.2 Software System Attributes
1. Security
2. Quality
3. Measurement
3.3 Features
3.4 Disadvantage of the Current System
3.5 Advantage of the Proposed System
4) Project Design and Implementation…………………………..
4.1) Feasibility Study
4.2) Data Flow Diagram
4.3) Use Case Diagram
4.4) Development Schedule(Gantt Chart)
4.5) EER Diagram
4.6) Implementation
4.7) Code
4.8) Testing
4.9)Experimental Setup
4|Page
5) Project Output
6) Conclusion and Future Scope
a) Conclusion
b) Future Scope
Appendix
a) Coding
b) Gontt Chart
c) EER Diagram
d) Test Cases
Bibliography
5|Page
INTRODUCTION
1.1 OBJECTIVE:
◦ An HTTP proxy server is a server that handles HTTP requests from clients. If the
◦ Caching, which migrates documents across the network closer to the users, reduces
network traffic, reduces the load on popular Web servers and reduces the time that
1.2 SCOPE:
• Caching proxies keep local copies of frequently requested resources, allowing large
organizations to significantly reduce their upstream bandwidth usage and cost, while
• A caching proxy server accelerates service requests by retrieving content saved from
6|Page
1.3 MOTIVATION:
◦ A proxy server accepts requests from clients. When possible and desired, it
generates replies based upon documents stored in its local cache; otherwise, it
forewords the requests, transfers the replies to the clients and caches them when
possible.
◦ The proxy thus acts both as a server and as a client. It is a server when accepting
HTTP requests from its clients, but a client to the remote servers it connects to
Administrator can monitor activities of various users like which kind of web
This project is a step ahead process to solve the various problems we face in
It provides web pages from it’s cache instead of the original web page which
7|Page
1.6 ORGANIZATION OF THE REPORT:
This report is organized in the six chapters and few appendix:
INTRODUCTION gives a brief introduction about the project. It consist of Objective, Scope,
Motivation, Problem Definition and Technology Used as the sub headings which completely
summarizes about the whole project.
BACKGROUND gives a few details about the various technologies used in this project and
also explains in brief about the functioning of the various technologies.
PROJECT DESIGN & IMPLEMENTATION describes about the various designing phases
that the project undergoes such as Gantt chart and data flow diagram. Also includes the
documentation of them and the testing of the various modules incorporated within the project.
PROJECT OUTPUT includes the snapshots of the various screens that the project shows
while running in the real time.
FUTURE SCOPE & CONCLUSION gives the direction about the enhancement of the project
in various dimensions and also concludes the project report.
APPENDIX: It has three parts. Part A consists of , the code of few modules that is in the
project. Part B consists of the development schedule of the whole project described by the
Gantt Chart. And Part C includes the Entity Relationship Diagram (ERD) that is used for the
project. And the last part D includes the Test Case of the project
8|Page
2. BACKGROUND:
The most obvious compromise is to provide a single host with Internet access for all your
users. However, this isn't a satisfactory solution because these hosts aren't transparent to users.
Users who want to access network services can't do so directly. They have to log in to the
dual-homed host, do all their work from there, and then somehow transfer the results of their
work back to their own workstations. At best, this multiple-step process annoys users by
forcing them to do multiple transfers and work without the customizations they're accustomed
to.
The problem is worse at sites with multiple operating systems; if your native system is a
Macintosh, and the dual-homed host is a UNIX system, the UNIX system will probably be
completely foreign to you. You'll be limited to using whatever tools are available on the dual-
homed host, and these tools may be completely unlike (and may seem inferior to) the tools
you use on your own system.
Dual-homed hosts configured without proxies therefore tend to annoy their users and
significantly reduce the benefit people get from the Internet connection. Worse, they usually
don't provide adequate security; it's almost impossible to adequately secure a machine with
many users, particularly when those users are explicitly trying to get to the external universe.
You can't effectively limit the available tools, because your users can always transfer tools
from internal machines that are the same type. For example, on a dual-homed host you can't
guarantee that all file transfers will be logged because people can use their own file transfer
agents that don't do logging.
Proxy systems avoid user frustration and the insecurities of a dual-homed host. They deal
with user frustration by automating the interaction with the dual-homed host. Instead of
requiring users to deal directly with the dual-homed host, proxy systems allow all interaction
to take place behind the scenes. The user has the illusion he is dealing directly (or almost
directly) with the server on the Internet that he really wants to access, with a minimum of
direct interaction with the dual-homed host.
9|Page
3. PROJECT DESCRIPTION:
3.1. SRS:
1. Product Perspective:
Product is designed to solve the problems regarding use of internet services and speed related
with bandwidth and to enhance surfing facility and minimize load from server .
2. USER INTERFACES:
User interface of the product is interactive and easily understandable by the user.
* Service Pack 3
* TCP/IP
5. OPERATIONS:
• A cache/proxy server network conserves bandwidth, decreases network-
imposed latency, and offsets the load on the origin server from which the
10 | P a g e
connection from the origin server is required to upload content to and
• Additionally, the load on the origin server is offset because fewer clients
are connecting directly to it. These three factors result in a better viewing
6. PRODUCT FUNCTIONS:
▪ Caching
▪ Reduces Latency
▪ Bandwidth Conservation
▪ Increases accessibility
▪ Connection sharing
7. USER CHARACTERISTICS:
8. CONSTRAINS:
• The existing physical network, hardware, and operating systems place
• As you create your Proxy Server design, ensure that your design meets the
11 | P a g e
3.2. SOFTWARE SYSTEM ATTRIBUTES:
1. Security:
◦ By caching pages that have been previously requested, the proxy server
page using the cached information rather than going to the web site
again.
◦ When using a proxy server external systems only see the IP address of
The proxy server can also be configured with basic rules of what ports
2. Quality:
◦ A horizontal and vertical involvement of all concerned in project
all must be harnessed for strategic long term benefits. This is important
and procedures.
internet, it helps all to clear doubts if any in mind of any of the persons
3. Measurement:
◦ Hits
◦ Page View/Impression
3.3. FEATURES:
* It may rewrites the client's request.
* Multithreadi
13 | P a g e
3.4. DISADVANTAGE OF CURRENT SYSTEM:
* Less trafficking
* Reduces latency
* Conserves Bandwidth
* Good at Logging
when evaluating the feasibility of accessing online journals (whether from Africa or anywhere
else). Feasibility is of course a fluid concept, as most of the important factors are adaptable,
given the will, the knowledge, and the resources. Some of the issues are relatively simple
university policy matters, others more intransigent technical or financial matters. The key
factors include:
◦ The university’s Internet and local area network (LAN) setup: What type of server
14 | P a g e
much space is available for caching? How is the LAN set up (single ring? multiple
nodes?)
◦ The size of the user community relative to the available bandwidth: Is the user
◦ There are several possible reasons the connection worked so poorly at University.
One is that the LAN is a single physical ethernet segment connecting some one
thousand computers, with all those computers competing for LAN resources,
each other by an ethernet switch. This setup manages the traffic more efficiently,
as computers compete only with other computers in the same segment, and inter-
efficient, making it possible to add more terminals to the network with less
degradation of service. Another possible reason is that the problems were a result
of the way that Windows handles Internet data transfers. Downloading is a two-
way process involving data coming in and receipt confirmations going out. When
there is a delay in the incoming data, Windows slows down its response rate, but if
the incoming rate increases, Windows does not speed back up to match it. This
15 | P a g e
4.2. DATA FLOW DIAGRAM:
No
Generate
Data retrieved No error Yes Request
Has update
successfully
No
Yes
Does object
meet Mark in
Cacheable Yes cache
guidelines?
NO
16 | P a g e
4.3. USE CASE DIAGRAM:
the start and finish dates of the terminal elements and summary elements of a project.
Terminal elements and summary elements comprise the work breakdown structure of the
project. Some Gantt charts also show the dependency (i.e., precedence network) relationships
between activities.
17 | P a g e
4.5. EER Diagram:
In computer science, the enhanced entity-relationship (EER) model is a high-level or
conceptual data model incorporating extensions to the original entity-relationship (ER) model,
used in the design of databases. It was developed by a need to reflect more precisely
properties and constraints that are found in more complex databases, such as in engineering
4.6. Implementation:
It is very important part of software development as we complete our
software than we go for the installation of the software to the user end. Where we
keep in mind the h/w & s/w requirement and plus we also train the employee who do
not have knowledge of computers. Though we have made the software user friendly
but than also we prepare user manual to operate the software easily & safely. We
also bring out the changes in h/w if it would not support the software and same would
be the case with the s/w and operating system.
Implementation is the most important part of software development. In
this phase after the completion of the software we go for its installation on the
system. In this phase we keep in mind that it takes the minimum amount of software
and hardware requirements in order to perform its various tasks correctly and
accurately. The software should be such that even a naïve user can easily operate all
its functions properly.
In the implementation phase we make sure that the software is performing
all its desired tasks properly using the minimum possible software and hardware
requirements. In the implementation phase we make sure that the software is user
friendly so that any new user can easily operate on it.
I hope this software will fully satisfy the needs and requirements of Caching
Proxy Server.
18 | P a g e
4.7. CODE:
Coding is undertaken once the design phase is complete and the design documents have been
successfully reviewed. In the coding phase, every module identified and specified in the
design document is independently code and unit tested. Project coding is given under
Appendix A.
4.8. TESTING:
Objective of Testing:
◦ Testing is a process of the executing a program with the intent of the
finding an error.
◦ A good test case is one that has a high probability of the finding an as-yet
undiscovered error.
Testing can not show the absence of the defects, it can only show that
Testing principles:
4. Testing should begin “in the small” and progress toward testing “in the large”.
19 | P a g e
Type of Testing:
1. White-box Testing:
This testing is also known as “glass-box testing”. Using white-box testing, test
• Guarantee that all independent path with in a module have been exercised at
last once;
• Exercise all logical decisions on their boundaries and with in their operational
bounds; and
enables to derive set of the input conditions that will folly exercise all functional
20 | P a g e
Black-box attempts to find errors the following categories:
• Interface errors,
• Performance errors
machine, while the origin server on another machine (most likely in the same lab). You
might have some issues with making your proxy server talk to the remote server through
RMI because of firewall issues. Java RMI does not use port 80 for communication: by
default rmiregistry runs on port 1099 and then assigns some random ports to RMI
sockets). A representative of the Techstaff in the CS Department has assured me that all
the Linux machines in undergraduate labs are not firewalled for intra-domain access.
Windows machines are more heavily firewalled, but this still should not be a problem for
intra-domain access. You’ll have to find a setup that’ll make it possible for you to run all
your experiments. Since this is a Java-based project, you should have no problem running
for the hobbits. It reduced the effective browsing time for the common sites to a minimum and
21 | P a g e
b) FUTURE SCOPE:
The caching proxy server as stand-alone product is an endangered species.In its place, we'll
continue to see software firewalls expand their breadth to include the kind of content filtering,
caching, and authentication that was traditionally the role of the proxy server.
However, the testing process downloads webpages which consume network bandwidth, so
it
is suggested that in the future, it can re-use the statistical information from some existing
measurement system like perfSONAR, so that it need not download webpages frequently..
5. APPENDIX:
a) Coding:
Module 1: Server.java
import java.net.*;
import java.io.*;
import java.util.*;
import java.awt.*;
import proxy.Proxy;
import proxy.HttpReplyHdr;
import proxy.HttpRequestHdr;
import proxy.Configuration;
import proxy.ServerDataBase;
import proxy.Cache;
22 | P a g e
import proxy.ServersAccessibleWOProxy;
import proxy.DocumentInfo;
import proxy.ServerInfo;
import proxy.MainFrame;
/*
* Server
*/
int serverPort;
23 | P a g e
switch (args.length) {
break;
case 1: try {
serverPort = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
return;
return;
break;
return;
int initialNoOfThreads = 0;
24 | P a g e
MainFrame mainFrame = new MainFrame("HTTP Proxy Server",config);
mainFrame.updateLog("Initializing cache...");
cached...");
mainFrame.setServersAccessibleWOProxy(serversAccessibleWOProxy);
mainFrame.setCache(cache);
try {
mainFrame.serverSocket = serverSocket;
initialNoOfThreads = activeCount();System.out.println(initialNoOfThreads);
25 | P a g e
for (int i=1;i<4;i++) {
mainFrame.updateLog("welcome\n");
mainFrame.updateLog("hi\n");
serversAccessibleWOProxy, mainFrame);
thd.start();System.out.println("after proxy");if(i==1)
b.read();}
} catch (IOException e) {
} catch (Exception e) {
} finally {
try {
serverSocket.close();
} catch (Exception b ) {}
// yield();
config.shutDown(serverDataBase.shutDown() &&
26 | P a g e
cache.shutDown() &&
serversAccessibleWOProxy.shutDown());
System.exit(0);
Module 2: Proxy.java
package proxy;
import java.net.*;
import java.io.*;
import java.util.*;
import java.awt.*;
import proxy.HttpReplyHdr;
import proxy.HttpRequestHdr;
import proxy.Configuration;
import proxy.ServerDataBase;
import proxy.Cache;
import proxy.ServersAccessibleWOProxy;
import proxy.DocumentInfo;
import proxy.ServerInfo;
import proxy.MainFrame;
27 | P a g e
public class Proxy extends Thread {
Configuration p_config,
ServerDataBase p_serverDataBase,
Cache p_cache,
ServersAccessibleWOProxy p_serversAccessibleWOProxy,
MainFrame p_mainFrame)
client = socket;
config = p_config;
serverDataBase = p_serverDataBase;
cache = p_cache;
serversAccessibleWOProxy = p_serversAccessibleWOProxy;
mainFrame = p_mainFrame;
URL url;
DocumentInfo documentInfo;
try {
System.out.println("in proxy");
request.parse(client.getInputStream());
clientName = client.getInetAddress().getHostName();
synchronized(serversAccessibleWOProxy) {
if(!serversAccessibleWOProxy.containsKey(url.getHost()))
29 | P a g e
serverFilesMayBeCached = true;
synchronized(cache) {
if(serverFilesMayBeCached &&
!request.pragmaNoCache &&
request.ifModifiedSince.equals("") &&
cache.containsKey(url)) {
documentInCache = true;
documentInfo = (DocumentInfo)cache.get(url);
if(documentInCache) {
synchronized (documentInfo) {
documentInfo.getFileName());
if (cachedFile.exists()) {
from cache.");
synchronized (hits) {
mainFrame.updatePieChart(hits.intValue(),
misses.intValue());
30 | P a g e
}
documentInfo.incrementReferences();
FileInputStream in = new
FileInputStream(cachedFile);
int count;
out.write(data,0,count);
Thread.yield();
return;
}
}
if(serverFilesMayBeCached &&
!request.pragmaNoCache &&
request.ifModifiedSince.equals(""))
31 | P a g e
synchronized(misses) {
mainFrame.updatePieChart(hits.intValue(), misses.intValue());
Date timerStart;
Date timerEnd;
if (config.alternativeProxyOn()) {
serverName = config.getAlternativeProxyName();
else {
serverName = serverName(request.url);
serverName);
DataOutputStream srvOut =
32 | P a g e
new DataOutputStream(server.getOutputStream());
if (!config.alternativeProxyOn())
request.url = serverUrl(request.url);
srvOut.writeBytes(request.toString(false));
srvOut.flush();
/*
*/
server.getOutputStream().write(client.getInputStream().read());
server.getOutputStream().flush();
/*
*/
DataInputStream Din =
new DataInputStream(server.getInputStream());
DataOutputStream Dout =
new DataOutputStream(client.getOutputStream());
33 | P a g e
StringTokenizer st = new StringTokenizer(statusLine);
if (!returnCode.equals("200") || !serverFilesMayBeCached) {
"+clientName);
Dout.writeBytes(statusLine + "\r\n");
if (statusLine.length() > 0) {
while (true) {
Dout.writeBytes(str+"\r\n");
Dout.flush();
InputStream in = server.getInputStream();
int count;
out.write(data,0,count);
34 | P a g e
}
if (serverFilesMayBeCached) {
// is saved.
synchronized (serverDataBase) {
if (serverDataBase.containsKey(url.getHost()))
((ServerInfo)serverDataBase.get(url.getHost())).
updateAverageConnectionTime(connectionTime,
config.getServerInfoSmoothingFactor());
return;
long fileSize = 0;
35 | P a g e
file = new File(config.getCacheDirectory(), fileName);
statusLine += "\r\n";
fileSize += statusLine.length();
Dout.writeBytes(statusLine);
statusLine.getBytes(0,statusLine.length(),bytes,0);
fileToCache.write(bytes);
if (statusLine.length() > 2) {
while (true) {
fileSize += str.length();
Dout.writeBytes(str);
str.getBytes(0,str.length(),bytes,0);
fileToCache.write(bytes);
36 | P a g e
Dout.flush();
InputStream in = server.getInputStream();
int count;
fileSize += count;
out.write(data,0,count);
fileToCache.write(data,0,count);
/(timerEnd.getTime() - timerStart.getTime());
37 | P a g e
synchronized (serverDataBase) {
ServerInfo serverInfo;
if (!serverDataBase.containsKey(url.getHost())) {
connectionTime,bandWidth);
serverDataBase.put(url.getHost(), serverInfo);
else {
serverInfo = (ServerInfo)serverDataBase.get(url.getHost());
serverInfo.updateAverageBandWidth(bandWidth,
config.getServerInfoSmoothingFactor());
serverInfo.updateAverageConnectionTime(connectionTime,
config.getServerInfoSmoothingFactor());
serverInfo.incrementReferences();
mainFrame.updateLog("Caching "+request.url);
synchronized (cache) {
if (cache.containsKey(url)) {
documentInfo = (DocumentInfo)cache.get(url);
synchronized (documentInfo) {
cache.incrementCurrentWaterMark(
38 | P a g e
fileSize - documentInfo.getSize());
File(config.getCacheDirectory(),
documentInfo.getFileName());
documentInfo.setFileName(fileName);
documentInfo.setSize(fileSize);
documentInfo.incrementReferences();
cache.put(url, documentInfo);
else {
cache.incrementCurrentWaterMark(fileSize);
mainFrame.updateCacheBar(config.getCacheHighWaterMark(),
config.getCacheLowWaterMark(),
cache.getCurrentWaterMark());
return;
39 | P a g e
catch (UnknownHostException uhe)
try {
DataOutputStream out =
new DataOutputStream(client.getOutputStream());
out.writeBytes(reply.formNotFound());
out.flush();
} catch (Exception e) {
mainFrame.updateLog("Proxy error"+e.toString());
try {
DataOutputStream out =
new DataOutputStream(client.getOutputStream());
out.writeBytes(reply.formInternalError());
out.flush();
} finally {
40 | P a g e
try {server.close();} catch (Exception e){}
// chop to "server.name:x/thing"
int i = str.indexOf("//");
str = str.substring(i+2);
// chop to server.name:xx
i = str.indexOf("/");
// chop to server.name
i = str.indexOf(":");
return str;
// chop to "server.name:x/thing"
int i = str.indexOf("//");
41 | P a g e
if (i< 0) return 80;
str = str.substring(i+2);
// chop to server.name:xx
i = str.indexOf("/");
// chop XX
i = str.indexOf(":");
if (0 < i) {
return Integer.parseInt(str.substring(i).trim());
return 80;
int i = str.indexOf("//");
str = str.substring(i+2);
i = str.indexOf("/");
return str.substring(i);
42 | P a g e
Module 3: Mainframe.java
import java.net.*;
import java.awt.*;
import proxy.Configuration;
import PieChart;
import CacheDlg;
import ServerDataBaseDlg;
import AlternativeProxyDlg;
import proxy.ServersAccessibleWOProxy;
import AboutDlg;
import proxy.Cache;
super(title);
config = p_config;
resize(800,500);
mainMenu.CreateMenu();
setLayout(gridBag);
constraints.gridwidth = 1;
constraints.gridheight = 2;
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 1;
constraints.weighty = 1;
gridBag.setConstraints(logArea,constraints);
44 | P a g e
add(logArea);
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.gridheight = 1;
constraints.weightx = 0;
pieChart.setBackground(Color.gray.brighter());
gridBag.setConstraints(pieChart,constraints);
add(pieChart);
config.getCacheLowWaterMark(),
config.getCacheCurrentWaterMark());
cacheBar.setBackground(Color.gray.brighter());
gridBag.setConstraints(cacheBar,constraints);
add(cacheBar);
shuttingDown = false;
repaint();
pack();
show();
45 | P a g e
public void updatePieChart(int hits, int misses)
pieChart.updatePieChart(hits, misses);
logArea.appendText(str+"\n");
if(shuttingDown)
return (true);
switch (event.id) {
case Event.WINDOW_DESTROY:
shuttingDown = true;
break;
case Event.ACTION_EVENT:
46 | P a g e
if(((String)event.arg).equals("Exit")) {
shuttingDown = true;
else if(((String)event.arg).equals("Cache")) {
if (cache == null)
return super.handleEvent(event);
Parameters",config, cache);
Parameters",config);
AlternativeProxyDlg ap = new
AlternativeProxyDlg(this,
"Alternative Proxy
Parameters",config);
if (serversAWOP == null)
return super.handleEvent(event);
ServersAccessibleWOProxyDlg sawp =
new ServersAccessibleWOProxyDlg(this,
else if(((String)event.arg).equals("About")) {
break;
default:
return super.handleEvent(event);
return true;
serverSocket = p_serverSocket;
serversAWOP = sawop;
cache = p_cache;
48 | P a g e
}
Module 4: Cache.java
package proxy;
import java.net.*;
import java.io.*;
import java.util.*;
import java.awt.*;
import proxy.DocumentInfo;
import proxy.ServerDataBase;
import proxy.Configuration;
import proxy.DocumentMark;
import MainFrame;
MainFrame p_mainFrame)
super();
config = p_config;
serverDataBase = p_serverDataBase;
mainFrame = p_mainFrame;
currentWaterMark = config.getCacheCurrentWaterMark();
DocumentInfo documentInfo;
File fileInHand;
try {
config.getCacheBackupFile(),"r");
String s = in.readLine().substring(1);
in.close();
String key;
String documentInfoStr;
int maxEnumerator = 0;
50 | P a g e
try {
if (config.proxyBroughtDownProperly())
while(st.hasMoreElements()) {
key = st.nextToken("=");
key = key.substring(1);
documentInfoStr = st.nextToken(",}");
documentInfoStr = documentInfoStr.substring(1);
//chop "="
DocumentInfo(documentInfoStr));
else {
currentWaterMark = 0;
while(st.hasMoreElements()) {
key = st.nextToken("=");
key = key.substring(1);
documentInfoStr = st.nextToken(",}");
51 | P a g e
documentInfoStr = documentInfoStr.substring(1);
//chop "="
documentInfo = new
DocumentInfo(documentInfoStr);
fileInHand = new
File(config.getCacheDirectory(),
documentInfo.getFileName());
if(fileInHand.exists()) {
filesIndexedInCache.put(fileInHand,
dummy);
try {
((ServerInfo)(serverDataBase
.get(documentInfo.getUrl().
getHost())))
.incrementReferences();
serverDataBase.clear();
throw new
52 | P a g e
incrementCurrentWaterMark(documentInfo.getSize());
if(maxEnumerator <
(new
Integer(fileInHand.getName())).intValue())
maxEnumerator =
(new
Integer(fileInHand.getName())).intValue();
}
}
config.setFileNameEnumerator(maxEnumerator);
config.setCacheCurrentWaterMark(currentWaterMark);
fileInHand = new
File(config.getCacheDirectory(),files[i]);
if(!
filesIndexedInCache.containsKey(fileInHand))
fileInHand.delete();
serverDataBase.clearZeroReferencedItems();
clear();
try {
53 | P a g e
File f = new File(config.getCacheBackupFile());
f.delete();
} finally {
mainFrame.updateCacheBar(config.getCacheHighWaterMark(),
config.getCacheLowWaterMark(),
currentWaterMark);
54 | P a g e
makeRoom();
return obj;
return currentWaterMark;
}
currentWaterMark += size;
currentWaterMark -= size;
if (file.exists()) file.delete();
try {
55 | P a g e
RandomAccessFile out = new RandomAccessFile(file,"rw");
out.writeBytes(toString()+'\n');
out.close();
} catch (IOException e) {
return false;
config.setCacheCurrentWaterMark(currentWaterMark);
return true;
URL keyInHand;
double mark;
double wCT,wBW,wRF,wS;
DocumentInfo documentInfoInHand;
ServerInfo serverInfoInHand;
synchronized (config) {
wCT = config.getWeightConnectionTime();
wBW = config.getWeightBandWidth();
wRF = config.getWeightReferencesFrequency();
56 | P a g e
wS = config.getWeightSize();
Enumeration e = keys();
keyInHand = (URL)e.nextElement();
documentInfoInHand = (DocumentInfo)get(keyInHand);
serverInfoInHand = (ServerInfo)serverDataBase.get(
keyInHand.getHost());
sort(array, 0, array.length-1);
File fileInHand;
long lowWaterMark;
long highWaterMark;
String cacheDirectory;
synchronized (config) {
lowWaterMark = config.getCacheLowWaterMark();
highWaterMark = config.getCacheHighWaterMark();
cacheDirectory = config.getCacheDirectory();
57 | P a g e
for(int i = 0; currentWaterMark >= lowWaterMark; i++) {
documentInfoInHand = (DocumentInfo)array[i].getDocumentInfo();
synchronized (documentInfoInHand) {
documentInfoInHand.getFileName());
fileInHand.delete();
decrementCurrentWaterMark(documentInfoInHand.getSize());
remove(documentInfoInHand.getUrl());
synchronized (serverDataBase) {
serverInfoInHand = (ServerInfo)serverDataBase.get(
documentInfoInHand.getUrl().getHost());
if(serverInfoInHand.decrementReferences() == 0)
serverDataBase.remove(documentInfoInHand
.getUrl().getHost());
mainFrame.updateCacheBar(highWaterMark,lowWaterMark,currentWaterMark);
58 | P a g e
double wCT, double wBW, double wRF, double
wS)
wBW / serverInfo.getAverageBandWidth()) *
Math.pow(documentInfo.getReferencesPerHour(),wRF) /
Math.pow(documentInfo.getSize(),wS));
return;
59 | P a g e
DocumentMark temp;
left++;
right--;
temp = array[left];
array[left] = array[right];
array[right] = temp;
left++;
right--;
temp = array[right];
array[right] = array[p_left];
array[p_left] = temp;
return right;
Module 5 : HttpRequestHdr.java
package proxy;
60 | P a g e
import java.io.InputStream;
import java.io.DataInputStream;
import java.util.StringTokenizer;
{
61 | P a g e
String CR ="\r\n";
DataInputStream lines;
StringTokenizer tz;
try {
tz = new StringTokenizer(lines.readLine());
} catch (Exception e) {
return false;
method = getToken(tz).toUpperCase();
url = getToken(tz);
version= getToken(tz);
while (true) {
try {
tz = new StringTokenizer(lines.readLine());
} catch (Exception e) {
return false;
if (0 == Token.length())
break;
if (Token.equalsIgnoreCase("USER-AGENT:")) {
userAgent = getRemainder(tz);
62 | P a g e
} else if (Token.equalsIgnoreCase("ACCEPT:")) {
} else if (Token.equalsIgnoreCase("REFERER:")) {
referer = getRemainder(tz);
} else if (Token.equalsIgnoreCase("PRAGMA:")) {
// Pragma: <no-cache>
Token = getToken(tz);
if (Token.equalsIgnoreCase("NO-CACHE"))
pragmaNoCache = true;
else
+getRemainder(tz) +"\n";
} else if (Token.equalsIgnoreCase("AUTHORIZATION:")) {
authorization= getRemainder(tz);
} else if (Token.equalsIgnoreCase("IF-MODIFIED-SINCE:")) {
if (index == -1) {
ifModifiedSince =str;
} else {
63 | P a g e
ifModifiedSince =str.substring(0,index);
index = str.indexOf("=");
if (index != -1) {
str = str.substring(index+1);
oldContentLength =Integer.parseInt(str);
} else if (Token.equalsIgnoreCase("CONTENT-LENGTH:")) {
Token = getToken(tz);
contentLength =Integer.parseInt(Token);
} else if (Token.equalsIgnoreCase("CONTENT-TYPE:")) {
contentType = getRemainder(tz);
} else {
return true;
String Request;
if (0 == method.length())
method = "GET";
64 | P a g e
Request = method +" "+ url + " HTTP/1.0" + CR;
if (0 < userAgent.length())
if (0 < referer.length())
if (pragmaNoCache)
if (0 < ifModifiedSince.length())
// ACCEPT TYPES //
if (0 < accept.length())
else
if (0 < contentType.length())
if (0 < contentLength)
65 | P a g e
if (0 != authorization.length())
if (sendUnknowen) {
if (0 != unrecognized.length())
Request += unrecognized;
Request += CR;
return Request; }
return toString(true);
if (tk.hasMoreTokens())
str =tk.nextToken();
return str;
if (tk.hasMoreTokens())
str =tk.nextToken();
while (tk.hasMoreTokens()){
}
66 | P a g e
return str;
b) Gantt Chart:
67 | P a g e
6. BIBLIOGRAPHY:
• Wrox Java Networking.
• Object-Oriented Modeling and Design-James Rambaugh
• Beej's Guide to Socket Programming.
• Wikipedia
68 | P a g e