Search in sources :

Example 6 with JposException

use of jpos.JposException in project JavaForFun by gumartinm.

the class JposDriverInstanceFactoryImpl method createInstance.

/**
 * @input_parameters:
 */
@Override
public <E> E createInstance(String logicalName, JposEntry entry, Class<E> typeClass) throws JposException {
    if (entry.getPropertyValue("driverClass") == null) {
        throw new JposException(JposConst.JPOS_E_NOSERVICE, "Missing driverClass JposEntry");
    }
    E driverInstance = null;
    try {
        String serviceClassName = (String) entry.getPropertyValue("driverClass");
        Class<?> serviceClass = Class.forName(serviceClassName);
        Class<?>[] params = new Class<?>[0];
        Constructor<?> ctor = serviceClass.getConstructor(params);
        if (typeClass.isInstance(ctor.newInstance((Object[]) params))) {
            // This cast is correct (IMHO) because we are checking the right type
            // with the method isInstance.
            // Why must I declare this local variable with SuppressWarnings? This is weird...
            @SuppressWarnings("unchecked") E aux = (E) ctor.newInstance((Object[]) params);
            driverInstance = aux;
        }
    } catch (Exception e) {
        throw new JposException(JposConst.JPOS_E_NOSERVICE, "Could not create " + "the driver instance for device with logicalName= " + logicalName, e);
    }
    return driverInstance;
}
Also used : JposException(jpos.JposException) JposException(jpos.JposException)

Example 7 with JposException

use of jpos.JposException in project JavaForFun by gumartinm.

the class MyPOSKeyboard method open.

