Dot matrix printer problem (/dev/parport)

Dear experts:

I have a problem with a dot matrix printer. Im in a Linux/Java App project thats prints tickets to it.
But i cant print on it. I dont know why. On Windows it works fine, but the javax.comm for windows is obviously different.
Can anyone help me?

Heres a log of what happens...


Starting printing test...
On Printer 3 :/dev/parport0
SerialDriver(port) Method
DefaultPort: /dev/parport0
Open Method
Trying to open port with Javax...
Opened the port Successfully with Javax!!
Obtaining the OutputStream...
OutputStream OK
Linux: /dev/parport0 opened succesfully
Creating StringBuffer...
Appending text
    +------------------------------+
    |          Tienda PRO          |
   +------------------------------+

        Print Test Successful













Converting to Bytes while replacing nulls
[B@dc024a
Opening FileOutputStream
Writing to printer
Couldnt send data to port due to :

java.io.IOException: Invalid argument
      at java.io.FileOutputStream.writeBytes(Native Method)
      at java.io.FileOutputStream.write(FileOutputStream.java:247)
      at com.storecheck.detailconnect.utils.TicketPrinter.printLPT(TicketPrinter.java:362)
      at com.storecheck.detailconnect.ui.panels.SettingsPanel.btnProbarActionPerformed(SettingsPanel.java:1447)
      at com.storecheck.detailconnect.ui.panels.SettingsPanel.access$3100(SettingsPanel.java:45)
      at com.storecheck.detailconnect.ui.panels.SettingsPanel$19.actionPerformed(SettingsPanel.java:854)
      at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
      at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
      at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
      at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
      at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:234)
      at java.awt.Component.processMouseEvent(Component.java:5488)
      at javax.swing.JComponent.processMouseEvent(JComponent.java:3093)
      at java.awt.Component.processEvent(Component.java:5253)
      at java.awt.Container.processEvent(Container.java:1966)
      at java.awt.Component.dispatchEventImpl(Component.java:3955)
      at java.awt.Container.dispatchEventImpl(Container.java:2024)
      at java.awt.Component.dispatchEvent(Component.java:3803)
      at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
      at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
      at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
      at java.awt.Container.dispatchEventImpl(Container.java:2010)
      at java.awt.Window.dispatchEventImpl(Window.java:1774)
      at java.awt.Component.dispatchEvent(Component.java:3803)
      at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
      at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
      at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
      at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)

Closing outputStream...
outputStream Closed Succesfully. Printing finished succesfully



