Question about Operating Systems

1 Answer

Please explain the working of this code

Import java.io.*;
import java.net.*;
import java.util.*;
import java.nio.*;
import java.nio.charset.*;
import java.nio.channels.*;
class NewIOHTTPServerTest{
private static String[] symbols = {"DELL", "INTC", "MSFT", "ORCL", "SUNW"};
private static Random rnd = new Random();
private static Charset cs = Charset.forName("UTF-8");
public static void main(String[] args) throws Exception{
Selector selector = Selector.open();

ServerSocketChannel server = ServerSocketChannel.open();
server.configureBlocking(
false);
server.socket().bind(
new InetSocketAddress(8055));
server.register(selector, SelectionKey.OP_ACCEPT);

//register other server channels

for(;;){
if(selector.select(1000) > 0){
Iterator i = selector.selectedKeys().iterator();
while(i.hasNext()){
SelectionKey key = (SelectionKey) i.next();
if(key.isAcceptable()){
ServerSocketChannel channel = (ServerSocketChannel) key.channel();
SocketChannel client = channel.accept();
client.configureBlocking(
false);
client.register(selector, SelectionKey.OP_READ);
}
else if(key.isReadable()){
SocketChannel channel = (SocketChannel) key.channel();
if(channel.socket().getLocalPort() == 8055)
handleHTTPRequest(channel);
}
i.remove();
}
}
else{
System.out.print(
new Date() + "\r");
}
}
}
private static void handleHTTPRequest(SocketChannel channel) throws IOException{
ByteBuffer buffer = ByteBuffer.allocate(1024);
int n = channel.read(buffer);
buffer.flip();
String request = cs.decode(buffer).toString();
String[] headers = request.split("\r\n");
String symbol = headers[0].substring(5, headers[0].length() - 9);
String response;
if(Arrays.binarySearch(symbols, symbol) >= 0)
response = "Price is " + (1000 + rnd.nextInt(9000)) / 100.0;
else
response = "Price not available";
channel.write(cs.encode("HTTP/1.0 200 OK\r\n"));
channel.write(cs.encode("Content-type: text/plain\r\n\r\n"));
channel.write(cs.encode(response));
channel.close();
}
}




















Posted by on

1 Answer

  • Level 1:

    An expert who has achieved level 1.

  • Contributor
  • 2 Answers

It's a Java http server (webserver) that serves random "prices" if they match a search string.

Well here is an explaination:

private static String[] symbols = {"DELL", "INTC", "MSFT", "ORCL", "SUNW"};
These are search strings

private static Random rnd = new Random();
This generates a random number

private static Charset cs = Charset.forName("UTF-8");
This is the charset that the http server uses

ServerSocketChannel server = ServerSocketChannel.open();
Create a new server

server.socket().bind(new InetSocketAddress(8055));
Bind the http server to port 8055

The rest is handling the request and processing it

But here:
if(Arrays.binarySearch(symbols, symbol) >= 0)
response = "Price is " + (1000 + rnd.nextInt(9000)) / 100.0;
else
response = "Price not available";
channel.write(cs.encode("HTTP/1.0 200 OK "));
channel.write(cs.encode("Content-type: text/plain "));
channel.write(cs.encode(response));
channel.close();
}
It sees if the string input matchs: DELL INTC MSFT ORCL SUNW.

(private static String[] symbols = {"DELL", "INTC", "MSFT", "ORCL", "SUNW"};)
If so, it gives a price based on a random number.
(
response = "Price is " + (1000 + rnd.nextInt(9000)) / 100.0;)
Or else
It says "price not available"
then it gives a html header to end the error message.

Hope I helped you :)
Gook luck

Posted on Nov 26, 2008

Add Your Answer

Uploading: 0%

my-video-file.mp4

Complete. Click "Add" to insert your video. Add

×

Loading...
Loading...

Related Questions:

1 Answer

What difference between genricServlet and httpServlet