@Override
public void open(String paramString, EventCallbacks paramEventCallbacks) throws JposException {
    this.logicalname = paramString;
    // La clase EventCallbacks se crea en la clase POSKeyboard, y contiene
    // los objectos listeners generados en nuestro wrapper
    // Esos objectos lo que contienen son punteros a funciones (en Java
    // realmente todo son punteros) conocidas como callbacks
    // 
    // this.dataListener = new DataListener() {
    // @Override
    // public void dataOccurred(final DataEvent dataEvent) {
    // JPosScaleWrapper.this.processDataOccurredOccurred(dataEvent);  <--- Esto es el "puntero" a funcion que será lo que se almacene en la clase EventCallbacs (se almacena el objecto DataListener que implementa la callback o puntero a funcion) ya a nivel Jpos (se introduce en el nivel Jpos algo creado en un nivel superior, es decir, en nuestro Wrapper)
    // }
    // }
    // this.scale.addDataListener(this.dataListener); <-- addDataListener es un método definido en POSKeyboard que introduce el objeto DataListener en un Vector (al introducir ese objecto lo que está haciendo es pasar el callback, en Java lo han hecho así, en C,C++ por ejemplo podría haberse pasado directamente el puntero a función
    // <---- En este objeto dentro del Vector está el objecto DataListener creado en el Wrapper
    this.callbacks = paramEventCallbacks;
    // Podemos extraer los valores de configuracion del jpos.xml o jpos.properties tal como sigue:
    // (Wincord usa la clase OSServiceConfiguration para hacer lo mismo)
    JposServiceManager localJposServiceManager = JposServiceLoader.getManager();
    // Esto contiene todo el jpos.xml o el jpos.properties correctamente ordenado y parseado
    this.jposEntryRegistry = localJposServiceManager.getEntryRegistry();
    // Así podemos obtener toda la configuracion localizada en el jpos.xml o .properties
    // para un determinado dispostivo
    // cuyo nombre pasamos aqui como parametro de entrada.
    // NOTA: Roberto lo que hacia era en la Factoria hacer esto mismo (recuperar
    // el jposEntryRegistry y el jposEntry
    // y pasarselo directamente al constructor. Mi constructor no hace nada
    // (no lo he implementado, al menos todavia)
    // En mi caso el constructor no hace eso y tengo que recuperarlo aquí
    // (keine Ahnung was ist besser)
    this.jposEntry = this.jposEntryRegistry.getJposEntry(paramString);
    // Aqui comienzo a leer toda la posible configuracion para cumplir con un Keyboard POS.
    // Finalmente de este modo podemos ir obteniendo la configuracion de ese
    // dispositivo pasado los campos
    String str = readJposConfiguration(this.jposEntry, this.jposEntryRegistry);
    if (str != null) {
        // En caso de devolver un string, este string es el mensaje de error.
        throw new JposException(JPOS_E_ILLEGAL, str);
    }
    // Recuperamos el codigo Java que lee eventos HW del teclado y los almacena en el
    // DataEvent. Si hubiera que modificar el driver podria hacerse creando un nuevo
    // interfaz que extiende de BaseKeyBoardDriver y aqui deberiamos aniadir algo
    // que hiciera cast al nuevo interfaz que extiende de BaseKeyBoardDriver. De esta forma
    // si hay que aniadir algo al driver no hay que modificar casi nada del codigo.
    // Ademas si queremos cambiar el driver lo unico que hay que hacer es crear una nueva
    // clase que implemente el interfaz BaseKeyBoardDriver y poner el nombre de la clase
    // en el jpos.xml o en el jpos.properties en el campo driverClass que es donde he definido
    // que se ponga el nombre de la clase que implementa el driver. En Wincord era en dcalClass.
    // Por ejemplo yo ahora tendria que aniadir un campos driverClass al jpos.xml de la N2A
    // con la clase de.javapos.example.hardware.KeyBoardDeviceLinux
    // Lo que no me gusta es que la factoria si se cambiara debe hacerse aquí en el codigo :S
    // TODO: poner la factoria tambien como un campo en el jpos.xml y extraerla por reflexión.
    this.jposDriverFactory = new JposDriverInstanceFactoryImpl();
    this.deviceDriver = this.jposDriverFactory.createInstance(paramString, this.jposEntry, BaseKeyBoardDriver.class);
    if (this.deviceDriver == null) {
        throw new JposException(JPOS_E_NOEXIST, "Class: " + this.jposEntry.getPropertyValue("driverClass") + " not found in current class loader.");
    }
    // Crear la cola donde almacenamos eventos estilo FIFO.
    // Esto tambien puede hacerser en jpos.xml y queda todo como un puzle LOL
    // TODO: poner la cola de eventos en el jpos.xml
    this.jposEventQueue = new JposEventQueueImpl();
    // estaria genial poner esto en el jpos.xml y asi puede tambien cambiar el eventlistener
    this.eventListener = new MyPOSKeyBoardEventListener(this.jposEventQueue, this.callbacks);
    this.deviceDriver.addEventListener(eventListener);
// estaria genial poner esto en el jpos.xml y asi puede tambien cambiar el firethread
// Lo malo es que no tengo interfaz para ello :(  Luego nada :/
}
Also used : JposException(jpos.JposException) BaseKeyBoardDriver(de.javapos.example.hardware.BaseKeyBoardDriver) JposServiceManager(jpos.loader.JposServiceManager) JposEventQueueImpl(de.javapos.example.queue.JposEventQueueImpl)

Example 8 with JposException

use of jpos.JposException in project JavaForFun by gumartinm.

the class KeyBoardDeviceLinux method claim.

/**
 * Claim device.
 *
 * <p>
 * <b>Thread-safe</b>
 * </p>
 */
