Saturday, May 30, 2009

Exercise 24. Virtual business worlds and software agents


1. Differentiate the various types of software agents.

A Software agent is a single software that works for a user or other program in a relationship of agency. The term 'agent' describes a software abstraction, an idea or a concept that similar to the methods, functions and objects in object oriented programming. The agent provides a easy and powerful way to describe a complex software entity that capable of working with a certain degree of autonomy in order to achieve tasks on behalf of its user. Various type of software agents

- Intelligent software agents are a branch of artificial intelligence research. The intelligent agents include ability to adapt and learn. Ability to adapt means sensing the environment and reconfiguring in response by choice of alternative problem solving rules or algorithms.
- Autonomous agents are software agents that claim to be autonomous. It is self contained and capable of making independent decisions, and taking actions to satisfy self goals that upon their sense environment.
- Distributed agents are designed to be very loosely coupled and easy to execute as independent threads on distributed processors.
- Multi-agent systems are several agents work together or collaborate with other agents. Data is decentralized and execution is asynchronous in mult-agent systems.
- Mobile agents are agent that moves itself include its execution state from one to another machine to continue execution there. Mobile agents can be used to gather system information, taking files backup, monitoring network throughput or checking of available resources and moderating the resource utilization.
- Fuzzy agents are software agent that implements fuzzy logic. They interact with their environment through an adaptive rule-base and can be considered as a kind of intelligent agent.



2. Describe how techniques such as artificial intelligence and statistical techniques are used in software agents.

The artificial intelligence technique is used in intelligent software agents and Fuzzy agents for capable in ability to adapt and learn. The ability to adapt means sensing the environment and reconfiguring in response, through the select of alternative problem-solving-rules or algorithms, or through the discovery of problem solving strategies. The ability to learn means learning through trial-and-error, then capable to introspection and analysis of behavior and success, capable to abstract and generalize.

The statistical technique is used in mobile agents in gather system information, monitoring network throughput, check resources avaliablity and moderating the resource utilization. The statistical technique is used intensively in data mining agents for information collection and analysis.


3. Identify various activities in e-commerce where software agents are currently in use.

Buyer agents are widely used in e-commerce such as Amazon.com and eBay. Their Website offer a list of products for users to buy. They also use the collaborative filtering technology to show similar products that customers who did the search looked at.

Data mining agents are also used e-commerce for collecting data to promote e-commerce activities. Data collect include the users' browsing history, keywords used in search engines and hit rate of Web page etc.



4. List popular software agents currently in use in the commercial world?


1. Buyer agents also called 'shopping bots', they search around the network to retrieve information about goods and services. The Website offer a list of products that you may like to buy such as Amazon.com or eBay.
2. User agents or personal agents are intelligent agents that take action on your behalf. They perform the tasks for you: check e-email, play computer games, assemble customized news reports, find information, fill out forms on the Web automatically, scan Web page and discuss topics with you.
3. Monitoring-and-surveillance(predictive) agents are used to observe and report on equipment, usually computer systems. They may keep track the inventory levels, price of competitors and relay them back to the company.
4. Data mining agents uses information technology to find trends and patterns in a abundance of information from many sources that come from different systems. Users can seek and sort the information in any way they want.


1. Hagg, S. (2006), Management information systems for the information age, 224-228.
2. Wikipedia (2009), Software agent, Retrieved at http://en.wikipedia.org/wiki/Software_agent on 3rd May, 2009.

Exercise 23: Search mechanisms


1. What is a spider? what does it do?


An Internet spider is a program used by searched engines which is designed to "crawl" over the World Wide Web, the portion of the Internet most familiar to general users, and retrieve locations of Web pages. The usual starting points are lists of heavily used servers and very popular pages. The spider will begin with a popular site, indexing the words on its pages and following every link found within the site. In this way, the spidering system quickly begins to travel, spreading out across the most widely used portions of the Web. It is sometimes referred to as a webcrawler. Many search engines use webcrawlers to obtain links, which are filed away in an index. When a user asks for information on a particular subject, the search engine pulls up pages retrieved by the Internet spider. Without spiders, the vast richness of the Web would be all but inaccessible to most users, rather as the Library of Congress would be if the books were not organized.

Some search engines are human-based, meaning that they rely on humans to submit links and other information, which the search engine categorizes, catalogues, and indexes. Most search engines today use a combination of human and crawler input. Crawler-based engines send out spiders, which are actually computer programs that have sometimes been likened to viruses because of their ability to move between, and insert themselves into, other areas in cyberspace.

Spiders visit Web sites, record the information there, read the meta tags that identify a site according to subjects, and follow the site's links to other pages. Because of the many links between pages, a spider can start at almost any point on the Web and keep moving. Eventually it returns the data gathered on its journey to the search engine's central depository of information, where it is organized and stored. Periodically the crawler will revisit the sites to check for changed information, but until it does so, the material in the search engine's index remains the same. It is for this reason that a search at any time may yield "dead" Web pages, or ones that can no longer be found.

No two search engines are exactly the same, the reason being (among other things) a difference in the choice of algorithm by which the indices are searched. Algorithms can be adjusted to scan for the frequency of certain keywords, and even to circumvent attempts at keyword stuffing or "spamdexing," the insertion of irrelevant search terms intended simply to draw traffic to a site.


http://www.answers.com/topic/internet-spider

http://computer.howstuffworks.com/search-engine1.htm


2. What is a meta-search engine? Provide some examples.


Meta search engines are search engine tools that pass queries on to many other search engines and/or directories and then summarize all the results in one handy interface. They appear like an aggregator for receiving your input (search requests) and then forward the request(s) to several other search engines and/or databases and aggregates the results into a single list or displays them according to their source. Metasearch engines enable users to enter search criteria once and access several search engines simultaneously. Metasearch engines operate on the premise that the Web is too large for any one search engine to index it all and that more comprehensive search results can be obtained by combining the results from several search engines. This also may save the user from having to use multiple search engines separately.

Examples of Meta-search engines:
Clusty: www.clusty.com
Dogpille: www.dogpile.com
SurWax: www.surfwax.com
Copernic Agent: www.copernic.com


3. How can you get your site listed at major search sites; and how could you improve your site ranking?

Here are some of the ways you could improve your website ranking.

- Subscribe your Web site to major search sites for them easily to reach your Web site.
- Declare the key terms that your users will search on to find content like yours carefully. Use those key terms to guide the text and construct your web pages.
- As users are likely to click the link if the title matches their search, choose terms for the title that match the concept of your document.
- Use meta-tags as a description and write the description accurately and carefully. Make sure the document title and description attract the interest of the user.
- Use 'keyword' in meta-tag to list key words for the document.
- Keep relevant text and links in HTML. An HTML site map, with a link from the welcome page, can help to make sure all your pages are crawled by the search engines.
- Use ALT text for graphics for good page design to accommodate text browsers or visually impaired visitors.

Exerscise 22: CRM


Differentiate between software systems such as Customer Relationship Management (CRM) software, Business-to-Business e-commerce programs and Supply-Chain Management (SCM) software.


CRM (customer relationship management) is a collective term for methodologies, software, and usually Internet capabilities that help and enterprises manage customer relationships in an organized way. For example, an enterprise might build a database about its customers that described relationships in sufficient detail so that management, salespeople, people providing service, and perhaps the customer directly could access information, match customer needs with product plans and offerings, remind customers of service requirements, know what other products a customer had purchased, and so forth.