public abstract class GenericServlet extends java.lang.Object implements Servlet, ServletConfig, java.io.Serializable
  • GenericServlet defines a generic, protocol-independent servlet.
  • GenericServlet gives a blueprint and makes writing servlet easier.
  • GenericServlet provides simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface.
  • GenericServlet implements the log method, declared in the ServletContext interface.
  • To write a generic servlet, it is sufficient to override the abstract service method.
javax.servlet.http.HttpServlet
Signature: public abstract class HttpServlet extends GenericServlet implements java.io.Serializable
  • HttpServlet defines a HTTP protocol specific servlet.
  • HttpServlet gives a blueprint for Http servlet and makes writing them easier.
  • HttpServlet extends the GenericServlet and hence inherits the properties GenericServlet.

May 12, 2011 | Operating Systems

2 Answers

Codes for if else if statement in java script


if (condition) {
//conditional true code here
} else {
//conditional false code here
}

Mar 23, 2011 | Operating Systems

1 Answer

I need a complete workingsource code written in


This is a simple source code for Simple calculator in Java using RMI
//mathServer//
import java.rmi.*;
import java.rmi.Naming.*;
import java.rmi.server.*;
import java.rmi.registry.*;
import java.net.*;
import java.util.*;
interface mathInterface extends Remote
{
public int add(int a,int b) throws RemoteException;
public int subt(int a,int b) throws RemoteException;
public int mult(int a,int b) throws RemoteException;
public int div(int a,int b) throws RemoteException;
}
public class mathServer extends UnicastRemoteObject implements
mathInterface
{
public mathServer() throws RemoteException
{
System.out.println("Initializing Server");
}
public int add(int a,int b)
{
return(a+b);
}
public int subt(int a,int b)
{
return(a-b);
}
public int mult(int a,int b)
{
return(a*b);
}
public int div(int a,int b)
{
return(a/b);
}
public static void main(String args[])
{
try
{
mathServer ms=new mathServer();
java.rmi.Naming.rebind("MathServ",ms);
System.out.println("Server Ready");
}
catch(RemoteException RE)
{
System.out.println("Remote Server Error:"+ RE.getMessage());
System.exit(0);
}
catch(MalformedURLException ME)
{
System.out.println("Invalid URL!!");
}
}
}

