Commit b58442dd authored by O'Reilly Media, Inc.'s avatar O'Reilly Media, Inc.
Browse files

Initial commit

parents
Loading
Loading
Loading
Loading

9781565922068

0 → 120000
+1 −0
Changes for 9781565922068: 1 added line, 0 removed lines.
Original line number Diff line number Diff line
9781565922068
 No newline at end of file
+209 −0
Changes for Appendices/AppWhiteboardUser.java: 209 added lines, 0 removed lines.
Original line number Diff line number Diff line
package dcj.examples.appB;

import dcj.util.Collaborative.*;
import java.awt.event.*;
import java.awt.*;
import java.util.Hashtable;
import java.util.Properties;
import java.io.IOException;
import java.util.Vector;

/**
 * Source code from "Java Distributed Computing", by Jim Farley.
 *
 * Class: AppWhiteboardUser
 * Example: A-1
 * Description: A message-passing collaborator to be used within
 *      an applet context.
 */

class Msg {
  public Object data;
  public String tag;

  public Msg(Object o, String t) {
    data = o;
    tag = t;
  }
}

class CommHelper extends Thread {
  Collaborator collaborator;
  static Vector msgs = new Vector();

  public CommHelper(Collaborator c) {
    collaborator = c;
  }

  public static void addMsg(Object o, String t) {
    synchronized (msgs) {
      msgs.addElement(new Msg(o, t));
    }
  }

  public void run() {
    while (true) {
      try {
        Msg m = null;
        synchronized (msgs) {
          m = (Msg)msgs.elementAt(0);
          msgs.removeElementAt(0);
        }
        collaborator.broadcast(m.tag, m.data);
      }
      catch (Exception e) {}
    }
  }
}

