Sunday, July 21, 2013

Java24h h18-h22 (Java)

1) Exception
(final Exception e)  用不用final的区别在哪?
throws 之后不会constructed
MalformedURLException e 不能throw e, unless throws MalformedURLException (or Exception, ...)
class HomePage and class PageCatalog
import java.net.*;

public class HomePage {
String owner;
URL address;
String category = "none";

public HomePage(String inOwner, String inAddress)
throws MalformedURLException {
// try{
owner = inOwner;
address = new URL(inAddress);
// }
// catch (MalformedURLException e){
// System.out.println("Error: " + e.getMessage());
// }
}

public HomePage(String inOwner, String inAddress, String inCategory) 
throws MalformedURLException {

this(inOwner, inAddress);
category = inCategory;
}
}
import java.net.*;

public class PageCatalog {
public static void main(String[] arguments) throws Exception {
HomePage[] catalog = new HomePage[5];
try {
catalog[0] = new HomePage("Mark Evanier",
"http://www.newsfromme.com", "comic books");
catalog[1] = new HomePage("Todd Smith",
"http://www.sharkbitten.com", "music");
catalog[2] = new HomePage("Rogers Cadenhead",
"http://workbench.cadenhead.org", "programming");
catalog[3] = new HomePage("Juan Cole",
"http://www.juancole.com", "politics");
catalog[4] = new HomePage("Rafe Colburn",
"www.rc3.org");
catch (MalformedURLException e) {
System.out.println("Error: " + e.getMessage() +"\n");
// throw e;
}
try {
for (int i = 0; i < catalog.length; i++) {
System.out.println(catalog[i].owner + ": " +
catalog[i].address + " — " +
catalog[i].category);
}
}
catch (Exception e) {
System.out.println("Error: " + e.getMessage() +"\n");
throw e;
}
}
}
2) Thread
Two ways to place a task in its own thread include:

  • . Putting the task in a class that implements the Runnable interface
  • must include the run()
  • Create an object of the threaded class by calling the Thread constructor
  • Start the thread by calling its start() method
  • . Putting the task in a class that is a subclass of Thread