//mathClient//
import java.rmi.*;
import java.rmi.registry.*;
import java.awt.*;
import java.awt.event.*;
public class mathClient extends Frame implements ActionListener
{
Button B1=new Button("Sum");
Button B2=new Button("Subtract");
Button B3=new Button("Multiply");
Button B4=new Button("Divide");
Label l1=new Label("Number 1");
Label l2=new Label("Number 2");
Label l3=new Label("Result");
TextField t1=new TextField(20);
TextField t2=new TextField(20);
TextField t3=new TextField(20);
public mathClient()
{
super("Calculator");
setLayout(null);
l1.setBounds(20,50,55,25);
add(l1);
l2.setBounds(20,100,55,25);
add(l2);
l3.setBounds(20,150,55,25);
add(l3);
t1.setBounds(150,50,100,25);
add(t1);
t2.setBounds(150,100,100,25);
add(t2);
t3.setBounds(150,150,100,25);
add(t3);
B1.setBounds(20,200,80,25);
add(B1);
B2.setBounds(100,200,80,25);
add(B2);
B3.setBounds(180,200,80,25);
add(B3);
B4.setBounds(260,200,80,25);
add(B4);
B1.addActionListener(this);
B2.addActionListener(this);
B3.addActionListener(this);
B4.addActionListener(this);
addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
}
public void actionPerformed(ActionEvent AE)
{
if(AE.getSource()==B1)
{
sum();
}
else if(AE.getSource()==B2)
{
subt();
}
else if(AE.getSource()==B3)
{
mult();
}
else if(AE.getSource()==B4)
{
div();
}
}
public void sum()
{
int i=Integer.parseInt(t1.getText());
int j=Integer.parseInt(t2.getText());
int val;
try
{
String ServerURL="MathServ";
mathInterface MI=(mathInterface)Naming.lookup(ServerURL);
val=MI.add(i,j);
t3.setText(""+val);
}
catch(Exception ex)
{
System.out.println("Exception:"+ex);
}
}
public void subt()
{
int i=Integer.parseInt(t1.getText());
int j=Integer.parseInt(t2.getText());
int val;
try
{
String ServerURL="MathServ";
mathInterface MI=(mathInterface)Naming.lookup(ServerURL);
val=MI.subt(i,j);
t3.setText(""+val);
}
catch(Exception ex)
{
System.out.println("Exception:"+ex);
}
}
public void mult()
{
int i=Integer.parseInt(t1.getText());
int j=Integer.parseInt(t2.getText());
int val;
try
{
String ServerURL="MathServ";
mathInterface MI=(mathInterface)Naming.lookup(ServerURL);
val=MI.mult(i,j);
t3.setText(""+val);
}
catch(Exception ex)
{
System.out.println("Exception:"+ex);
}
}
public void div()
{
int i=Integer.parseInt(t1.getText());
int j=Integer.parseInt(t2.getText());
int val;
try
{
String ServerURL="MathServ";
mathInterface MI=(mathInterface)Naming.lookup(ServerURL);
val=MI.div(i,j);
t3.setText(""+val);
}
catch(Exception ex)
{
System.out.println("Exception:"+ex);
}
}
public static void main(String args[])
{
mathClient MC=new mathClient();
MC.setVisible(true);
MC.setSize(600,500);
};
}

Jul 03, 2009 | Microsoft Operating Systems

2 Answers

How to connect from jsp login page to database


hey try this code......just found it on the net... Put the code in tomcat and test the application through browser. The browser should display the display the data stored in the table.

Here is the code of our JSP file
<%@ page language="java" import="java.sql.*"%>
<html>
<head><title>Read from mySQL Database</title>
</head>
<body>

<p align="center"><b>Following records are selected from the 'jakartaproject' table.</b><br>&nbsp;</p>

<div align="center" width="85%">
<center>
<table border="1" borderColor="#ffe9bf" cellPadding="0" cellSpacing="0" width="658" height="63">
<tbody>
<td bgColor="#008080" width="47" align="center" height="19"><font color="#ffffff"><b>Sr.
No.</b></font></td>
<td bgColor="#008080" width="107" height="19"><font color="#ffffff"><b>Project</b></font></td>
<td bgColor="#008080" width="224" height="19"><font color="#ffffff"><b>Url
Address</b></font></td>
<td bgColor="#008080" width="270" height="19"><font color="#ffffff"><b>Description
of the project</b></font></td>

<%
String DRIVER = "org.gjt.mm.mysql.Driver";
Class.forName(DRIVER).newInstance();


Connection con=null;
ResultSet rst=null;
Statement stmt=null;