and my code that prints is this:



    public static boolean printLPT(String datos[]) throws java.lang.NullPointerException {
        FileOutputStream outputStream = null;
        try {
            String OS = System.getProperty("os.name").toString();
            String defaultPort = SmartClientSettings.getInstance().getSerialPort();
           
            if (!OS.startsWith("Windows")){
                SerialDriver serial = new SerialDriver(defaultPort);

                if(!serial.open()){
                    logger.info("Couldnt open the parallel port!");
                    return false;
                }
            }
           
            logger.info(OS + ": " + defaultPort + " opened succesfully");
            logger.info("Creating StringBuffer...");
            StringBuffer yourText = new StringBuffer();
            logger.info("Appending text");
            for(int i=0; i < datos.length; i++){
                    yourText.append(datos[i]);
            }
            logger.info(yourText);
            logger.info("Converting to Bytes while replacing nulls");
            byte[] bytes = yourText.toString().replace("null","").getBytes();
            logger.info(bytes);
           
       
            logger.info("Opening FileOutputStream");
            outputStream = new FileOutputStream(defaultPort);
            logger.info("Writing to printer");
            outputStream.write(bytes);
           
        } catch (FileNotFoundException fileNotFoundException) {
            logger.error("Could not find the port file : ",fileNotFoundException);
            return false;
        } catch (IOException ioException) {
            logger.error("Couldnt send data to port due to : ",ioException);
            return false;
        }catch (Exception Exception) {
            logger.error("Error while printing to parallel printer port : ",Exception);
            return false;
        }finally{
           
            try{
                logger.info("Closing outputStream...");
                outputStream.close();
                logger.info("outputStream Closed Succesfully. Printing finished succesfully");
                return true;
            } catch (FileNotFoundException fileNotFoundException) {
                logger.error("Could not find the port file : ",fileNotFoundException);
                return false;
            } catch (IOException ioException) {
                logger.error("Couldnt send data to port due to : ",ioException);
                return false;
            }
           
        }
    }



    public synchronized boolean open(){
        boolean abierto=true;
        logger.info("Open Method");
        while (portList.hasMoreElements()) {
            logger.info("Found 1 port");
            portId = (CommPortIdentifier) portList.nextElement();

            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                logger.info("and its Serial");
                if (portId.getName().equals(defaultPort)) {

                    logger.info("This is the preferred port ");
                    portFound = true;

                    try {
                        logger.info("Trying to open port with Javax...");
                        serialPort = (SerialPort) portId.open("SimpleWrite", 2000);
                        logger.info("Opened the port Successfully with Javax!!");
                    } catch (Exception e) {

                        logger.error("Couldnt open port with javax", e);
                        JOptionPane.showMessageDialog(null,"Couldnt open the printer port!!","E00156",2);
                        abierto=false;
                        continue;
                    }
                    logger.info("Obtaining OutputStream...");
                    try {
                        outputStream = serialPort.getOutputStream();
                        logger.info("OutputStream OK");
                    } catch (IOException e) {
                        logger.error("Error getting OutputStream port",e);
                        abierto=false;
                    }

                    //try {

                         int impresora = Integer.parseInt(SmartClientSettings.getInstance().getSelectedPrinter());
                         logger.info("Setting Serial parameters");
                         if (impresora == 0){
                            //serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
                         }else if(impresora == 1){
                            //serialPort.setSerialPortParams(19200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
                         }
                        logger.info("Done setting SerialPort Params");
                    //} catch (UnsupportedCommOperationException e) {
                     //   logger.error("Error setting port parameters", e);
                      //  abierto=false;
                    //}


                    try {
                        serialPort.notifyOnOutputEmpty(true);
                    } catch (Exception e) {
                        logger.error("Error on notifyOnOutputEmpty",e);
                        abierto=false;
                    }

                }
            }else{   //LPT1
                logger.info("and its Parallel");
                if (portId.getName().equals(defaultPort)) {

                    logger.info("This is the preferred port");
                    portFound = true;

                    try {
                        logger.info("Trying to open port with Javax...");
                        parallelPort = (ParallelPort) portId.open("SimpleWrite", 2000);
                        logger.info("Opened the port Successfully with Javax!!");

                    }catch (javax.comm.PortInUseException ex1){
                        logger.error("Used Port Exception: " + portId.isCurrentlyOwned(), ex1 );

                    } catch (Exception e) {

                        logger.error("Couldnt open port with javax", e);
                        abierto=false;
                        continue;
                    }
                    logger.info("Obtaining the OutputStream...");
                    try {
                        outputStream = parallelPort.getOutputStream();
                         logger.info("OutputStream OK");
                    } catch (IOException e) {
                        logger.error("Error getting OutputStream port", e);
                        abierto=false;
                    }


                    try {
                        if (parallelPort.isPaperOut()){
                            Toolkit.getDefaultToolkit().beep();
                        }
                    } catch (Exception e) {
                        logger.error("Error on notifyOnOutputEmpty",e);
                        abierto=false;
                    }

                }


            }
        }

        if (!portFound) {
            abierto=false;
        }

        return abierto;
    }




Can anyone help me?

Nemo
memozebaduaAsked:
Who is Participating?
 