import java.applet.*;
public class LinkRotator extends JApplet implements Runnable, ActionListener {
public void init() {
URL getURL(String urlText) {
public void paint(Graphics screen) {
public void start() {
public void run() {
public void stop() {
public void actionPerformed(ActionEvent event) {

  • File: File.pathSeparator
.exists(); .getName(); .length(); .createNewFile(); .delete(); .renameTo(File)
  • Folder: .listFiles();
  • I/O
  • FileInputStream
stream.read(); return current single byte or -1
  • BufferedInputStream
  • Properties .load(); .store();
the way to convert an array of bytes into a string: Call the String() constructor method with the array as an argument.
class ID3Reader();
public class ID3Reader {
public class Console {
public static void main(String[] arguments) {
class ConfigWriter {
ConfigWriter() {
void write(FileOutputStream stream, String output) throws IOException {
output = output + newline;
public static void main(String[] arguments) {
class Configurator {
Configurator() {
public static void main(String[] arguments) {
public class PropertyFileCreator {
public static void main(String[] arguments) {

  • Builder .build();
  • Document .getRootElement(); .getFirstChildElement(); .get(int); .getChildElements(); .getValue(); .getAttribute();
public class WeatherStation {
public WeatherStation() throws ParsingException, IOException {
public void display() {
public static void main(String[] arguments) {
public class Aggregator {
public Aggregator(String rssUrl) {
public void listItems() {
public static void main(String[] arguments) {

  • Service Endpoint Interface
  • Service Implementation Bean
  • Publish (String, Objcet)
  • Web Service Description Language(WSDL)
class LinkRotator and LinkRotator.html
package java24h18to24;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;

String[] pageTitle = new String[6];
URL[] pageLink = new URL[6];
Color butterscotch = new Color(255, 204, 158);
int current = 0;
Thread runner;

pageTitle = new String[] {
"Sun’s Java site",
"Cafe au Lait",
"JavaWorld",
"Java in 24 Hours",
"Sams Publishing",
"Workbench"
};
pageLink[0] = getURL("http://java.sun.com");
pageLink[1] = getURL("http://www.ibiblio.org/javafaq");
pageLink[2] = getURL("http://www.javaworld.com");
pageLink[3] = getURL("http://www.java24hours.com");
pageLink[4] = getURL("http://www.samspublishing.com");
pageLink[5] = getURL("http:// workbench.cadenhead.org");
Button goButton = new Button("Go");
goButton.addActionListener(this);
FlowLayout flow = new FlowLayout();
setLayout(flow);
add(goButton);
}

URL pageURL = null;
try {
pageURL = new URL(getDocumentBase(), urlText);

catch (MalformedURLException m) { 

}
return pageURL;
}

Graphics2D screen2D = (Graphics2D) screen;
screen2D.setColor(butterscotch);
screen2D.fillRect(0, 0, getSize().width, getSize().height);
screen2D.setColor(Color.black);
screen2D.drawString(pageTitle[current], 5, 60);
screen2D.drawString("" + pageLink[current], 5, 80);
}

if (runner == null) {
runner = new Thread(this);
runner.start();
}
}

Thread thisThread = Thread.currentThread();
while (runner == thisThread) {
current++;
if (current > 5) {
current = 0;
}
repaint();
try {
Thread.sleep(10000);

catch (InterruptedException e) {
// do nothing
}
}
}

if (runner != null) {
runner = null;
}
}

if (runner != null) {
runner = null;
}
AppletContext browser = getAppletContext();
if (pageLink[current] != null) {
browser.showDocument(pageLink[current]);
}
}
}
<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<body>
<applet 
code=java24h18to24.LinkRotator.class 
codebase=../../bin/ 
width="200" height="200"
>
</applet>
</body>
</html>
3) Files and I/O streams

  • FileInputStream stream.read(); (current single byte or -1) .skip();


  • ButteredInputStream
  • Properties .load(); .store();

import java.io.*;

public static void main(String[] arguments) {
try {
File song = new File(arguments[0]);
FileInputStream file = new FileInputStream(song);
int size = (int) song.length();
file.skip(size - 128);
byte[] last128 = new byte[128];
file.read(last128);
String id3 = new String(last128);
String tag = id3.substring(0, 3);
if (tag.equals("TAG")) {
System.out.println("Title: " + id3.substring(3, 32));
System.out.println("Artist: " + id3.substring(33, 62));
System.out.println("Album: " + id3.substring(63, 91));
System.out.println("Year: " + id3.substring(93, 97));

else {
System.out.println(arguments[0] + " does not contain"
+ " ID3 info.");
}
file.close();

catch (Exception e) {
System.out.println("Error : " + e.toString());
}
}
}
class Console();
import java.io.*;

public static String readLine() {
StringBuffer response = new StringBuffer();
try {
BufferedInputStream bin = new BufferedInputStream(System.in);
int in = 0;
char inChar;
do {
in = bin.read();
inChar = (char) in;
if (in != -1) {
response.append(inChar);
}
} while ((in != -1) & (inChar != '\n'));
bin.close();
return response.toString();

catch (IOException e) {
System.out.println("Exception: " + e.getMessage());
return null;
}
}

System.out.print("You are standing at the end of the road ");
System.out.print("before a small brick building. Around you ");
System.out.print("is a forest. A small stream flows out of ");
System.out.println("the building and down a gully.\n");
System.out.print("> ");
String input = Console.readLine();
System.out.println("That’s not a verb I recognize.");
}
}
class ConfigWriter();
import java.io.*;

String newline = System.getProperty("line.separator"); //system key of '\n'

try {
File file = new File("src/java24h18to24/program.properties");
FileOutputStream fileStream = new FileOutputStream(file);
write(fileStream, "username=max");
write(fileStream, "score=12550");
write(fileStream, "level=5");

catch (IOException ioe) {
System.out.println("Could not write file");
}
}


byte[] data = output.getBytes();
stream.write(data, 0, data.length);
}

ConfigWriter cw = new ConfigWriter();
}
}
class Configurator();
import java.io.*;
import java.util.*;


try {
// load the properties file
File configFile = new File("src/java24h18to24/program.properties");
FileInputStream inStream = new FileInputStream(configFile);
Properties config = new Properties();
config.load(inStream);
// create a new property
Date current = new Date();
config.setProperty("runtime", current.toString());
// save the properties file
FileOutputStream outStream = new FileOutputStream(configFile);
config.store(outStream, "Properties settings");
inStream.close();
config.list(System.out);

catch (IOException ioe) {
System.out.println("IO error " + ioe.getMessage());
}
}

Configurator con = new Configurator();
}
}
class PropertyFileCreator();
import java.io.*;
import java.util.*;

public PropertyFileCreator() {
Properties prop = new Properties();
prop.setProperty("username", "rcade");
prop.setProperty("browser", "Mozilla Firefox");
prop.setProperty("showEmail", "no");
try {
File propFile = new File("src/java24h18to24/properties.xml");
FileOutputStream propStream = new FileOutputStream(propFile);
Date now = new Date();
prop.storeToXML(propStream, "Created on " + now);

catch (IOException exception) {
System.out.println("Error: " + exception.getMessage());
}
}

PropertyFileCreator pfc = new PropertyFileCreator();
}
}
4) XML (Extensible Markup Language)
XOM XML Object Model: a bridge between Java and XML
When warned by "Access restriction: The constructor Builder() is not accessible due to restriction on required library"
Delete the JRE System Libraries. Then import JRE System Libraries again. 

  • Builder .build()


  • Document .getRootElement(); .getFirstChildElement(); .get(int); .getChildElements(); .getValue(); .getAttribute();

class WeatherStation();
import java.io.*;
import nu.xom.*;

int[] highTemp = new int[6];
int[] lowTemp = new int[6];
String[] conditions = new String[6];

// get the XML document
Builder builder = new Builder();
Document doc = builder.build("http://tinyurl.com/rd4r72");
// get the root element, <forecast>
Element root = doc.getRootElement();
// get the <simpleforecast> element
Element simple = root.getFirstChildElement("simpleforecast");
// get the <forecastday> elements
Elements days = simple.getChildElements("forecastday");
for (int current = 0; current < days.size(); current++) {
// get current <forecastday>
Element day = days.get(current);
// get current <high>
Element high = day.getFirstChildElement("high");
Element highF = high.getFirstChildElement("fahrenheit");
// get current <low>26: 
Element low = day.getFirstChildElement("low");
Element lowF = low.getFirstChildElement("fahrenheit");
// get current <icon>
Element icon = day.getFirstChildElement("icon");
// store values in object variables
lowTemp[current] = -1;
highTemp[current] = -1;
try {
lowTemp[current] = Integer.parseInt(lowF.getValue());
highTemp[current] = Integer.parseInt(highF.getValue());

catch (NumberFormatException nfe) {
// do nothing
}
conditions[current] = icon.getValue();
}
}

for (int i = 0; i < conditions.length; i++) {
System.out.println("Period " + i);
System.out.println("\tConditions: " + conditions[i]);
System.out.println("\tHigh: " + highTemp[i]);
System.out.println("\tLow: " + lowTemp[i]);
}
}

try {
WeatherStation station = new WeatherStation();
station.display();

catch (Exception exception) {
System.out.println("Error: " + exception.getMessage());
}
}
}
RSS
class Aggregator();
import java.io.*;
import nu.xom.*;

public String[] title = new String[15];
public String[] link = new String[15];
public int count = 0;

try {
// retrieve the XML document
Builder builder = new Builder();
Document doc = builder.build(rssUrl);
// retrieve the document's root element
Element root = doc.getRootElement();
// retrieve the root’s channel element
Element channel = root.getFirstChildElement("channel");
// retrieve the item elements in the channel
if (channel != null) {
Elements items = channel.getChildElements("item");
for (int current = 0; current < items.size(); current++) {
if (count > 15) {
break;
}
// retrieve the current item
Element item = items.get(current);
Element titleElement = item.getFirstChildElement("title");
Element linkElement = item.getFirstChildElement("link");
title[current] = titleElement.getValue();
link[current] = linkElement.getValue();
count++;
}
}

catch (ParsingException exception) {
System.out.println("XML error: " + exception.getMessage());
exception.printStackTrace();
} catch (IOException ioException) {
System.out.println("IO error: " + ioException.getMessage());
ioException.printStackTrace();
}
}

for (int i = 0; i < 15; i++) {
if (title[i] != null) {
System.out.println("\n" + title[i]);
System.out.println(link[i]);
i++;
}
}
}

if (arguments.length > 0) {
Aggregator aggie = new Aggregator(arguments[0]);
aggie.listItems();

else {
System.out.println("Usage: java Aggregator rssUrl");
}
}
}
5) JAX-WS: Java API for XML web services
Annotations are a smarter form of comments that can be understood by the Java interpreter, compiler, and programming tools. They provide a way to define information about a program that’s not part of the program itself but which can trigger actions when the program is compiled or run. 
@WebMethod @Override
class SquareRootServer();
class SquareRootServerImpl();
class SquareRootServerPublisher();
(SquareRootServer.xml的内容自动生成)
class SquareRootClient();
在SquareRootServerPublisher()运行时,运行SquareRootClient();
package com.rockyniu.ws;

import javax.jws.*;
import javax.jws.soap.*;
import javax.jws.soap.SOAPBinding.*;

@WebService

@SOAPBinding(style = Style.RPC)

public interface SquareRootServer {
// get the square root of a number
@WebMethod double getSquareRoot(double input);

// get the current time and date as a string
@WebMethod String getTime();

}
package com.rockyniu.ws;

import java.util.*;
import javax.jws.*;

@WebService(endpointInterface = "com.rockyniu.ws.SquareRootServer")

public class SquareRootServerImpl implements SquareRootServer {

public double getSquareRoot(double input) {
return Math.sqrt(input);
}
public String getTime() {
Date now = new Date();
return now.toString();
}
}
package com.rockyniu.ws;

import javax.xml.ws.*;

public class SquareRootServerPublisher {
public static void main(String[] arguments) {
SquareRootServerImpl srsi = new SquareRootServerImpl();
Endpoint.publish("http://127.0.0.1:5335/service", srsi);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!— Published by JAX-WS RI at http://jax-ws.dev.java.net. RI's version
is JAX-WS RI 2.2.2 in JDK 7. —>
<!— Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version
is JAX-WS RI 2.2.2 in JDK 7. —>
<definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://ws.rockyniu.com/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.xmlsoap.org/wsdl/"
targetNamespace="http://ws.rockyniu.com/"
name="SquareRootServerImplService">
<types></types>
<message name="getSquareRoot">
<part name="arg0" type="xsd:double"></part>
</message>
<message name="getSquareRootResponse">
<part name="return" type="xsd:double"></part>
</message>
<message name="getTime"></message>
<message name="getTimeResponse">
<part name="return" type="xsd:string"></part>
</message>
<portType name="SquareRootServer">
<operation name="getSquareRoot" parameterOrder="arg0">
<input message="tns:getSquareRoot"></input>
<output message="tns:getSquareRootResponse"></output>
</operation>
<operation name="getTime" parameterOrder="">
<input message="tns:getTime"></input>
<output message="tns:getTimeResponse"></output>
</operation>
</portType>
<binding name="SquareRootServerImplPortBinding"
type="tns:SquareRootServer">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http"
style="rpc"></soap:binding>
<operation name="getSquareRoot">
<soap:operation soapAction=""></soap:operation>
<input>
<soap:body use="literal"
namespace="http://ws.rockyniu.com/"></soap:body>
</input>
<output>
<soap:body use="literal"
namespace="http://ws.rockyniu.com/"></soap:body>
</output>
</operation>
<operation name="getTime">
<soap:operation soapAction=""></soap:operation>
<input>
<soap:body use="literal"
namespace="http://ws.rockyniu.com/"></soap:body>
</input>
<output>
<soap:body use="literal"
namespace="http://ws.rockyniu.com/"></soap:body>
</output>
</operation>
</binding>
<service name="SquareRootServerImplService">
<port name="SquareRootServerImplPort"
binding="tns:SquareRootServerImplPortBinding">
<soap:address location="http://127.0.0.1:5335/service"></soap:address>
</port>
</service>
</definitions>
package com.rockyniu.ws;

import java.net.*;
import javax.xml.namespace.*;
import javax.xml.ws.*;

class SquareRootClient {
public static void main(String[] arguments) throws Exception {
URL url = new URL("http://127.0.0.1:5335/service?wsdl");
QName qname = new QName(
"http://ws.rockyniu.com/",
"SquareRootServerImplService"
);
Service service = Service.create(url, qname);
SquareRootServer srs = service.getPort(SquareRootServer.class);

System.out.println(srs.getTime()); // get the system time
System.out.println(srs.getSquareRoot(625D)); // input
}
}