public class AppWhiteboardUser
    extends MessageCollaborator
    implements java.awt.event.MouseListener,
               java.awt.event.MouseMotionListener
{
  protected Hashtable lastPts = new Hashtable();
  protected Component whiteboard;
  protected Image buffer;

  public AppWhiteboardUser(String name, Color color,
                           String host, int port, Container c) {
    super(host, port, name);
    getIdentity().setProperty("color", color);
    buildUI(c);
    CommHelper helper = new CommHelper(this);
    helper.start();
  }

  protected void buildUI(Container cont) {
    if (cont == null)
      cont = new Frame();
    GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    cont.setLayout(gridbag);
    cont.addNotify();
    c.fill = GridBagConstraints.BOTH;
    c.gridwidth = GridBagConstraints.REMAINDER;
    Canvas canvas1 = new java.awt.Canvas();
    canvas1.setSize(240,180);
    canvas1.setBackground(Color.white);
    gridbag.setConstraints(canvas1, c);
    cont.add(canvas1);
    String name = null;
    try {
      name = getIdentity().getName();
    }
    catch (Exception e) {
      name = "unknown";
    }
    Label label1 = new java.awt.Label("Your name: " + name);
    label1.setSize(100,30);
    gridbag.setConstraints(label1, c);
    cont.add(label1);
    cont.setSize(240,210);
    cont.setVisible(true);
    whiteboard = canvas1;
    whiteboard.addMouseListener(this);
    whiteboard.addMouseMotionListener(this);
    buffer = whiteboard.createImage(cont.getSize().width,
                                    cont.getSize().height);
  }

  protected void nextLine(String agent, Point pt, Color c) {
    Graphics g = buffer.getGraphics();
    g.setColor(c);
    Point lastPt = (Point)lastPts.get(agent);
    g.drawLine(lastPt.x, lastPt.y, pt.x, pt.y);
    whiteboard.getGraphics().drawImage(buffer, 0, 0, whiteboard);
  }

  public void mousePressed(MouseEvent ev) {
    //System.out.println("Got mouse pressed");
    Point evPt = ev.getPoint();
    try {
      lastPts.put(getIdentity().getName(), evPt);
      CommHelper.addMsg(evPt, "start");
    }
    catch (Exception e) {}
  }

  public void mouseReleased(MouseEvent ev) {
    Point evPt = ev.getPoint();
    try {
      nextLine(getIdentity().getName(), evPt,
               (Color)getIdentity().getProperty("color"));
      lastPts.remove(getIdentity().getName());

      CommHelper.addMsg(evPt, "end");
    }
    catch (Exception e) {}
  }

  public void mouseDragged(MouseEvent ev) {
    //System.out.println("Got mouse drag");
    Point evPt = ev.getPoint();
    try {
      nextLine(getIdentity().getName(), evPt,
               (Color)getIdentity().getProperty("color"));
      lastPts.put(getIdentity().getName(), evPt);

      CommHelper.addMsg(evPt, "drag");
    }
    catch (Exception e) {
      //System.out.println("exception");
    }
    //System.out.println("Finished drag.");
  }

  public void mouseExited(MouseEvent ev) {}
  public void mouseMoved(MouseEvent ev) {}
  public void mouseClicked(MouseEvent ev) {}
  public void mouseEntered(MouseEvent ev) {}

  public boolean notify(String tag, Object data, Identity src)
      throws IOException {

    if (src.getName().compareTo(getIdentity().getName()) == 0) {
      return true;
    }
    //System.out.println("Got notified");
    Color origColor = null;
    Color agentColor = null;
    Graphics gr = buffer.getGraphics();
    try {
      agentColor = (Color)src.getProperty("color");
      if (agentColor != null) {
        //System.out.println("src color = " + agentColor.getRed()
          //                 + " " + agentColor.getGreen() + " "
            //               + agentColor.getBlue());
        gr.setColor(agentColor);
      }
      else {
        System.out.println("No agent color available.");
      }
    }
    catch (Exception exc) {
      System.out.println("Exception while switching colors.");
      exc.printStackTrace();
    }

    if (tag.compareTo("start") == 0) {
      lastPts.put(src.getName(), data);
    }
    else if (tag.compareTo("drag") == 0) {
      Point lastPt = (Point)lastPts.get(src.getName());
      Point currPt = (Point)data;
      gr.drawLine(lastPt.x, lastPt.y, currPt.x, currPt.y);
      lastPts.put(src.getName(), data);
    }
    else if (tag.compareTo("end") == 0) {
      Point lastPt = (Point)lastPts.get(src.getName());
      Point currPt = (Point)data;
      gr.drawLine(lastPt.x, lastPt.y, currPt.x, currPt.y);
      lastPts.remove(src.getName());
    }

    whiteboard.getGraphics().drawImage(buffer, 0, 0, whiteboard);

    return true;
  }
}
+16 −0
Changes for Appendices/WhiteboardApplet.java: 16 added lines, 0 removed lines.
Original line number Diff line number Diff line
package dcj.examples.appB;

import java.applet.*;
import java.awt.Color;
import dcj.examples.Collaborative.*;

public class WhiteboardApplet extends Applet {
  private MsgWhiteboardUser wbUser;

  public WhiteboardApplet() {}

  public void init() {
    wbUser = new MsgWhiteboardUser("Fred", new Color(255, 0, 0),
                                   "localhost", 5009);
  }
}
 No newline at end of file
+95 −0
Changes for Bandwidth Limited/AudioProducer.java: 95 added lines, 0 removed lines.
Original line number Diff line number Diff line
package dcj.examples.Bandwidth;

import dcj.util.Bandwidth.*;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Source code from "Java Distributed Computing", by Jim Farley.
 *
 * Class: AudioProducer
 * Example: 8-6
 * Description: A producer of audio content.
 * NOTE: This file contains incomplete example code only, which will
 *       not compile without additions and modifications.
 */

public abstract class AudioProducer extends ContentProducer
{
  byte[] buffer = null;
  long maxBuffer = 0;
  long sampleRate;