Mayank SAssociate Director - Product EngineeringCommented:
>> The other lines (CommPortIdentifier portIdentifier = ....  and CommPort port = portIdentifier.open ( "Your application ... )  are indeed used...

Yeah noticed. Maybe try calling the input stream too, before calling the output stream.
0
 
ADSLMarkCommented:
This looks weird:

byte[] bytes = yourText.toString().replace("null","").getBytes();

you replace "null" inside a string with "".. so for example

"abcnulldef" becomes "abcdef".

I think you meant to write:

String myText = yourText.toString();
if(myText == null)
  myText = "<nothing>";

byte[] bytes = myText.getBytes();

Mark
0
 
memozebaduaAuthor Commented:
Hey Mark!   :)

Mmm i did that because i was trying to avoid null in a string. The string is indeed this:


    +------------------------------+
    |          Tienda PRO          |
   +------------------------------+

        Print Test Successful





(with the blank lines)
So basically, the string is this:     +------------------------------+\n   |          Tienda PRO         \n |   +------------------------------+\n .... and so on.
But at the end of the string, it always sent a null because my String array is sometimes larger or shorter and i cant define it as a single number like 11, so sometimes it just sends a null when there was no more data but the for was still spinning.
So i just decided to replace nulls to "".




But now i changed a little bit my code, to correct it as you told me:



for(int i=0; i < datos.length; i++){
        if (datos[i] != null){                                             <--- ADDED THIS NULL CHECK
            yourText.append(datos[i]);
        }
}
logger.info(yourText);
logger.info("Converting to Bytes while replacing nulls");
byte[] bytes = yourText.toString().getBytes();             <--- ERASED THAT NULL CHCK
logger.info(bytes);



But, now i have another problem, as you can see below:


SerialDriver Constructor
PortID OK... Jumping to the other Constructor method...
SerialDriver(port) Method
DefaultPort: /dev/parport0
Open Method
This is the preferred port
Trying to open port with Javax...
Opened the port Successfully with Javax!!
Obtaining the OutputStream...
Error while printing to parallel printer port :
java.lang.IllegalStateException: This port has not been opened yet
      at com.sun.comm.LinuxParallel.getOutputStream(LinuxParallel.java:320)
      at com.storecheck.detailconnect.utils.SerialDriver.open(SerialDriver.java:167)
      at com.storecheck.detailconnect.utils.TicketPrinter.printLPT(TicketPrinter.java:340)
      at com.storecheck.detailconnect.ui.panels.SettingsPanel.btnProbarActionPerformed(SettingsPanel.java:1447)
      at com.storecheck.detailconnect.ui.panels.SettingsPanel.access$3100(SettingsPanel.java:45)
      at com.storecheck.detailconnect.ui.panels.SettingsPanel$19.actionPerformed(SettingsPanel.java:854)
      at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
      at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
      at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
      at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
      at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:234)
      at java.awt.Component.processMouseEvent(Component.java:5488)
      at javax.swing.JComponent.processMouseEvent(JComponent.java:3093)
      at java.awt.Component.processEvent(Component.java:5253)
      at java.awt.Container.processEvent(Container.java:1966)
      at java.awt.Component.dispatchEventImpl(Component.java:3955)
      at java.awt.Container.dispatchEventImpl(Container.java:2024)
      at java.awt.Component.dispatchEvent(Component.java:3803)
      at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
      at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
      at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
      at java.awt.Container.dispatchEventImpl(Container.java:2010)
      at java.awt.Window.dispatchEventImpl(Window.java:1774)
      at java.awt.Component.dispatchEvent(Component.java:3803)
      at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
      at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
      at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
      at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
Closing outputStream...



Any ideas?

Thanks  :)

Nemo
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
ADSLMarkCommented:
This seems incorrect:

String defaultPort = SmartClientSettings.getInstance().getSerialPort();
outputStream = new FileOutputStream(defaultPort);
outputStream.write(bytes);

I'm not sure if you can create a fileoutputstream from that "defaultPort" thingie. Could you show how you connect to your serial port, open the connection and generate input/outputstreams from that connection?

Mark
0
 
memozebaduaAuthor Commented:
:)

This line:
String defaultPort = SmartClientSettings.getInstance().getSerialPort();

brings this result:
/dev/parport0
only. It looks for the actual selected port for my application only.

The other question you made is "how you connect to your serial port and how you generate input/outputstreams from that connection?".