try{
String url="jdbc:mysql://192.168.10.2/tutorial?user=tutorial&password=tutorial";

int i=1;
con=DriverManager.getConnection(url);
stmt=con.createStatement();
rst=stmt.executeQuery("select * from jakartaproject ");
while(rst.next()){

if (i==(i/2)*2){
%>
<tr>
<td bgColor="#ffff98" vAlign="top" width="47" align="center" height="19"><%=i%>.</td>
<td bgColor="#ffff98" vAlign="top" width="107" height="19"><%=rst.getString(2)%></td>
<td bgColor="#ffff98" vAlign="top" width="224" height="19"><a href="<%=rst.getString(3)%>"><%=rst.getString(3)%></a>&nbsp;</td>
<td bgColor="#ffff98" vAlign="top" width="270" height="19"><%=rst.getString(4)%></td>
</tr>
<%
}else{
%>
<tr>
<td bgColor="#ffcc68" vAlign="top" width="47" align="center" height="19"><%=i%>.</td>
<td bgColor="#ffcc68" vAlign="top" width="107" height="19"><%=rst.getString(2)%></td>
<td bgColor="#ffcc68" vAlign="top" width="224" height="19"><a href="<%=rst.getString(3)%>"><%=rst.getString(3)%></a>&nbsp;</td>
<td bgColor="#ffcc68" vAlign="top" width="270" height="19"><%=rst.getString(4)%></td>
</tr>
<% }

i++;
}
rst.close();
stmt.close();
con.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
%>

</tbody>
</table>
</center>
</div>


</body>
</html>

Feb 27, 2009 | Compaq Operating Systems

1 Answer

How to write jdbc connections


http://www.jdbc-tutorial.com/

window.google_render_ad();

welcome_title_image.gif Java JDBC Tutorial Java JDBC Tutorial
The JDBC ( Java Database Connectivity) API defines interfaces and classes for writing database applications in Java by making database connections. Using JDBC you can send SQL, PL/SQL statements to almost any relational database. JDBC is a Java API for executing SQL statements and supports basic SQL functionality. It provides RDBMS access by allowing you to embed SQL inside Java code. Because Java can run on a thin client, applets embedded in Web pages can contain downloadable JDBC code to enable remote database access. You will learn how to create a table, insert values into it, query the table, retrieve results, and update the table with the help of a JDBC Program example.


window.google_render_ad();
Although JDBC was designed specifically to provide a Java interface to relational databases, you may find that you need to write Java code to access non-relational databases as well.
JDBC Architecture jdbc.jpg Java application calls the JDBC library. JDBC loads a driver which talks to the database. We can change database engines without changing database code.
JDBC Basics - Java Database Connectivity Steps Before you can create a java jdbc connection to the database, you must first import the
java.sql package.
import java.sql.*; The star ( * ) indicates that all of the classes in the package java.sql are to be imported.
1. Loading a database driver,
In this step of the jdbc connection process, we load the driver class by calling Class.forName() with the Driver class name as an argument. Once loaded, the Driver class creates an instance of itself. A client can connect to Database Server through JDBC Driver. Since most of the Database servers support ODBC driver therefore JDBC-ODBC Bridge driver is commonly used.
The return type of the Class.forName (String ClassName) method is “Class”. Class is a class in
java.lang package.
try { Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”); //Or any other driver } catch(Exception x){ System.out.println( “Unable to load the driver class!” ); } 2. Creating a oracle jdbc Connection

The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager is considered the backbone of JDBC architecture. DriverManager class manages the JDBC drivers that are installed on the system. Its getConnection() method is used to establish a connection to a database. It uses a username, password, and a jdbc url to establish a connection to the database and returns a connection object. A jdbc Connection represents a session/connection with a specific database. Within the context of a Connection, SQL, PL/SQL statements are executed and results are returned. An application can have one or more connections with a single database, or it can have many connections with different databases. A Connection object provides metadata i.e. information about the database, tables, and fields. It also contains methods to deal with transactions.
JDBC URL Syntax:: jdbc: <subprotocol>: <subname> JDBC URL Example:: jdbc: <subprotocol>: <subname>•Each driver

Feb 01, 2009 | Microsoft Windows XP Home Edition

1 Answer

How to play audio clip in java


  • Create an AudioClip object
  • Load .au sound file into AudioClip
  • Play sounds once or loop continuously
  • Stop playback


Here's how the code for these steps looks:
import java.applet.*;
AudioClip ac = getAudioClip(getCodeBase(), soundFile);
ac.play(); //play once
ac.stop(); //stop playing
ac.loop(); //play continuously


It would seem logical to use this same code to play audio clips in a Java application. Unfortunately, if you do that you will get errors from the compiler. Why? Because the AudioClip object and the getAudioClip() method are part of the java.applet package -- and are not part of applications. The good news is we can dive down and make things work ourselves.
The trick to solving this problem is to use some undocumented features that are provided by Sun in its JDK. Taking a peek inside the classes.zip file from the Sun JDK (using any of the various zipfile utilities), we find not only the standard Java packages such as java.applet but also sun.audio. (These are in the directory sun/audio.)
The sun.audio package contains everything we need to be able to play audio clips! Here's the code:
import sun.audio.*; //import the sun.audio package
import java.io.*;
//** add this into your application code as appropriate
// Open an input stream to the audio file.
InputStream in = new FileInputStream(Filename);
// Create an AudioStream object from the input stream.
AudioStream as = new AudioStream(in);
// Use the static class member "player" from class AudioPlayer to play
// clip.
AudioPlayer.player.start(as);
// Similarly, to stop the audio.
AudioPlayer.player.stop(as);


To use a URL as the audio stream source, substitute the following for the input stream and audio stream setup:
AudioStream as = new AudioStream (url.openStream());


Playing the audio stream continuously adds a bit more complexity:
// Create audio stream as discussed previously.
// Create AudioData source.
AudioData data = as.getData();
// Create ContinuousAudioDataStream.
ContinuousAudioDataStream cas = new ContinuousAudioDataStream (data);
// Play audio.
AudioPlayer.player.play (cas);
// Similarly, to stop the audio.
AudioPlayer.player.stop (cas);

Jan 22, 2009 | Operating Systems

3 Answers

What is servlets?


Java Servlet technology provides Web developers with a simple, consistent mechanism for extending the functionality of a Web server and for accessing existing business systems. A servlet can almost be thought of as an applet that runs on the server side--without a face. Java servlets make many Web applications possible.  » Read More The reference implementation is included in the Java EE 5 SDK and also in the open-source Java Platform, Enterprise Edition (Java EE) application server, available through the GlassFish project, which you can download from java.net. The reference implementation source code is available from the servlet-sources project on java.net.

Dec 29, 2008 | Microsoft Windows Vista Ultimate Edition

2 Answers

StartActivity fails to launch class called


This example is working try it.

Forwarding.java
----------------------

package com.example.android.apis.graphics;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Forwarding extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.forwarding);
Button goButton = (Button)findViewById(R.id.go);
goButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
Intent intent = new Intent();
intent.setClass(Forwarding.this, ForwardTarget.class);
startActivity(intent);
finish();
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
});
}
}