Business-to-Business (B2B) software is used to transfer data between businesses such as purchase orders and invoices. This decreases cost of employees to manually enter data, time for goods to ship as orders can be processed almost immediately if stock is available, and time to receive payment, as many businesses using B2B have payments automatically flagged to pay on their due date.

Supply chain Management: Supply chain management (SCM) is the oversight of materials, information, and finances as they move in a process from supplier to manufacturer to wholesaler to retailer to consumer. Supply chain management involves coordinating and integrating these flows both within and among companies. Supply chain management flows can be divided into three main flows:
- The product flow
- The information flow
- The finances flow
The product flow includes the movement of goods from a supplier to a customer, as well as any customer returns or service needs. The information flow involves transmitting order and updating the status of delivery. The financial flow consists of credit terms, payment schedules, and consignment and title ownership arrangements.

Exercise 21: Shopping Cart Specifications


Develop the class diagram for the following shopping cart specifications:

A shoppingCart object is associated with only one creditCard and customer and to items in itemToBuy object. Persistent customer information such as name, billing address, delivery address, e-mail address and credit rating is stored in the customer object. The credit card object is associated with a frequentShopper discount object, if the credit rating for the customer is good. The customer can make or cancel orders as well as add and delete items to the shopping cart product. The credit card object contains the secure method for checking that the charge is authentic.

Exercise 20: Modelling with UML

Describe each of the eight main diagrams used in UML.
At the centre of the UML are its nine kinds of modelling diagrams, which we describe here.
- Use case diagrams
- Class diagrams
- Object diagrams
- Sequence diagrams
- Collaboration diagrams
- Statechart diagrams
- Activity diagrams
- Component diagrams
- Deployment diagrams


Use case diagrams describe what a system does from the standpoint of an external observer(High Level View). The emphasis is on what a system does rather than how.

Class diagram gives an overview of a system by showing its classes and the relationships among them. Class diagrams are static -- they display what interacts but not what happens when they do interact.

Object diagrams show instances instead of classes. They are useful for explaining small pieces with complicated relationships, especially recursive relationships.
Sequence diagram is an interaction diagram that details how operations are carried out -- what messages are sent and when. Sequence diagrams are organized according to time. The time progresses as you go down the page

Collaboration diagrams are also interaction diagrams. They convey the same information as sequence diagrams, but they focus on object roles instead of the times that messages are sent. In a sequence diagram, object roles are the vertices and messages are the connecting links.

A state chart diagram shows the possible states of the object and the transitions that cause a change in state.

An activity diagram is basically a glorified flowchart. Activity diagrams and state chart diagrams are related where a state chart diagram focuses the attention on an object undergoing a process (or on a process as an object), the activity diagram focuses on the flow of activities involved in a single process. The activity diagram shows the how those activities depend on one another.

A component is a code module. Component diagrams are physical analogs of class diagram.

Deployment diagrams show the physical configurations of software and hardware.

Exercise 19: TP Monitors and Transaction Protocols


1. Give a description in your own words of the ACID properties of a transaction.


ACID properties of a transaction refers to
Atomicity: When an update occurs to a database, either all or none of the update becomes available to anyone beyond the user or application performing the update.
Consistency: Consistency is the ACID property that ensures that any changes to values in an instance are consistent with changes to other values in the same instance
Isolation: The isolation portion of the ACID properties is needed when there are concurrent transactions. An important concept to understanding isolation through transactions is serializability. Transactions are serializable when the effect on the database is the same whether the transactions are executed in serial order or in an interleaved fashion.
Durability: Durability refers to the ability of the system to recover committed transaction updates if either the system or the storage media fails.


2. Describe a TP monitor environment. How can a TP monitor stop an operating system being overwhelmed?