This code shows:

    private Enumeration portList;
    private CommPortIdentifier portId;
   
    private ParallelPort parallelPort;
    private SerialPort serialPort;
   
    private OutputStream outputStream = null;
    private boolean outputBufferEmptyFlag = false;
   
    private boolean portFound = false;
    private String defaultPort;
    String OS = System.getProperty("os.name").toString();

    public SerialDriver(String puerto) {
        this();
        logger.info("SerialDriver(port) Method");
        defaultPort = puerto;
        logger.info("DefaultPort: " + defaultPort);
       
    }
   
    public SerialDriver(){
        logger.info("SerialDriver Constructor");
        portList = CommPortIdentifier.getPortIdentifiers();
        logger.info("PortID OK... Jumping to the other Constructor method...");
    }
   
    public String[] portList(){
        logger.info("portList Method");
        CommPortIdentifier puerto;
        int cuenta=0;
        logger.info("Finding ports ...");
        Enumeration puertos = CommPortIdentifier.getPortIdentifiers();
       
        String sPuertos="";
        while (puertos.hasMoreElements()) {
            logger.info("Found 1 port");
            cuenta++;
            puerto = (CommPortIdentifier) puertos.nextElement();
           
            //if(puerto.getPortType() == CommPortIdentifier.PORT_SERIAL)
                sPuertos += puerto.getName() + ":";
        }
        logger.info("Found " + cuenta + " ports in this computer");
        if(sPuertos.endsWith(":") && sPuertos.length()>1)
            sPuertos = sPuertos.substring(0, sPuertos.length()-1);
        logger.info("AllPorts list: " + sPuertos);
        String resultado[] = sPuertos.split(":");
        logger.info("portList Method ends.");
        return resultado;
    }

public synchronized boolean open(){
        boolean abierto=true;
        logger.info("Open Method");
        while (portList.hasMoreElements()) {
            logger.info("Found 1 port");
            portId = (CommPortIdentifier) portList.nextElement();

            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                logger.info("and its Serial");
                if (portId.getName().equals(defaultPort)) {

                    logger.info("This is the preferred port ");
                    portFound = true;

                    try {
                        logger.info("Trying to open port with Javax...");
                        serialPort = (SerialPort) portId.open("SimpleWrite", 2000);
                        logger.info("Opened the port Successfully with Javax!!");
                    } catch (Exception e) {

                        logger.error("Couldnt open port with javax", e);
                        JOptionPane.showMessageDialog(null,"Couldnt open the printer port!!","E00156",2);
                        abierto=false;
                        continue;
                    }
                    logger.info("Obtaining OutputStream...");
                    try {
                        outputStream = serialPort.getOutputStream();
                        logger.info("OutputStream OK");
                    } catch (IOException e) {
                        logger.error("Error getting OutputStream port",e);
                        abierto=false;
                    }

                    //try {

                         int impresora = Integer.parseInt(SmartClientSettings.getInstance().getSelectedPrinter());
                         logger.info("Setting Serial parameters");
                         if (impresora == 0){
                            //serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
                         }else if(impresora == 1){
                            //serialPort.setSerialPortParams(19200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
                         }
                        logger.info("Done setting SerialPort Params");
                    //} catch (UnsupportedCommOperationException e) {
                     //   logger.error("Error setting port parameters", e);
                      //  abierto=false;
                    //}


                    try {
                        serialPort.notifyOnOutputEmpty(true);
                    } catch (Exception e) {
                        logger.error("Error on notifyOnOutputEmpty",e);
                        abierto=false;
                    }

                }
            }else{   //LPT1
                logger.info("and its Parallel");
                if (portId.getName().equals(defaultPort)) {

                    logger.info("This is the preferred port");
                    portFound = true;

                    try {
                        logger.info("Trying to open port with Javax...");
                        parallelPort = (ParallelPort) portId.open("SimpleWrite", 2000);
                        logger.info("Opened the port Successfully with Javax!!");

                    }catch (javax.comm.PortInUseException ex1){
                        logger.error("Used Port Exception: " + portId.isCurrentlyOwned(), ex1 );

                    } catch (Exception e) {

                        logger.error("Couldnt open port with javax", e);
                        abierto=false;
                        continue;
                    }
                    logger.info("Obtaining the OutputStream...");
                    try {
                        outputStream = parallelPort.getOutputStream();
                         logger.info("OutputStream OK");
                    } catch (IOException e) {
                        logger.error("Error getting OutputStream port", e);
                        abierto=false;
                    }


                    try {
                        if (parallelPort.isPaperOut()){
                            Toolkit.getDefaultToolkit().beep();
                        }
                    } catch (Exception e) {
                        logger.error("Error on notifyOnOutputEmpty",e);
                        abierto=false;
                    }

                }


            }
        }

        if (!portFound) {
            abierto=false;
        }

        return abierto;
    }