  // Buffer operations...
  abstract protected void appendToBuffer(byte[] data);
  abstract protected byte[] removeFromBuffer(long size);

  // Method for computing new buffer size based on input
  // data rate, our production rate, and the audio sample rate
  abstract protected void resizeBuffer(float inRate, float outRate,
                                       long audioRate);

  // Method that decodes a given chunk of compressed data into
  // audio samples.
  abstract protected byte[] decode(byte[] cData);

  public boolean produceAll() {
    long bytesPerLoop = 512;
    if (buffer == null) {
      int maxLoop = 10;
      for (int loop = 0; loop < maxLoop; loop++) {
        byte[] data = produce(bytesPerLoop);
        appendToBuffer(data);
      }

      // Assuming we know the rate that data is required by the
      // AudioConsumer (i.e. the sample rate of the audio), then
      // estimate the buffer size needed for continuous playback
      resizeBuffer(source.getAverageRate(), monitor.getAverageRate(),
                   sampleRate);
    }

    boolean success = false;
    if (dest != null) {
      byte[] data = produce(bytesPerLoop);
      while (data != null) {
        success = dest.consume(data);

        // Re-estimate buffer size
        resizeBuffer(source.getLastRate(), monitor.getLastRate(),
                     sampleRate);
        if (success)
          data = produce(bytesPerLoop);
        else
          data = null;
      }
    }

    return success;
  }

  protected byte[] doProduction(long limit) {
    byte[] sData = null;

    // Ask our source for compressed data, and decode it.
    if (source != null) {
      sData = source.produce(limit);
    }
    byte[] audioData = decode(sData);

    // If our buffer is not full, add the new data to it
    if (buffer.length < maxBuffer) {
      appendToBuffer(audioData);
    }

    // If our buffer is now full, then return the requested
    // amount of data, else return nothing.
    if (buffer.length > maxBuffer) {
      audioData = removeFromBuffer(limit);
    }
    else
      audioData = null;

    return audioData;
  }
}
 No newline at end of file
+88 −0
Changes for Bandwidth Limited/ContentConsumer.java: 88 added lines, 0 removed lines.
Original line number Diff line number Diff line
package dcj.util.Bandwidth;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

/**
 * Source code from "Java Distributed Computing", by Jim Farley.
 *
 * Example: 8-4  ContentConsumer
 * Description: A consumer of content streaming into an application.
 */

public class ContentConsumer
{
  protected ContentProducer source = null;
  protected ContentConsumer dest = null;
  protected DataMonitor     monitor = new DataMonitor();

  public ContentConsumer(ContentProducer src) {
    source = src;
  }

  public ContentConsumer(ContentConsumer dst) {
    dest = dst;
  }

  public void setSource(ContentProducer p) {
    source = p;
  }

  public void setDest(ContentConsumer c) {
    dest = c;
  }

  // Consume data from our producer until it is exhausted.
  public boolean consumeAll() {
    boolean success = false;
    if (source != null) {
      byte[] data = source.produce(0);
      while (data != null) {
        success = consume(data);
        data = source.produce(0);
      }
    }

    return success;
  }

  // Consume a chunk of data
  public boolean consume(byte[] data) {
    // Log the start of the consumption cycle.
    Date start = new Date();

    boolean success;
    success = preConsume(data);
    if (success)
      success = doConsume(data);
    if (success)
      success = postConsume(data);

    // Mark the end of our consumption cycle
    monitor.addSample(data.length, start, new Date());

    // Pass the data on to the next consumer in the chain,
    // if present.
    if (dest != null) {
      dest.consume(data);
    }

    return success;
  }

  protected boolean preConsume(byte[] data) {
    return true;
  }

  // Default consumption procedure.
  protected boolean doConsume(byte[] data) {
    return true;
  }

  // Default post-consumption procedure: log the data consumption
  // size and finish time with our monitor.
  protected boolean postConsume(byte[] data) {
    return true;
  }
}
 No newline at end of file
Loading