A TP Monitor is a subsystem that groups together sets of related database updates and submits them together to a relational database. The result is that the database server does not need to do all of the work of managing the consistency/correctness of the database; the TP Monitor makes sure that groups of updates take place together or not at all. TP-Monitor environment which partitions the workflow engine into several resource managers (RMs) individually managed by a TP-Monitor environment. The RMs together form the workflow engine serving user requests. (Browne's, 2007)


3. What is the difference in load balancing with traditional and transactional MOM, RPC, and conversations?


Load balancing is dividing the amount of work that a computer has to do between two or more computers so that more work gets done in the same amount of time and, in general, all users get served faster.
Traditional RPC Model: In this the request from user should be queued and wait synchronously for the server to execute and return the reply where the client and server should be free at the same time.
MOM: MOM stands for Message-oriented middleware It acts as a middleware between the client and server, buffering the requests from user and replies from servers.
RPC(remote Procedure Call): Remote procedure call (RPC) is an Inter-process communication technology that allows a computer program to cause a subroutine or procedure to execute in another address space(commonly on another computer on a shared network) without the programmer explicitly coding the details for this remote interaction.


4.Why is a two-phase commit protocol better than a one-phase atomic commit protocol?


One –phase Atomic Commit Protocol
This protocol overlaps the voting phase with the execution of transaction and just has a decision
phase. There are two implementation the Implicit Yes Voting and the Coordinate Log.
Advantages:
Simple protocol fewer overheads.
• Low latency due to fewer disk writes.
• Useful in case of low bandwidth networks, as lesser messages are exchanged.
• In most cases all the updates will be logged befor commit so durability is assured.
Disadvantages
• The greatest disadvantage is that it can only handle immediate consistency con-
straints as there is no voting phase. It can not handle the deferred consistency
constraints

Two-Phase Atomic commit protocol: This is the most widely used protocol which commences in two phases ,Voting , to ensure that all sites are ready to commit,Decision , to ensure uniformity at abort or commit at all sites.
2PC is largely used in all distributed systems.
Advantages
• It ensures atomicity even in the presence of deferred constraints.
• It ensures independent recovery of all sites.
• Since it takes place in twophases, it can handle network failures, disconnections and
in their presence assure atomicity.
Disadvantages
• Involves a great deal of message complexity.
• Greater communication overheads as compared to simple optimistic protocols.
• Blocking of site nodes in case of failure of coordinator.
• Multiple forced writes of log, which increase latency.
• Its performance is again a trade off,especially for short lived transactions, like Internet
applications

Exercise 18: Threading demonstration in Python.


A simple demonstration of the threading module in Python that uses both a lock and semaphore to control concurrency is by Ted Herman at the University of Iowa. The code and sample output below are worth a look. Report your findings.



There are a number of elements to the threaddemo.py program. It incorporates threaded programming, including locks, semaphores and monitoring.

The following were my findings after reviewing a threaddemo.py program which

- Firstly the numtasks variable is set to 10, which gives a total of ten tasks to be run.
- The second variable of sema is set to 3, which allows three threads to run simultaneously.
- The third variable set is mutex, which creates a read lock on the thread.
- The final variable set is running, which keeps track of how many threads are running.

As the code runs, the tasks are completed, with a maximum of three running at the one time (as set in the sema variable). The running variable monitors this number of threads. When each thread completes running, the mutex variable allows the read lock to be released and for the next thread to be run. These continue to run until the total number of tasks listed in numtasks (ten in this case) have been processed, with a maximum of three running at the one time.

Exercise 17: Concurrency terms


Find definitions for eight terms and concepts used in threaded programming:


Listed below are the 8 terms and concepts used in threaded programming

- Thread Synchronisation
- Locks
- Deadlock
- Semaphores
- Mutex (mutual exclusion)
- Thread
- Event
- Waitable timer.


1. Thread Synchronisation requires that a running thread gain a "lock" on an object before it can access it. The thread will wait in line for another thread that is using the method/data member to be done with it. This is very important to prevent the corruption of program data if multiple threads will be accessing the same data. If two threads try to change a variable or execute the same method at the same, this can cause serious and difficult to find problems. Thread synchronization helps prevent this.
2. Locks is a technique that prevents processing of a file by more than one program or user at a time, ensuring that a file in use by one user is made unavailable to others.
3. A deadlock is a situation wherein two or more competing actions are waiting for the other to finish, and thus neither ever does.
4. Semaphores is hardware or software flag used to indicate the status of some activity.
5. Mutex (mutal exclusion) is programming flag used to grab and release an object. When data are acquired that cannot be shared or processing is started that cannot be performed simultaneously elsewhere in the system, the mutex is set to "lock," which blocks other attempts to use it. The mutex is set to "unlock" when the data are no longer needed or the routine is finished.
6. Thread in computer programming, a thread is placeholder information associated with a single use of a program that can handle multiple concurrent users. From the program's point-of-view, a thread is the information needed to serve one individual user or a particular service request. If multiple users are using the program or concurrent requests from other programs occur, a thread is created and maintained for each of them. The thread allows a program to know which user is being served as the program alternately gets re-entered on behalf of different users. (One way thread information is kept by storing it in a special data area and putting the address of that data area in a register. The operating system always saves the contents of the register when the program is interrupted and restores it when it gives the program control again.)
7. The language was organized around a series of events. Each time an event happened (for example, mouse click, pulling down a menu), the program would respond.
8. Waitable timer is a kernel object that is signaled at a certain time or at regular intervals. An asynchronous procedure call (APC) can be associated with a waitable timer to allow a callback function to be executed whenever the timer is signaled. The sample code in this article demonstrates how to do this.


References
1. Wikianswer, 2009 " Thread Synchronisation"

2. Wikianswer, 2009, " File-Locking"

3. Wikianswer, 2009, " Deadlock"

4. Wikianswer, 2009, "Semaphores"

5. Wikianswer, 2009, " Mutex"

6. Wikianswer, 2009, " Definition of Thread"

7. Wikianswer, 2009." Event"

8. Microsoft, 2006," How To Use a Waitable Timer with an Asynchronous Procedure Call"

Exercise 16: Authentication and Encryption systems


1. Visit an e-commerce website and survey the mode of payment allowed.Would you trust the site with your business?


I visited the eBay site of http://www.ebay.co.uk/.

The Mode of payments offered were
- PayPal
- Credit Card
- Personal or Bank cheques
- Money Orders
- Bank Deposit or Bank Deposit Express
- Cash on Delivery.

This is a site I would trust and use for making online purchases because I am a consumer that has bought many items through this site using Paypal and Credit Cards and have not faced any issues at all. All the payments I have made have been secure and trusted.


2. What measures should e-commerce provide to create trust among their potential customers? What measures can be verified by the customer?


Trust is key in any relationship or operation. Nothing can function or coexist without it and it stems from the home to business.In the world of e-commerce, earning and providing trust to its all stakeholders especially to its customers is the first step to good business. It takes a life time to forge and can be lost as easy a mouse click.

The following measures can help the customer verify the trustworthiness of a website or business
- Digital certificates from a trusted source.
- Website reviews from trusted sources
- Providing encryption
- Customer reviews from frequent users
- Undisputed and Uninterrupted customer care.
- Provision of contact information or other details that can be used to verify that the seller is authentic.
- Industry membership.


3. Visit the Verisign web site-what solutions does it offer for e-commerce?

What is Verisign?

VeriSign is the leading Secure Sockets Layer (SSL) Certificate Authority enabling secure e-commerce, communications, and interactions for Web sites, intranets, and extranets.

Versign provides SSL certification for authentication. The certification is used to certify the identity of the individuals and website. By using the PKI infrastructure, it is possible to authenticate the website and individual through the certificate and the three way hand-share mechanism.


4. Visit the TRUST web site. Describe what services and solutions are offered.


The TRUSTe web site provides online privacy services for the Businesses such as Enterprises, Small business and for Consumers. They have helped thousands of website and millions of users for protecting their privacy.

Web Privacy Seal Marks companies that adhere to TRUSTe’s strict privacy principles and comply with the TRUSTe Watchdog Dispute Resolution System.

EUSafe Harbor Seal Certifies compliance with the EU Directive on Data Protection, specifically the Safe Harbor Framework, to avoid trade disruptions resulting from international privacy laws.

Email Privacy Seal Reinforces companies’ commitments to good email practices by certifying email disclosures, reputation, and unsubscribe policies.

Trusted Download Program Provides market incentives for ad-ware and other software companies to clearly and unavoidably communicate key functions and obtain informed consumer consent prior to download.

Site Reputation Services Reduces the risk of attack by using technology to scan user-generated or third-party content for potential malicious content before it’s uploaded to a Web site"



5. Get the latest PGP software from http://web.mit.edu/network/pgp.html;install it on two machines and encrypt a message on one machine and decrypt it on the other. Report your findings.


This software is out of date and no longer available.

6. The use of digital certificates and passports are just two examples of many tools for validating legitimate users and avoiding consequences such as identity theft. What others exist?


Some of the validation tools that can be used include:

Wildcard SSL certificate

Authentication logon with a secure USB authentication token

Basic authentication where a username and password is provided for each realm

Digest authentication which is based on challenge – response. This involves the user making a request without any credentials. The server then responds with a WWW-Authenticate header requesting credentials. Instead of sending the clear text credentials, the user sends the Message Digest (MD5) version of their credentials.

NTLM is Microsoft’s own NT LAN Manager authentication algorithm over HTTP. It is similar to MD5 in the way that it works.

Certificate authentication is stronger than other methods. it involves the use of public and private keys to encrypt and decrypt data.

Microsoft passport and other passport methods involve the use of a single set of credentials to sign in to any of the sites that use these passports.

Forms based authentication uses cookies to allow validated users to access parts of a website.

Exercise 15: Protecting and archiving data


1. What makes a firewall a good security investment? Accessing the Internet, find two or three firewall vendors. Do they provide hardware, software or both?


Firewalls are systems (Hardware or Software or a combination of both) that are designed to prevent unauthorized access to or from a private network. Firewalls are frequently used to prevent unauthorized Internet users from accessing private networks connected to the Internet, especially intranets. All messages entering or leaving the intranet pass through the firewall, which examines each message and blocks those that do not meet the specified security criteria.

As every IT-Infrastructure model stems on security, Firewalls are a good security investment for the following reasons.

- To prevent access to certain services built into Windows which are notoriously difficult or even impossible to disable.
- To prevent certain Denial Of Service attacks, most notably disconnects due to spoofed unreach aka "click" - this is perhaps its most important (and some would say only unique) contribution to your security.
- To block inadvertent holes in your computer's security if you unintentionally leave open services such as file or print sharing or an FTP daemon. Instead of relying on a firewall, however, you should check your security (try the Shields UP! site) and just fix these vulnerabilities.
- To make it impractical for others to port scan you to identify your vulnerabilities. It does so by making scanning more time consuming, by preventing the usual RST response on closed ports so that the scanner has to wait for the connection attempt to time out. It can also defeat automated scanning for active hosts by disabling ICMP ECHO replies (aka "pings").

Vendors of Firewalls are:
- Juniper Networks - http://www.juniper.net, provides both hardware and software integrating firewall called NetScreen.
- Check Point - http://www.checkpoint.com, provides integrated appliance solutions (Security Gateways) for both hardware and software
- SonicWALL - http://www.sonicwall.com, provides both hardware and software firewall products


2. Find out if your university or workplace has a backup policy in place. Is it followed and enforced?

The following is an overview of the policy enforced at my organization(workplace)
Back up Policy
• The frequency and extent of backups must be in accordance with the importance
of the information and the acceptable risk as determined by the data owner. Incremental and Differential Backup
• E-Solutions Information Resource backup and recovery process
for each system must be documented and periodically reviewed.
• Physical access controls implemented at offsite backup storage locations must
meet or exceed the physical access controls of the source systems. Additionally
backup media must be protected in accordance with the highest
sensitivity level of information stored.
• A process must be implemented to verify the success of the
electronic information backup.
• Backups must be periodically tested to ensure that they are recoverable.
• Signature cards held by the offsite backup storage vendor(s) for access to
backup media must be reviewed annually or when an
authorized individual leaves %ORGANIZATION%.
• Procedures between and the offsite backup storage
vendor(s) must be reviewed at least annually.
• Backup tapes must have at a minimum the following identifying criteria that can
be readily identified by labels and/or a bar-coding system:
o System name
o Creation Date
o Sensitivity Classification
o Contact Information
Version History
Version Number Date Reason/Comments
Vn.00.00 Month, Year


3. Most of the anti virus software perform an active scanning of the user activity on the Internet, detecting downloads and attachments in e-mails. Hackers have readily available resources to create new viruses. How easy is it to find a virus writing kit? Search the Internet and find such a tool. For example, see what you can find at http://vx.netlux.org/dat/vct.shtml.


On a search conducted using www.google.lk with the search term virus writing kit, the following are resources i found.

http://vx.netlux.org/lib/static/vdat/creatrs1.htm
http://www.ca.com/us/securityadvisor/pest/pest.aspx?id=818

http://vx.netlux.org/dat/vct.shtml
VX Heavens
Home Upload Library Collection Sources Engines Constructors Simulators Utilities Links AV Checkβ

Virus Creation Tools (195)
"INVICTUS" VX Library
$MOOTHiE::s Macro Virus Creator 2000
Access Macro Generator
Acid Flowing Trojan Generator
Advanced Batch Mutator
Advanced Steam Trojan Generator
Alchemic Life Generator
ANSI Bomb Constructor by Duke
The ANSI Bomb Generator
Ansi Bomb Kit
Ansi Bomb Maker
Apokalipses
BAT Poly Generator
BAT virii Generator MIX 1.0
Batch Encrypt
Batch Maker
Batch Trojan Generator
Batch Virus Construction Kit
Batch Worm Generator
Batch-O-Matic
Valid XHTML 1.0! S1

Exercise 14: Electronic payments and security II


1. What are cookies and how are they used to improve security?


Cookies are files that websites create(and store o your computer) that often contains information about your personalization preferences for websites, but can also be used to include usernames or email addresses information. Its important to recognize that the vast majority of cookies are not malicious but are often required to visit secure
site like those associated with online banking or e-commerce based sites

To address the security concern, only the web site that creates a cookie is able to read it. Web servers can use only information that you provide or choices that you make while visiting the web site as content in cookies. This way it is unique.


2. Can the use of cookies be a security risk?


The following are ways that a cookie could be the subject of security risk and threat

Cookie hijacking
Cookies may contain sensitive information (such as user name, credit card no., etc.), their values should not be accessible to other computers. Cookie theft is the act of intercepting cookies by an unauthorized party.

Cookies can be stolen via packet sniffing in an attack called session hijacking. Traffic on a network can be intercepted and read by computers on the network other than its sender and its receiver. This traffic includes cookies sent on ordinary unencrypted http sessions. Where network traffic is not encrypted, malicious users can therefore read the communications of other users on the network, including their cookies, using programs called packet sniffers.

A different way to steal cookies is cross-site scripting and making the browser sends cookies to servers that should not receive them. Modern browsers allow execution of pieces of code retrieved from the server. If cookies are accessible during execution, their value may be communicated in some form to servers that should not access them. This type of cross-site scripting is typically exploited by attackers on sites that allow users to post HTML content.

Cookie poisoning
While cookies are supposed to be stored and sent back to the server unchanged, an attacker may modify the value of cookies before sending them back to the server. For example, a cookie contains the total value a user has to pay for the items in their shopping basket, changing this value exposes the server to the risk of making the attacker pay less than the supposed price. The process of tampering with the value of cookies is called cookie poisoning, and is sometimes used after cookie theft to make an attack persistent.

Cookie expiry
Persistent cookies have been criticized by privacy experts for not being set to expire soon enough, and thereby allowing websites to track users and build up a profile of them over time. This aspect of cookies also compounds the issue of session hijacking, because a stolen persistent cookie can potentially be used to impersonate a user for a considerable period of time.

http://en.wikipedia.org/wiki/HTTP_cookie

Exercise 13: Electronic payments and security


1. List and describe your experience with a secure Web site.

As part of my life dwells on the internet, security is important to me. Given below is a summary of my activities online using secure means.

- Online banking (via www.hsbc.lk and http://www.standardchartered.com/lk/)
- Airline Reservations
- Online Book Purchases

Whenever I use the online banking service to do my transactions, I prefer HSBC. The following lists out a typical money transfer.

1. Log on the site with my user name, password and Security code(Generated by a security device provided by the bank that last no longer than 60 secs at which point the code is invalid)

2. Successful login redirects me via SSL to a secure page to process my banking transactions.

3. To transfer money to other bank accounts I am prompted for another security code generated by the device to be keyed in. (This keeps every transaction secure and unique)



2. What is SET and how does it compare to SSL as a platform for secure electronic transaction? Is SET in common use?


Secure Electronic Transaction (SET) is a system for ensuring the security of financial transactions on the Internet.

The safety of SET is equal to the security system which an electronic payment system each company is enforcing with SSL fundamentally.

It becomes decoding with the server of the card issue company of the human control where finally technically the individual information (this case, not card number but the registration number of SET) that it was enciphered with the public-key such as RSA by a member's personal computer is made.

But, it flows from the member to the issue company in the case of SET when information goes through the route (joining store, authentication organ, joining store control company) in some middle. Therefore you must prevent decoding in the middle route and a data theft more than each electronic payment system form.

It is not a mere code signature for its sake which decodes only necessary information with the joining store, the joining store control company, the authentication organ, and two-fold code signature is necessary. An item and the way of the treatment are complex, and there are many preservation plans of the data made securing a security system in that place and decoding �y that place �z, and it has been getting necessary as for contents of registration to WALLET as well.

SSL

It has the information which a client (payment system use member) inputted on WEB enciphered with the present condition RSA public-key, and ssl is decoded with the server (joining store or payment system company).
In this case, or it has the possibility that it has data stolen and decoded information is seen on the server from the outside.
Therefore, it is inside the firewall which decoded data did neatly, and it must be kept under the condition that data are managed.

Decoding is decided to be done in the joining store when generally credit card NO. is transmitted with SSL in Internet. It can think about the case that the control of the data isn't being done with many cases that the technical protection of the server isn't made being, and it is the reason why it is said that it has danger. Because it can think that the firewall spreads individually in the technical side as for the joining store in Internet as well, the rest will become the problem that control of data such as a card number is left in the joining store. But, this problem is not the problem of the Internet, but it is a use copy credit card store stay credit card problem.

It is the form of the electronic payment system each company such as electronic credit, a third party form, a prepaid system to do data after decoding with the server of a payment system company where technically even a human control side feels secure and to cut.
Therefore, these electronic payment systems may say assurance first. You may rather say safety more as much as there is no thing that a member number stays at the joining store like the case of the credit card of the rial shop,rial business.

http://www.savagerun.com/SSLSET.htm

Exercise 12. Designing a secure framework


1. Find out about SET and the use of RSA 128-bit encryption for e-commerce.


SET (Secure Electronic Transaction protocol) is a security method used in payment card transactions(payment gateways) that was developed originally by Visa and MasterCard. SET is an open protocol and standard for protecting the privacy, while ensuring the authenticity of the electronic transaction. The SET protocol consists of two different encrytion mechanisms. If uses sysmmetric encryption, in the form of the aging DES (Data Encryption Standard), and uses asymmetric (public key) encrytion to transmit session keys for DES transactions. SET simple uses 56 bits session keys which are transmitted asymmetrically. As the public key cryptography is only used to encrypt DES keys and for authentication, and not for the main body of the transaction to save computational cost. The DES algorithm has been used since year 1970.

RSA is a public key cryptosystem for both encryption and authentication. It was invented in 1977. It is an encryption algorithm that uses very large prime numbers to generate the public key and the private key. RSA is typically used in conjunction with a secret key cryptosystem such as DES. DES would be used to encrypt the message as a whole and then use RSA to encrypt the secret key. Thus, RSA provides a digital envelope for the message. RSA is in wide use today, it is possibly the most commonly used public key algorithm used. Because of this it has undergone a lot of public scrutiny and there is much empirical evidence of its security. It can be used for both encryption and signing.

As authentication is vital in e-commerce for both merchants and consumers, it is achieved through the use of digital signatures in SET. SET uses hashing algorithm to sign a transaction message with the sender's public key, and the authenticity of the transaction can be verified.


2.What can you find out about network and host-based intrusion detection systems?


An intrusion detection system (IDS) (software or Hardware) monitors network traffic and monitors for suspicious activity and alerts the system or network administrator. In some cases the IDS may also respond to anomalous or malicious traffic by taking action such as blocking the user or source IP address from accessing the network.

An IDS comes in a variety of “flavors” and approach the goal of detecting suspicious traffic in different ways. There are network based (NIDS) and host based (HIDS) intrusion detection systems. There are IDS that detect based on looking for specific signatures of known threats- similar to the way antivirus software typically detects and protects against malware- and there are IDS that detect based on comparing traffic patterns against a baseline and looking for anomalies.

NIDS

Network Intrusion Detection Systems are placed at a strategic point or points within the network to monitor traffic to and from all devices on the network. Ideally you would scan all inbound and outbound traffic, however doing so might create a bottleneck that would impair the overall speed of the network.

HIDS

Host Intrusion Detection Systems are run on individual hosts or devices on the network. A HIDS monitors the inbound and outbound packets from the device only and will alert the user or administrator of suspicious activity is detected

* Network-based vs. Host-based systems: in a network-based system, or NIDS, the individual packets flowing through a network are analyzed. The NIDS can detect malicious packets that are designed to be overlooked by a firewall’s simplistic filtering rules. In a host-based system, the IDS examines at the activity on each individual computer or host.


3. What is 'phishing'?


Phishing is an e-mail fraud method in which the perpetrator sends out legitimate-looking email in an attempt to gather personal and financial information from recipients. Typically, the messages appear to come from well known and trustworthy Web sites. Web sites that are frequently spoofed by phishers include PayPal, eBay, MSN, Yahoo, BestBuy, and America Online. A phishing expedition, like the fishing expedition it's named for, is a speculative venture: the phisher puts the lure hoping to fool at least a few of the prey that encounter the bait.


http://www.witiger.com/ecommerce/encryption.htm
http://netsecurity.about.com/cs/hackertools/a/aa030504.htm
http://www.webopedia.com/TERM/I/intrusion_detection_system.html
http://www.webopedia.com/TERM/p/phishing.html

Exerscise 11: XML Introduction


1. Conduct research on the Internet to find out what tools can be used to parse an XML document and ensure that the document is well formed and valid.


The following were found from a web search to validate that an XML is well formed and valid.

1 W3Schools
http://www.w3schools.com/Dom/dom_validate.asp

2 Scholarly technology group

http://www.stg.brown.edu/service/xmlvalid/

3 HTML/XML Validator

http://validator.aborla.net/index.php5?lang=en

4 XML well-formed checker and validator
http://www.cogsci.ed.ac.uk/~richard/xml-check.html

5. XMLPARSE at http://www.gnu.org/software/gnustep/resources/documentation/Developer/Tools/Reference/xmlparse.html



2. What are the benefits of adopting a schema standardized for a business sector?


The following can be considered benefits of adopting schema standards for a business sector

- Facilitate sharing of information between business;
- Ensure interoperability between corporate systems;
- Exchange documents between different people and organizations in much structured manner
- Improve efficiency in production, core distribution and operation;
- Establish a sophisticated level of computerization in product traceability and recycle fields;


3. SMIL is an application of XML. What is the purpose of this technology? Where does it apply?


SMIL (Synchronised Multimedia Integration Language) is a collection of reusable modules for multimedia editing and playing. To create a presentation with SMIL, an XML document is created with components of a head and body. The head defines the layout, and the body defines the content and where, when and for how long to display it. This allows you to overlay animation, logos, and other images over an image or video, without affecting the original video. This technique can be used for example, on a music television show where the name of a song and the artist will be displayed at the start of a song, trivial facts will be displayed throughout the song, and the television station logo is displayed in the corner throughout the broadcast.
It is specificlly useful for applying to the use of multimedia presentationon the web. As of Dec 1, 2008, The SYMM Working Group at W3C.org has published the SMIL 3.0 Recommendation. (http://www.w3.org/TR/2008/REC-SMIL3-20081201/)

Exerscise 10: Application Server Platforms in E-Commerce


1. Go to the website of IBM, Oracle, Microsoft and Sybase. Is there any mention of e-commerce associated with their database products? What suite or partnership do they list with related e-commerce offerings? How do they compare with open source products like MySQL?


The following is my observation after browsing the related sites of IBM


IBM’s main offerings relating to e-commerce revolve around the Websphere suite of products. However its most famous DB2 database products are focused more on data management.(this supports database driven e-commerce applications.)
Link :-
http://www-01.ibm.com/common/ssi/cgi-bin/ssialias?subtype=ca&infotype=an&appname=iSource&supplier=897&letternum=ENUS200-415

Oracle refers to iStore and Siebel Commerce suites as their E-commerce platform that supports database driven applications.

http://www.oracle.com/applications/crm/siebel/self-service-ebilling/siebel-e-commerce-8-1-1.html. They detail that this can be integrated with their own ERP applications.

Microsoft’s SQL server have SQL Server Database Engine and SQL Server Management Studio components. Using these, the database can be built, and then published using .NET Framework SDK 2.0 or Microsoft Visual Studio (Readme_reviewWatcher, 2009).
Their e-commerce efforts has been with MSDN for small business although they also have relevant articles dated for 2005 MS SQL for e-commerce.
Their latest releases are here (http://www.microsoft.com/sqlserver/2008/en/us/default.aspx)

Sybase does not focus on e-commerce however Sybase database products are often used as a backend to widely used ERP systems. These systems will only integrate with specified products seamlessly. To integrate them with other database systems, customisation and intermediate layers will be required.

MySQL data can be published interactively to the web using PHP. Although this is not an out-of-the-box solution, it provides greater flexibility, and reduces the overall cost of ownership. They have released their own version of GUI tools to help ease with the Database Administration

MySQL is a open source GPL license (acquired by Sun OS), but IBM, Oracle, Microsoft and Sybase are all related to paid/license software. In terms of functionality, there isn't much difference other than scalability and performance.



2. Why is the perception getting stronger that integration will become a critical factor in coming days? What is the role of AJAX within the enterprise software architecture?


Integration is gradually becoming more vital and critical to businesses as there is an increasing demand to access information across their systems and to integrate with other organizations as well. Large businesses expect their suppliers and customers to send or make data available and others focus on new technologies which allow integration and to push the demands forward. The most efficient way to do this is to automate the flow of data throughout the supply chain.

AJAX(Asynchronous Javascript and XML) refers to a wide range of web technologies that allow a web application to communicate with a background server (AJAX – Wikipedia, n.d.). Web applications that use AJAX can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. The use of Ajax has led to an increase in interactive animation on web pages. This additional functionality allows various sources to be integrated together seamlessly for the end user.



3. What are the similarities between the object-oriented development using model-view-controller (MVC) in Ruby on Rails 2.0 and Action Script 2.0 (Flash animations)?


1. Both Actionscript 2.0 and Ruby on Rails 2.0 have syntax for creating classes and objects. (They are Object Oriented Programming tools)
2. Used in some applications – Actionscript 2.0 in Alpha Five, and Ruby on Rails mostly with MySQL.
3. They have development tools which have built-in functionality for prototyping, and use freeform languages.

Exerscise 9: Web Form Design and Processing: A basis for e-commerce interaction


1. Design the Form







2. Write the Script

Please refer the Perl Script at.http://www.scriptarchive.com/download.cgi?s=ccver&c=txt&f=cc_ver.pl.

This was modified accordingly.

The first thing this script does is to tell the interpreter that it is a Perl script.
Next it imports required modules to handle CGI scripts.
It then creates a field storage instance to store the incoming data.
Next it retrieves the form data and stores it as a variable.


3. Can you modify the script to process the form?

Initially I had problems processing the form and then I was able to change the form to read input into new variables that I defined in particularly i changed to the variable to "parfarm" eq "french" then, process the Credit Card.
The CGI is placed onto the CGI bin directory.

Exerscise 8: PHP and MySQL database Access


1. Start with a simple table in a Database


I created a database called Test. I created a table called Employees and entered some values for this particular exercise.





2. Create a Webpage with the given code


The following is the code snippet and output:







3.This is how we add a record and is part of a file to create called add_record.html







4. The corresponding PHP file is add_records.php used with the POST method:




Once Added the following is displayed.




5. The last code example shows how to get multiple records.




Exerscise 7: User Input for Database Access with php


1. Create an HTML page with the form:






2. Then create a PHP file named submit.php with the following code:




Friday, May 29, 2009

Exerscise 6: Some Server Practice with PHP


1.


For this Exerscise I used PHP 5.2.9 and XAMP.

The Code:


The Output




2. Create a web application called "hello_world.php" which contains in the body.


Code :




Output

Exerscise 5: Network and Programming Frameworks


1. Investigate a simple chat client/server system. Look at some program code and describe how it works with multiple users.


1: A simple server that will accept a single client connection and display everything the client says on the screen. If the client user types ".bye", the client and the server will both quit.
2: A server as before, but this time it will remain 'open' for additional connection once a client has quit. The server can handle at most one connection at a time.
3: A server as before, but this time it can handle multiple clients simultaneously. The output from all connected clients will appear on the server's screen.
4: A server as before, but this time it sends all text received from any of the connected clients to all clients. This means that the server has to receive and send, and the client has to send as well as receive
5: Wrapping the client from step 4 into a very simple GUI interface but not changing the functionality of either server or client. The client is implemented as an Applet, but a Frame would have worked just as well (for a stand-alone program).

Step 1: Simple, one-time Server

import java.net.*;
import java.io.*;

public class ChatServer
{ private Socket socket = null;
private ServerSocket server = null;
private DataInputStream streamIn = null;

public ChatServer(int port)
{ try
{ System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted: " + socket);
open();
boolean done = false;
while (!done)
{ try
{ String line = streamIn.readUTF();
System.out.println(line);
done = line.equals(".bye");
}
catch(IOException ioe)
{ done = true;
}
}
close();
}
catch(IOException ioe)
{ System.out.println(ioe);
}
}
public void open() throws IOException
{ streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
}
public void close() throws IOException
{ if (socket != null) socket.close();
if (streamIn != null) streamIn.close();
}
public static void main(String args[])
{ ChatServer server = null;
if (args.length != 1)
System.out.println("Usage: java ChatServer port");
else
server = new ChatServer(Integer.parseInt(args[0]));
}
}

The Simple Client corresponding to the previous server (and to step 2 and step 3 servers as well):

import java.net.*;
import java.io.*;

public class ChatClient
{ private Socket socket = null;
private DataInputStream console = null;
private DataOutputStream streamOut = null;

public ChatClient(String serverName, int serverPort)
{ System.out.println("Establishing connection. Please wait ...");
try
{ socket = new Socket(serverName, serverPort);
System.out.println("Connected: " + socket);
start();
}
catch(UnknownHostException uhe)
{ System.out.println("Host unknown: " + uhe.getMessage());
}
catch(IOException ioe)
{ System.out.println("Unexpected exception: " + ioe.getMessage());
}
String line = "";
while (!line.equals(".bye"))
{ try
{ line = console.readLine();
streamOut.writeUTF(line);
streamOut.flush();
}
catch(IOException ioe)
{ System.out.println("Sending error: " + ioe.getMessage());
}
}
}
public void start() throws IOException
{ console = new DataInputStream(System.in);
streamOut = new DataOutputStream(socket.getOutputStream());
}
public void stop()
{ try
{ if (console != null) console.close();
if (streamOut != null) streamOut.close();
if (socket != null) socket.close();
}
catch(IOException ioe)
{ System.out.println("Error closing ...");
}
}
public static void main(String args[])
{ ChatClient client = null;
if (args.length != 2)
System.out.println("Usage: java ChatClient host port");
else
client = new ChatClient(args[0], Integer.parseInt(args[1]));
}
}


Step 2: Many Time Server, One Client (Client is as before)

import java.net.*;
import java.io.*;

public class ChatServer implements Runnable
{ private Socket socket = null;
private ServerSocket server = null;
private Thread thread = null;
private DataInputStream streamIn = null;

public ChatServer(int port)
{ try
{ System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
start();
}
catch(IOException ioe)
{ System.out.println(ioe);
}
}
public void run()
{ while (thread != null)
{ try
{ System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted: " + socket);
open();
boolean done = false;
while (!done)
{ try
{ String line = streamIn.readUTF();
System.out.println(line);
done = line.equals(".bye");
}
catch(IOException ioe)
{ done = true; }
}
close();
}
catch(IOException ie)
{ System.out.println("Acceptance Error: " + ie); }
}
}
public void start()
{ if (thread == null)
{ thread = new Thread(this);
thread.start();
}
}
public void stop()
{ if (thread != null)
{ thread.stop();
thread = null;
}
}
public void open() throws IOException
{ streamIn = new DataInputStream(new
BufferedInputStream(socket.getInputStream()));
}
public void close() throws IOException
{ if (socket != null) socket.close();
if (streamIn != null) streamIn.close();
}
public static void main(String args[])
{ ChatServer server = null;
if (args.length != 1)
System.out.println("Usage: java ChatServer port");
else
server = new ChatServer(Integer.parseInt(args[0]));
}
}

Step 3: Multi-Server handling Multi-Client (Client as before)

import java.net.*;
import java.io.*;

public class ChatServer implements Runnable
{ private ServerSocket server = null;
private Thread thread = null;
private ChatServerThread client = null;

public ChatServer(int port)
{ try
{ System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
start();
}
catch(IOException ioe)
{ System.out.println(ioe); }
}
public void run()
{ while (thread != null)
{ try
{ System.out.println("Waiting for a client ...");
addThread(server.accept());
}
catch(IOException ie)
{ System.out.println("Acceptance Error: " + ie); }
}
}
public void addThread(Socket socket)
{ System.out.println("Client accepted: " + socket);
client = new ChatServerThread(this, socket);
try
{ client.open();
client.start();
}
catch(IOException ioe)
{ System.out.println("Error opening thread: " + ioe); }
}
public void start() { /* no change */ }
public void stop() { /* no change */ }
public static void main(String args[]){ /* no change */ }
}

import java.net.*;
import java.io.*;

public class ChatServerThread extends Thread
{ private Socket socket = null;
private ChatServer server = null;
private int ID = -1;
private DataInputStream streamIn = null;

public ChatServerThread(ChatServer _server, Socket _socket)
{ server = _server; socket = _socket; ID = socket.getPort();
}
public void run()
{ System.out.println("Server Thread " + ID + " running.");
while (true)
{ try
{ System.out.println(streamIn.readUTF());
}
catch(IOException ioe) { }
}
}
public void open() throws IOException
{ streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
}
public void close() throws IOException
{ if (socket != null) socket.close();
if (streamIn != null) streamIn.close();
}
}


Step 4: A Simple but functional, text based chat server/client

import java.net.*;
import java.io.*;

public class ChatServer implements Runnable
{ private ChatServerThread clients[] = new ChatServerThread[50];
private ServerSocket server = null;
private Thread thread = null;
private int clientCount = 0;

public ChatServer(int port)
{ try
{ System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
start(); }
catch(IOException ioe)
{ System.out.println("Can not bind to port " + port + ": " + ioe.getMessage()); }
}
public void run()
{ while (thread != null)
{ try
{ System.out.println("Waiting for a client ...");
addThread(server.accept()); }
catch(IOException ioe)
{ System.out.println("Server accept error: " + ioe); stop(); }
}
}
public void start() { /* as before */ }
public void stop() { /* as before */ }
private int findClient(int ID)
{ for (int i = 0; i < clientCount; i++)
if (clients[i].getID() == ID)
return i;
return -1;
}
public synchronized void handle(int ID, String input)
{ if (input.equals(".bye"))
{ clients[findClient(ID)].send(".bye");
remove(ID); }
else
for (int i = 0; i < clientCount; i++)
clients[i].send(ID + ": " + input);
}
public synchronized void remove(int ID)
{ int pos = findClient(ID);
if (pos >= 0)
{ ChatServerThread toTerminate = clients[pos];
System.out.println("Removing client thread " + ID + " at " + pos);
if (pos < clientCount-1)
for (int i = pos+1; i < clientCount; i++)
clients[i-1] = clients[i];
clientCount--;
try
{ toTerminate.close(); }
catch(IOException ioe)
{ System.out.println("Error closing thread: " + ioe); }
toTerminate.stop(); }
}
private void addThread(Socket socket)
{ if (clientCount < clients.length)
{ System.out.println("Client accepted: " + socket);
clients[clientCount] = new ChatServerThread(this, socket);
try
{ clients[clientCount].open();
clients[clientCount].start();
clientCount++; }
catch(IOException ioe)
{ System.out.println("Error opening thread: " + ioe); } }
else
System.out.println("Client refused: maximum " + clients.length + " reached.");
}
public static void main(String args[]) { /* as before */ }
}

import java.net.*;
import java.io.*;

public class ChatServerThread extends Thread
{ private ChatServer server = null;
private Socket socket = null;
private int ID = -1;
private DataInputStream streamIn = null;
private DataOutputStream streamOut = null;

public ChatServerThread(ChatServer _server, Socket _socket)
{ super();
server = _server;
socket = _socket;
ID = socket.getPort();
}
public void send(String msg)
{ try
{ streamOut.writeUTF(msg);
streamOut.flush();
}
catch(IOException ioe)
{ System.out.println(ID + " ERROR sending: " + ioe.getMessage());
server.remove(ID);
stop();
}
}
public int getID()
{ return ID;
}
public void run()
{ System.out.println("Server Thread " + ID + " running.");
while (true)
{ try
{ server.handle(ID, streamIn.readUTF());
}
catch(IOException ioe)
{ System.out.println(ID + " ERROR reading: " + ioe.getMessage());
server.remove(ID);
stop();
}
}
}
public void open() throws IOException
{ streamIn = new DataInputStream(new
BufferedInputStream(socket.getInputStream()));
streamOut = new DataOutputStream(new
BufferedOutputStream(socket.getOutputStream()));
}
public void close() throws IOException
{ if (socket != null) socket.close();
if (streamIn != null) streamIn.close();
if (streamOut != null) streamOut.close();
}
}

import java.net.*;
import java.io.*;

public class ChatClient implements Runnable
{ private Socket socket = null;
private Thread thread = null;
private DataInputStream console = null;
private DataOutputStream streamOut = null;
private ChatClientThread client = null;

public ChatClient(String serverName, int serverPort)
{ System.out.println("Establishing connection. Please wait ...");
try
{ socket = new Socket(serverName, serverPort);
System.out.println("Connected: " + socket);
start();
}
catch(UnknownHostException uhe)
{ System.out.println("Host unknown: " + uhe.getMessage()); }
catch(IOException ioe)
{ System.out.println("Unexpected exception: " + ioe.getMessage()); }
}
public void run()
{ while (thread != null)
{ try
{ streamOut.writeUTF(console.readLine());
streamOut.flush();
}
catch(IOException ioe)
{ System.out.println("Sending error: " + ioe.getMessage());
stop();
}
}
}
public void handle(String msg)
{ if (msg.equals(".bye"))
{ System.out.println("Good bye. Press RETURN to exit ...");
stop();
}
else
System.out.println(msg);
}
public void start() throws IOException
{ console = new DataInputStream(System.in);
streamOut = new DataOutputStream(socket.getOutputStream());
if (thread == null)
{ client = new ChatClientThread(this, socket);
thread = new Thread(this);
thread.start();
}
}
public void stop()
{ if (thread != null)
{ thread.stop();
thread = null;
}
try
{ if (console != null) console.close();
if (streamOut != null) streamOut.close();
if (socket != null) socket.close();
}
catch(IOException ioe)
{ System.out.println("Error closing ..."); }
client.close();
client.stop();
}
public static void main(String args[])
{ ChatClient client = null;
if (args.length != 2)
System.out.println("Usage: java ChatClient host port");
else
client = new ChatClient(args[0], Integer.parseInt(args[1]));
}
}

import java.net.*;
import java.io.*;

public class ChatClientThread extends Thread
{ private Socket socket = null;
private ChatClient client = null;
private DataInputStream streamIn = null;

public ChatClientThread(ChatClient _client, Socket _socket)
{ client = _client;
socket = _socket;
open();
start();
}
public void open()
{ try
{ streamIn = new DataInputStream(socket.getInputStream());
}
catch(IOException ioe)
{ System.out.println("Error getting input stream: " + ioe);
client.stop();
}
}
public void close()
{ try
{ if (streamIn != null) streamIn.close();
}
catch(IOException ioe)
{ System.out.println("Error closing input stream: " + ioe);
}
}
public void run()
{ while (true)
{ try
{ client.handle(streamIn.readUTF());
}
catch(IOException ioe)
{ System.out.println("Listening error: " + ioe.getMessage());
client.stop();
}
}
}
}


Stage 5: Chat client moved to very simple GUI interface

import java.net.*;
import java.io.*;
import java.applet.*;
import java.awt.*;
public class ChatClient extends Applet
{ private Socket socket = null;
private DataInputStream console = null;
private DataOutputStream streamOut = null;
private ChatClientThread client = null;
private TextArea display = new TextArea();
private TextField input = new TextField();
private Button send = new Button("Send"), connect = new Button("Connect"),
quit = new Button("Bye");
private String serverName = "localhost";
private int serverPort = 4444;

public void init()
{ Panel keys = new Panel(); keys.setLayout(new GridLayout(1,2));
keys.add(quit); keys.add(connect);
Panel south = new Panel(); south.setLayout(new BorderLayout());
south.add("West", keys); south.add("Center", input); south.add("East", send);
Label title = new Label("Simple Chat Client Applet", Label.CENTER);
title.setFont(new Font("Helvetica", Font.BOLD, 14));
setLayout(new BorderLayout());
add("North", title); add("Center", display); add("South", south);
quit.disable(); send.disable(); getParameters(); }
public boolean action(Event e, Object o)
{ if (e.target == quit)
{ input.setText(".bye");
send(); quit.disable(); send.disable(); connect.enable(); }
else if (e.target == connect)
{ connect(serverName, serverPort); }
else if (e.target == send)
{ send(); input.requestFocus(); }
return true; }
public void connect(String serverName, int serverPort)
{ println("Establishing connection. Please wait ...");
try
{ socket = new Socket(serverName, serverPort);
println("Connected: " + socket);
open(); send.enable(); connect.disable(); quit.enable(); }
catch(UnknownHostException uhe)
{ println("Host unknown: " + uhe.getMessage()); }
catch(IOException ioe)
{ println("Unexpected exception: " + ioe.getMessage()); } }
private void send()
{ try
{ streamOut.writeUTF(input.getText()); streamOut.flush(); input.setText(""); }
catch(IOException ioe)
{ println("Sending error: " + ioe.getMessage()); close(); } }
public void handle(String msg)
{ if (msg.equals(".bye"))
{ println("Good bye. Press RETURN to exit ..."); close(); }
else println(msg); }
public void open()
{ try
{ streamOut = new DataOutputStream(socket.getOutputStream());
client = new ChatClientThread(this, socket); }
catch(IOException ioe)
{ println("Error opening output stream: " + ioe); } }
public void close()
{ try
{ if (streamOut != null) streamOut.close();
if (socket != null) socket.close(); }
catch(IOException ioe)
{ println("Error closing ..."); }
client.close(); client.stop(); }
private void println(String msg)
{ display.appendText(msg + "\n"); }
public void getParameters()
{ serverName = getParameter("host");
serverPort = Integer.parseInt(getParameter("port")); }

Referred :

http://pirate.shu.edu/~wachsmut/Teaching/CSAS2214/Virtual/Lectures/chat-client-server.html



2. Describe the important and distinguishing properties of Peer to Peer computing and the Grid. How is this peer to peer and the Grid architecture changing work flow and service-oriented applications?


Peer-to-peer networks
The traditional client-server Internet model ("client" asks for and receives information from "server") is beginning to give some ground to peer-to-peer (P2P) networking - where all network participants are approximately equal. The primary advantage of P2P networks is that large numbers of people share the burden of providing computing resources (processor time and disk space), administration effort, creativity and legal liability. It's relatively easy to be anonymous in such an environment and it's harder for opponents of a P2P service to bring it down.

Napster was one of the best-known examples to date, though it's not a completely P2P system because users register their file libraries with a central server when they log on to the service. Because of this central link, it was possible for opponents to force Napster to stop facilitating free music downloads. This was done by legal action on behalf of the music industry, to protect copyright infringement. However, true P2P networks such as Kaaza and Morpheus now operate with impunity, because there is no central server, They are now generating traffic many times the rate of Napster at its peak.

P2P has some limitations
P2P does have problems. The primary disadvantage is the tendency of computers at the edge of the network to fade in and out of availability. Also, accountability for the actions of network participants could be a difficult problem. Several high-profile implementations have shown that architecture, security, and systems management issues are difficult to control. For these reasons, system managers often prefer to operate P2P systems as separate isolated entities. But, doing so is often impossible for practical applications.

The increasing reach of P2P beyond the desktop and into distributed computing fringe may further magnify these stumbling blocks. But that will not hold back the rising tide of P2P implementations. Dramatic cost savings and the ability to do parallel processing will continue to drive P2P use higher.


Grid Computing
Grid Computing can be defined as applying resources from many computers in a network to a single problem, usually one that requires a large number of processing cycles or access to large amounts of data.

The computational power grid is analogous to electric power grid. It allows the coupling of geographically distributed resources to offer consistent and inexpensive access to resources irrespective of their physical location or access point. The Internet or dedicated networks can be used to interconnect a wide variety of distributed computational resources (such as supercomputers, computer clusters, storage systems, data sources) and present them as a single, unified resource.

At its core, Grid Computing enables devices-regardless of their operating characteristics-to be virtually shared, managed and accessed across an enterprise, industry or workgroup. This virtualization of resources places all of the necessary access, data and processing power at the fingertips of those who need to rapidly solve complex business problems, conduct compute-intensive research and data analysis, and operate in real-time.

A company with slightly fewer than 2,000 desktop computers can harvest nearly 1 teraflop (one trillion floating-point operations per second) of computing capacity. Even better, the company can capture that power from computers it already owns that sit idle at night and work at less than full capacity during the day.

Universities and research institutions have long used grid-computing technology, but recently it is also making fast inroads into the business market. IBM has recently come up with operating standards that will generate many new business applications and will cause wide proliferation.


Resource location or discovery is a key issue for Grid systems in which applications are composed of hardware and software resources that need to be located. Classical approaches to Grid resource location are either centralized or hierarchical and will prove inefficient as the scale of Grid systems rapidly increases. On the other hand, the Peer-to-Peer (P2P) paradigm emerged as a successful model that achieves scalability in distributed systems. One possibility would be to borrow existing methods from the P2P paradigm and to adopt them to Grid systems taking into consideration the existing differences. Several such attempts have been made during the last couple of years. The architecture has a 3-layered hierarchical configuration-procedure-layer, role-layer, and actor-layer-and the three workflow knowledge models-ICN-based model, role-based model, and actor-based model-are the workflow knowledge representations on Grid/P2P nodes in the corresponding layers, respectively

Referred : http://www.jimpinto.com/writings/grid.html


3. Frameworks for development. Compare and contrast any TWO of:


Java
.NET
Ruby on Rails
Turbo Gears
Google Gears
AJAX frameworks

Comparing Java with .Net