And with this I send things to the printer:




 public static boolean printLPT(String datos[]) throws java.lang.NullPointerException {
        FileOutputStream outputStream = null;
        try {
            String OS = System.getProperty("os.name").toString();
            String defaultPort = SmartClientSettings.getInstance().getSerialPort();
           
            if (!OS.startsWith("Windows")){
                SerialDriver serial = new SerialDriver(defaultPort);

                if(!serial.open()){
                    logger.info("Couldnt open the parallel port!");
                    return false;
                }
            }
           
            logger.info(OS + ": " + defaultPort + " opened succesfully");
            logger.info("Creating StringBuffer...");
            StringBuffer yourText = new StringBuffer();
            logger.info("Appending text");
            for(int i=0; i < datos.length; i++){
                    if (datos[i] != null){
                        yourText.append(datos[i]);
                    }
            }
            logger.info(yourText);
            logger.info("Converting to Bytes while replacing nulls");
            byte[] bytes = yourText.toString().getBytes();
            logger.info(bytes);
           
            logger.info("Opening FileOutputStream");
            outputStream = new FileOutputStream(defaultPort);
            logger.info("Writing to printer");
            outputStream.write(bytes);
           
        } catch (FileNotFoundException fileNotFoundException) {
            logger.error("Could not find the port file : ",fileNotFoundException);
            return false;
        } catch (IOException ioException) {
            logger.error("Couldnt send data to port due to : ",ioException);
            return false;
        }catch (Exception Exception) {
            logger.error("Error while printing to parallel printer port : ",Exception);
            return false;
        }finally{
           
            try{
                logger.info("Closing outputStream...");
                outputStream.close();
                logger.info("outputStream Closed Succesfully. Printing finished succesfully");
                return true;
            } catch (FileNotFoundException fileNotFoundException) {
                logger.error("Could not find the port file : ",fileNotFoundException);
                return false;
            } catch (IOException ioException) {
                logger.error("Couldnt send data to port due to : ",ioException);
                return false;
            }
           
        }
    }

0
 
ADSLMarkCommented:
Ok, I think you have to do something like:

String defaultPort = SmartClientSettings.getInstance().getSerialPort();
SerialDriver serial = new SerialDriver(defaultPort);
if(!serial.open())
{
    logger.info("Couldnt open the parallel port!");
    return false;
}
OutputStream out = serial.getOutputStream();
out.write(...)

Now the serial port is constructed, but never used again. So I think you should first get the port.. create a serial driver and then get the outputstream from this serial driver. The serialdriver class still needs a get-method to get the outputstream, simply:

public OutputStream getOutputStream()
{
    return this.outputStream;
}

Mark
0
 
memozebaduaAuthor Commented:
Mmm it didnt work... same exception:



SerialDriver Constructor
PortID OK... Jumping to the other Constructor method...
SerialDriver(port) Method
DefaultPort: /dev/parport0
Open Method
This is the preferred port
Trying to open port with Javax...
Opened the port Successfully with Javax!!
Obtaining the OutputStream...
Error while printing to parallel printer port :
java.lang.IllegalStateException: This port has not been opened yet
      at com.sun.comm.LinuxParallel.getOutputStream(LinuxParallel.java:320)
      at com.storecheck.detailconnect.utils.SerialDriver.open(SerialDriver.java:167)
      at com.storecheck.detailconnect.utils.TicketPrinter.printLPT(TicketPrinter.java:340)
      at com.storecheck.detailconnect.ui.panels.SettingsPanel.btnProbarActionPerformed(SettingsPanel.java:1447)
      at com.storecheck.detailconnect.ui.panels.SettingsPanel.access$3100(SettingsPanel.java:45)
      at com.storecheck.detailconnect.ui.panels.SettingsPanel$19.actionPerformed(SettingsPanel.java:854)
      at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
      at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
      at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
      at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
      at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:234)
      at java.awt.Component.processMouseEvent(Component.java:5488)
      at javax.swing.JComponent.processMouseEvent(JComponent.java:3093)
      at java.awt.Component.processEvent(Component.java:5253)
      at java.awt.Container.processEvent(Container.java:1966)
      at java.awt.Component.dispatchEventImpl(Component.java:3955)
      at java.awt.Container.dispatchEventImpl(Container.java:2024)
      at java.awt.Component.dispatchEvent(Component.java:3803)
      at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
      at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
      at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
      at java.awt.Container.dispatchEventImpl(Container.java:2010)
      at java.awt.Window.dispatchEventImpl(Window.java:1774)
      at java.awt.Component.dispatchEvent(Component.java:3803)
      at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
      at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
      at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
      at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
Closing outputStream...




Here's the new code:



    public static boolean printLPT(String datos[]) throws java.lang.NullPointerException {
        OutputStream outputStream = null;
        try {
            String OS = System.getProperty("os.name").toString();
            String defaultPort = SmartClientSettings.getInstance().getSerialPort();
            SerialDriver serial = null;
            if (!OS.startsWith("Windows")){
                 serial = new SerialDriver(defaultPort);

                if(!serial.open()){
                    logger.info("Couldnt open the parallel port!");
                    return false;
                }
            }
           
            logger.info(OS + ": " + defaultPort + " opened succesfully");
            logger.info("Creating StringBuffer...");
            StringBuffer yourText = new StringBuffer();
            logger.info("Appending text");
            for(int i=0; i < datos.length; i++){
                    if (datos[i] != null){
                        yourText.append(datos[i]);
                    }
            }
            logger.info(yourText);
            logger.info("Converting to Bytes while replacing nulls");
            byte[] bytes = yourText.toString().getBytes();
            logger.info(bytes);
            logger.info("Opening FileOutputStream");
            outputStream = serial.getOutputStream();
            logger.info("Writing to printer");
            outputStream.write(bytes);
           
        } catch (FileNotFoundException fileNotFoundException) {
            logger.error("Could not find the port file : ",fileNotFoundException);
            return false;
        } catch (IOException ioException) {
            logger.error("Couldnt send data to port due to : ",ioException);
            return false;
        }catch (Exception Exception) {
            logger.error("Error while printing to parallel printer port : ",Exception);
            return false;
        }finally{
           
            try{
                logger.info("Closing outputStream...");
                outputStream.close();
                logger.info("outputStream Closed Succesfully. Printing finished succesfully");
                return true;
            } catch (FileNotFoundException fileNotFoundException) {
                logger.error("Could not find the port file : ",fileNotFoundException);
                return false;
            } catch (IOException ioException) {
                logger.error("Couldnt send data to port due to : ",ioException);
                return false;
            }
           
        }
    }


and in SerialDriver class:


    public synchronized OutputStream getOutputStream()
    {
            return this.getOutputStream();
    }



... Any other ideas?    :S

I'm trying a new approach meanwhile  :)


Thanks :)
0
 
ADSLMarkCommented:
I wonder why i do not see "Found 1 port" in your log, since in the serial.open(), there is this line:

while (portList.hasMoreElements()) {
            logger.info("Found 1 port");
            portId = (CommPortIdentifier) portList.nextElement();

but if portList does not contain any ports, then where are we writing to?
Could you check that it really does create the outputstream in the serial.open()?
It's difficult to give advice without being able to insert some debug statements, so I'm trying my best by analyzing, sorry for the inconvenience.

Mark
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Tried:

CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier ( "COM1" ) ; // or whatever port name
CommPort port = portIdentifier.open ( "Your application name", 500 ) ; // app name and time out
InputStream is = port.getInputStream () ;
OutputStream os = port.getOutputStream () ;

?
0
 
memozebaduaAuthor Commented:
Dont worry Mark, i know you are really trying and i am too.

Sorry, i delete that lines of the log because it was already too long, but i post the entire one if you want...


portList Method
Finding ports ...
Found 1 port
Found 1 port
Found 1 port
Found 3 ports in this computer
AllPorts list: /dev/ttyS0:/dev/ttyS1:/dev/parport0
SerialDriver Constructor
PortID OK... Jumping to the other Constructor method...
SerialDriver(port) Method
DefaultPort: /dev/parport0
Open Method
Found 1 port
and its Serial
Found 1 port
and its Serial
Found 1 port
and its Parallel
This is the preferred port
Trying to open port with Javax...
Opened the port Successfully with Javax!!
Obtaining the OutputStream...
Error while printing to parallel printer port :
java.lang.IllegalStateException: This port has not been opened yet
      at com.sun.comm.LinuxParallel.getOutputStream(LinuxParallel.java:320)
      at com.storecheck.detailconnect.utils.SerialDriver.open(SerialDriver.java:167)
      at com.storecheck.detailconnect.utils.TicketPrinter.printLPT(TicketPrinter.java:340)
      at com.storecheck.detailconnect.ui.panels.SettingsPanel.btnProbarActionPerformed(SettingsPanel.java:1447)
      at com.storecheck.detailconnect.ui.panels.SettingsPanel.access$3100(SettingsPanel.java:45)
      at com.storecheck.detailconnect.ui.panels.SettingsPanel$19.actionPerformed(SettingsPanel.java:854)
      at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
      at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
      at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
      at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
      at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:234)
      at java.awt.Component.processMouseEvent(Component.java:5488)
      at javax.swing.JComponent.processMouseEvent(JComponent.java:3093)
      at java.awt.Component.processEvent(Component.java:5253)
      at java.awt.Container.processEvent(Container.java:1966)
      at java.awt.Component.dispatchEventImpl(Component.java:3955)
      at java.awt.Container.dispatchEventImpl(Container.java:2024)
      at java.awt.Component.dispatchEvent(Component.java:3803)
      at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
      at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
      at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
      at java.awt.Container.dispatchEventImpl(Container.java:2010)
      at java.awt.Window.dispatchEventImpl(Window.java:1774)
      at java.awt.Component.dispatchEvent(Component.java:3803)
      at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
      at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
      at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
      at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
Closing outputStream...




In my code, i Do call OutputStream os = port.getOutputStream ()  , but
i do NOT call InputStream is = port.getInputStream ()...

Do you want me to put that? Im trying it now?
The other lines (CommPortIdentifier portIdentifier = ....  and CommPort port = portIdentifier.open ( "Your application ... )  are indeed used...

Thx   :)
0
 
ADSLMarkCommented:
Here is a nice document describing some examples with serial/parallel ports using the same library..
http://java.sun.com/developer/Books/javaprogramming/cookbook/11.pdf
Somewhere in the beginning they say:
The message “Can’t open input stream” appears because my notebook’s printer
port is (according to the Java Comm API) unable to do bidirectional I/O. This is
in fact incorrect, as I have used various printer-port devices that require bidirectional
I/O, such as the Logitech (formerly Connectix) QuickCam, on this same
hardware platform (but under Unix and MS-Windows, not using Java). This message
is just a warning; the program works correctly despite it

Maybe this is also the case now. Anyway, I would suggest you try to implement a basic tryout which succesfully communicates with your printer and if you got that, you insert that into the bigger program.

Mark
0
 
memozebaduaAuthor Commented:
Mmm never mind, i did it :D  
with another code (mayankeagle helped me in another question)...

But now, i dont know what to do :S

Thanks a lot guys!

Nemo
0
 
Mayank SAssociate Director - Product EngineeringCommented:
You mean closing the ports in the finally block?
0
 
memozebaduaAuthor Commented:
The same code that i had with your corrections (yes, the finally block and more) worked fine with LPT printers, although the code is specifically for COM drivers.

:)
0
 
Mayank SAssociate Director - Product EngineeringCommented:
:-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.