ForwardTarget
--------------------

package com.example.android.apis.graphics;
import android.app.Activity;
import android.os.Bundle;
public class ForwardTarget extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

setContentView(R.layout.forward_target);
}
}



AndroidManifest.xml
-----------------------------

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.apis.graphics"
android:versionCode="1"
android:versionName="1.0.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Forwarding"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ForwardTarget"/>
</application>
</manifest>


forwarding.xml
---------------------

<?xml version="1.0" encoding="utf-8" ?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:padding="4dip"
android:gravity="center_horizontal" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_weight="0"
android:paddingBottom="4dip" android:text="forwarding" />
<Button android:id="@+id/go" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="go">
<requestFocus />
</Button>
</LinearLayout>

forward_target.xml
---------------------------

<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:padding="4dip"
android:gravity="center_horizontal" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_weight="0"
android:text="forward_target" />
</LinearLayout>


Nov 03, 2008 | Google Android

Not finding what you are looking for?
Operating Systems Logo

Related Topics:

148 people viewed this question

Ask a Question

Usually answered in minutes!

Top Operating Systems Experts

Les Dickinson
Les Dickinson

Level 3 Expert

18297 Answers

Brian Sullivan
Brian Sullivan

Level 3 Expert

27725 Answers

Prashant  Sharma
Prashant Sharma

Level 3 Expert

1127 Answers

Are you an Operating System Expert? Answer questions, earn points and help others

Answer questions

Manuals & User Guides

Loading...