FileDocCategorySizeDatePackage
SynchronizedPrinter.javaAPI DocExample1900Thu Nov 08 00:23:34 GMT 2001com.ora.rmibook.chapter21.printer.printers

SynchronizedPrinter.java

package com.ora.rmibook.chapter21.printer.printers;


import com.ora.rmibook.chapter21.printer.*;
import java.io.*;
import java.rmi.*;
import java.rmi.server.*;


public class SynchronizedPrinter implements Printer {
    private PrintWriter _log;
    public SynchronizedPrinter(OutputStream log)
        throws RemoteException {
        _log = new PrintWriter(log);
    }

    public synchronized boolean printerAvailable() {
        return true;
    }

    public synchronized boolean printDocument(DocumentDescription documentDescription)
        throws PrinterException {
        if (null == _log) {
            throw new NoLogException();
        }
        if (null == documentDescription) {
            throw new NoDocumentException();
        }
        _log.println("Printed file");
        _log.flush();
        if (_log.checkError()) {
            throw new CantWriteToLogException();
        }
        sleepForRandomAmountOfTime();
        return true;
    }

    private void sleepForRandomAmountOfTime() {
        int time = 1000 + (int) (Math.random() * 100000);

        try {
            Thread.sleep(time);
        } catch (Exception ignored) {
        }
    }

    private class NoLogException extends PrinterException {
        public NoLogException() {
            super (0, "Synchronized printer failure. No log to record print request.");
        }
    }


    private class NoDocumentException extends PrinterException {
        public NoDocumentException() {
            super (0, "Synchronized printer failure. No document received as part of print request.");
        }
    }


    private class CantWriteToLogException extends PrinterException {
        public CantWriteToLogException() {
            super (0, "Synchronized printer failure. Attempt to record print request to log failed");
        }
    }
}