@Override
public synchronized void claim(int time) throws JposException {
    FileLock lock = null;
    FileChannel fileChannelLock = null;
    if (this.isClaimed) {
        return;
    }
    try {
        fileChannelLock = new FileOutputStream(javaposKeyBoardLock).getChannel();
    } catch (FileNotFoundException e) {
        throw new JposException(JposConst.JPOS_E_NOTCLAIMED, "File not found.", e);
    }
    if (time == -1) {
        // :(
        while (true) {
            try {
                if ((lock = fileChannelLock.tryLock()) != null) {
                    break;
                }
                // Release monitor
                this.wait(250);
            // I do not like catching RunTimeExceptions but I have no
            // choice...
            } catch (OverlappingFileLockException e) {
                closeFileLock(fileChannelLock);
                logger.warn("File already locked or more than one instances of the " + "KeyBoardDeviceLinux JavaPOS driver.", e);
                // supported.
                return;
            } catch (IOException e) {
                closeFileLock(fileChannelLock);
                throw new JposException(JposConst.JPOS_E_CLAIMED, "Error while trying to claim device.", e);
            } catch (InterruptedException e) {
                // restore interrupt status.
                Thread.currentThread().interrupt();
                closeFileLock(fileChannelLock);
                throw new JposException(JposConst.JPOSERR, "Interrupt exception detected.", e);
            }
        }
    } else {
        long lastTime = System.nanoTime() + ((time + 250) * 1000000);
        // :(
        do {
            try {
                if ((lock = fileChannelLock.tryLock()) != null) {
                    break;
                }
                // Release monitor
                this.wait(250);
            // I do not like catching RunTimeExceptions but I have no
            // choice...
            } catch (OverlappingFileLockException e) {
                closeFileLock(fileChannelLock);
                logger.warn("File already locked or more than one instances of the " + "KeyBoardDeviceLinux JavaPOS driver.", e);
                // supported.
                return;
            } catch (IOException e) {
                closeFileLock(fileChannelLock);
                throw new JposException(JposConst.JPOS_E_CLAIMED, "Error while trying to claim device.", e);
            } catch (InterruptedException e) {
                // restore interrupt status.
                Thread.currentThread().interrupt();
                closeFileLock(fileChannelLock);
                throw new JposException(JposConst.JPOSERR, "Interrupt exception detected.", e);
            }
        } while (System.nanoTime() <= lastTime);
        if (lock == null) {
            // Time out
            closeFileLock(fileChannelLock);
            throw new JposException(JposConst.JPOS_E_TIMEOUT, "Timeout while trying to claim device.");
        }
    }
    this.lock = lock;
    this.fileChannelLock = fileChannelLock;
    this.isClaimed = true;
}
Also used : JposException(jpos.JposException) FileChannel(java.nio.channels.FileChannel) FileOutputStream(java.io.FileOutputStream) FileLock(java.nio.channels.FileLock) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException)

Example 9 with JposException

use of jpos.JposException in project JavaForFun by gumartinm.

the class KeyBoardDeviceLinux method release.

/**
 * Release device.
 *
 * <p>
 * Thread-safe.
 * </p>
 */
@Override
public synchronized void release() throws JposException {
    if (!this.isClaimed) {
        return;
    }
    try {
        this.lock.release();
        this.fileChannelLock.close();
    } catch (IOException e) {
        throw new JposException(JposConst.JPOSERR, "Error when closing the keyboard file lock", e);
    }
    this.isClaimed = false;
}
Also used : JposException(jpos.JposException) IOException(java.io.IOException)

Example 10 with JposException

use of jpos.JposException in project JavaForFun by gumartinm.

the class KeyBoardDeviceLinux method disable.

@Override
public synchronized void disable() throws JposException {
    if (!this.isEnabled) {
        return;
    }
    // This method releases the Java NIO channel. It is thread safety. :)
    // see: Interruptible
    this.thread.interrupt();
    try {
        this.thread.join();
    } catch (InterruptedException e) {
        // restore interrupt status.
        Thread.currentThread().interrupt();
        throw new JposException(JposConst.JPOSERR, "Interrupt exception detected.", e);
    }
    this.isEnabled = false;
}
Also used : JposException(jpos.JposException)

Aggregations

JposException (jpos.JposException)12 JposServiceInstance (jpos.loader.JposServiceInstance)3 FileNotFoundException (java.io.FileNotFoundException)2 IOException (java.io.IOException)2 Constructor (java.lang.reflect.Constructor)2 Field (java.lang.reflect.Field)2 Iterator (java.util.Iterator)2 JposEntry (jpos.config.JposEntry)2 ImprimeTicketEnvio (ar.com.comit.print.javapos.ImprimeTicketEnvio)1 DialogActionListener (ar.com.ergio.print.fiscal.view.AInfoFiscalPrinter.DialogActionListener)1 BaseKeyBoardDriver (de.javapos.example.hardware.BaseKeyBoardDriver)1 JposEventQueueImpl (de.javapos.example.queue.JposEventQueueImpl)1 Dimension (java.awt.Dimension)1 PointerInfo (java.awt.PointerInfo)1 ActionEvent (java.awt.event.ActionEvent)1 ActionListener (java.awt.event.ActionListener)1 DataInputStream (java.io.DataInputStream)1 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1 FileChannel (java.nio.channels.FileChannel)1