Esempio n. 1
0
public abstract class Connection {
  private static final boolean TRAKTOR_USED = false;

  private static final org.apache.log4j.Logger CAT =
      org.apache.log4j.Logger.getLogger(Connection.class.getName());

  private Frame traktor;
  private static boolean traktorConnectionDown = false;

  /**
   * Creates a new connection to the specified host of specified type. <br>
   * <br>
   * type: Type of connection to create <br>
   * destination: Host to connect to (in "host:port" or "host" syntax)
   */
  public Connection(java.net.InetAddress host, int port, PluginContext ctx)
      throws MessagingNetworkException, java.io.IOException {
    if (TRAKTOR_USED) {
      if (traktorConnectionDown) throw new IOException("network is down");

      traktor = new Frame("" + host + ":" + port + " - Traktor");
      final Checkbox c = new Checkbox("break this & ALL future connections");
      c.setState(traktorConnectionDown);
      c.addItemListener(
          new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
              traktorConnectionDown = c.getState();
              try {
                if (traktorConnectionDown) closeSocket();
              } catch (Exception ex) {
              }
            }
          });
      traktor.add(c);
      traktor.setSize(100, 50);
      traktor.setLocation(230, 450);
      traktor.setVisible(true);
    } else {
      traktor = null;
    }
  }

  public final int available() throws IOException {
    if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException();
    if (isClosed()) throw new IOException("connection closed");
    return getInputStream().available();
  }

  public abstract void closeSocket();

  public final void flush() throws IOException, MessagingNetworkException {
    OutputStream os = getOutputStream();
    synchronized (os) {
      os.flush();
    }
  }

  protected final java.io.InputStream getInputStream() throws IOException {
    if (isClosed()) throw new IOException("connection closed");
    InputStream is = getInputStream0();
    if (is == null) throw new IOException("connection closed");
    return is;
  }

  protected abstract java.io.InputStream getInputStream0() throws IOException;

  protected final java.io.OutputStream getOutputStream() throws IOException {
    if (isClosed()) {
      if (TRAKTOR_USED && traktor != null && !traktorConnectionDown) {
        traktor.dispose();
        traktor = null;
      }
      throw new IOException("connection closed");
    }
    OutputStream os = getOutputStream0();
    if (os == null) throw new IOException("connection closed");
    return os;
  }

  protected abstract java.io.OutputStream getOutputStream0() throws IOException;

  public abstract boolean isClosed();

  /*
  private byte[] buf = new byte[8192];
  private int ofs = 0;
  private int len = 0;

  private void fill(InputStream is, long abortTime)
  throws IOException
  {
    for (;;)
    {
      if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out");
      int av = is.available();
      if (av == 0)
      {
        try
        {
          Thread.currentThread().sleep(100);
        }
        catch (InterruptedException ex)
        {
          throw new InterruptedIOException();
        }
        continue;
      }
      int capacity = buf.length - len;
      if (av > capacity) av = capacity;
      int rc = capacity - ofs;
      int pos = ofs + len;
      if (rc >= av)
      {
        int read = is.read(buf, pos, av);
        if (read < 0) read = 0;
        len += read;
        return;
      }
      //rc < av
      while (rc > 0)
      {
        int read = is.read(buf, ofs, rc);
        if (read < 0) read = 0;
        len += read;
        rc -= read;
        if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out");
      }
      //rc <= 0
      //case 1, when buf.length-1 >= ofs+len-1  (=> rc > 0)
      //cells ofs, ..., ofs+len-1 are filled
      //case 2, when buf.length-1 < ofs+len-1 (<=> buf.length-1 <= ofs+len-2)
      //cells ofs, ..., buf.length-1 are filled
      //cells 0, ..., ofs+len-2 - (buf.length-1) are filled, too
      int lm = ofs+len-1 - buf.length;
      if (lm > av) lm = av;
      rc = 0;
      while (lm > 0)
      {
        int read = is.read(buf, ofs, rc);
        if (read < 0) read = 0;
        len += read;
        rc -= read;
        if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out");
      }

    }
  }
  */

  public final String readCommand(byte[] b)
      throws IOException, InterruptedException, MessagingNetworkException {
    InputStream is = getInputStream();
    synchronized (is) {
      long abortTime =
          System.currentTimeMillis() + 1000 * MSNMessagingNetwork.REQPARAM_SOCKET_TIMEOUT_SECONDS;
      int ofs = 0;
      boolean d = false;
      for (; ; ) {
        if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException();
        int by = is.read();
        if (by == -1) throw new IOException("unexpected EOF");
        if (by == 10 && d) break;
        d = (by == 13);
        if (ofs < b.length) {
          b[ofs++] = (byte) by;
        }
        if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out");
        /*
        if (len >= buffer.length)
        {
          ...
          return ...;
        }
        int pos = findCRLF();
        if (pos != -1) break;
        fill(is, abortTime);
        */
      }
      if (b[ofs - 1] == 13) --ofs;

      String line = new String(b, 0, ofs, "ASCII");

      if (StringUtil.startsWith(line, "MSG")) {
        StringTokenizer st = new StringTokenizer(line);
        String len_s = null;
        while (st.hasMoreTokens()) {
          len_s = st.nextToken();
        }
        if (len_s == null) throw new AssertException("len_s is null");
        int len;
        try {
          len = Integer.parseInt(len_s);
        } catch (NumberFormatException ex) {
          ServerConnection.throwProtocolViolated("MSG length must be int");
          len = 0;
        }
        String msg = readMSG(len);
        line = line + "\r\n" + msg;
      }
      if (Defines.DEBUG && CAT.isDebugEnabled()) CAT.debug("S: " + line);
      return line;
    }
  }

  private final String readMSG(final int len)
      throws IOException, InterruptedException, MessagingNetworkException {
    if (len > 65000)
      ServerConnection.throwProtocolViolated("incoming message is too long: " + len + " bytes");
    byte[] b = new byte[len];
    InputStream is = getInputStream();
    synchronized (is) {
      long abortTime =
          System.currentTimeMillis() + 1000 * MSNMessagingNetwork.REQPARAM_SOCKET_TIMEOUT_SECONDS;
      int ofs = 0;

      while (ofs < len) {
        if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException();
        int read = is.read(b, ofs, len - ofs);
        if (read < 0) read = 0;
        ofs += read;
        if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out");
        /*
        if (len >= buffer.length)
        {
          ...
          return ...;
        }
        int pos = findCRLF();
        if (pos != -1) break;
        fill(is, abortTime);
        */
      }

      String msg = new String(b, 0, len, "UTF-8");
      return msg;
    }
  }

  public final void writeASCII(String s) throws IOException {
    if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException();
    OutputStream os = getOutputStream();
    synchronized (os) {
      if (Defines.DEBUG && CAT.isDebugEnabled()) CAT.debug("C: " + s);
      os.write(s.getBytes("ASCII"));
      os.write((byte) 13);
      os.write((byte) 10);
      os.flush();
    }
  }

  /**
   * UTF byte count is appended to the asciiPrefix, then UTF bytes are appended to the result; the
   * final result is sent.
   */
  public final void writeMSG(String asciiPrefix, String msgBody) throws IOException {
    if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException();
    OutputStream os = getOutputStream();
    synchronized (os) {
      byte[] utfBytes = msgBody.getBytes("UTF-8");
      asciiPrefix = asciiPrefix + ' ' + utfBytes.length;
      if (Defines.DEBUG && CAT.isDebugEnabled()) CAT.debug("C: " + asciiPrefix + "\r\n" + msgBody);
      os.write(asciiPrefix.getBytes("ASCII"));
      os.write((byte) 13);
      os.write((byte) 10);
      os.write(utfBytes);
      os.flush();
    }
  }
}
Esempio n. 2
0
/**
 * An icon for the preview of a given resource.
 *
 * <p>TODO: merge common code with PreviewPane, and perhaps put in a 3rd class so can have multiple
 * icons referencing the same underlying image.
 *
 * @version $Revision: 1.19 $ / $Date: 2010-02-03 19:16:31 $ / $Author: mike $
 * @author Scott Fraize
 */
public class ResourceIcon implements javax.swing.Icon, Images.Listener, Runnable {
  private static final org.apache.log4j.Logger Log =
      org.apache.log4j.Logger.getLogger(ResourceIcon.class);

  // private final Image NoImage = VueResources.getImage("/icon_noimage32.gif");
  private static final Image NoImage = GUI.NoImage32;

  private Resource mResource;
  private Object mPreviewData;
  private Image mImage;
  private int mImageWidth;
  private int mImageHeight;
  private boolean isLoading = false;
  private Component mPainter = null;

  private int mWidth = -1;
  private int mHeight = -1;

  // private final JLabel StatusLabel = new JLabel("(status)", JLabel.CENTER);

  /**
   * This constructor will be needed if the icon is to be placed into a component that uses cell
   * renderers, such as JList, JTable, or JTree. In the normal course, ResourceIcon's repaint when
   * their data is loaded, and to do so they remember the component they're being painted on, and
   * ask it to repaint when the data comes in.
   *
   * <p>But this repaint doesn't work if what they're being asked to paint on is a renderer.
   *
   * <p>The problem with renderer's is that "repaint" is overriden and defined as a no-op, as
   * they're only used to temporarily take on and draw their values when they're asked to paint.
   */

  // above could be handled w/out having to pass the painter around by requiring that
  // any cell renderer that wants to display a ResourceIcon to do a putClientProperty
  // of a key (e.g., ResourceIcon.PAINTER) with a reference to the  parent repainter,
  // which we could grab the first time we repaint here.

  public ResourceIcon(Resource r, int width, int height, Component painter) {
    setSize(width, height);
    // StatusLabel.setVisible(false);
    // add(StatusLabel);
    // loadResource(r);
    mResource = r;
    mPainter = painter;
    if (DEBUG.IMAGE)
      out("Constructed " + width + "x" + height + " " + r + " painter=" + GUI.namex(painter));
  }

  /** Act like a regular Icon */
  public ResourceIcon(Resource r, int width, int height) {
    this(r, width, height, null);
  }

  /** Expand's to fit the size of the component it's painted into */
  public ResourceIcon() {}

  public void setSize(int w, int h) {
    if (w != mWidth || h != mHeight) {
      mWidth = w;
      mHeight = h;
      repaint();
    }
  }

  private void repaint() {
    if (mPainter != null) {
      if (DEBUG.IMAGE) out("repaint in " + GUI.name(mPainter));
      mPainter.repaint();
    }
    // FYI, this will not repaint if the parent is a DefaultTreeCellRenderer,
    // and the parent of the parent (a JLabel), is null, so we can't get that.
  }

  public int getIconWidth() {
    return mWidth;
  }

  public int getIconHeight() {
    return mHeight;
  }

  private void showLoadingStatus() {
    // StatusLabel.setText("Loading...");
    // StatusLabel.setVisible(true);
  }

  private void status(String msg) {
    // StatusLabel.setText("<HTML>"+msg);
    // StatusLabel.setVisible(true);
  }

  private void clearStatus() {
    // StatusLabel.setVisible(false);
  }

  public Resource getResource() {
    return mResource;
  }

  /** If the image for the icon has been loaded, this will return it, otherwise, null. */
  public Image getImage() {
    return mImage;
  }

  synchronized void loadResource(Resource r) {

    if (DEBUG.RESOURCE || DEBUG.IMAGE) out("loadResource: " + Util.tag(r) + " " + r);

    mResource = r;
    if (r != null) mPreviewData = r.getPreview();
    else mPreviewData = null;
    mImage = null;

    // URLResource decides this
    // if (mPreviewData == null && mResource.isImage())
    //    mPreviewData = mResource;

    loadPreview(mPreviewData);
  }

  private void loadPreview(Object previewData) {
    // todo: handle if preview is a Component,
    // todo: handle a String as preview data.

    if (false /*&& r.getIcon() != null*/) { // these not currently valid from Osid2AssetResource
                                            // (size=-1x-1)
      // displayIcon(r.getIcon());
    } else if (previewData instanceof java.awt.Component) {
      out("TODO: handle Component preview " + previewData);
      displayImage(NoImage);
    } else if (previewData != null) { // todo: check an Images.isImageableSource
      loadImage(previewData);
    } else {
      displayImage(NoImage);
    }
  }

  // TODO: if this triggered from an LWImage selection, and LWImage had
  // an image error, also notify the LWImage of good data if it comes
  // in as a result of selection.

  private synchronized void loadImage(Object imageData) {
    if (DEBUG.IMAGE) out("loadImage " + imageData);

    // test of synchronous loading:
    // out("***GOT IMAGE " + Images.getImage(imageData));

    // TODO: refactor ResourceIcon to use the new ImageRef --
    // will be much simpler.

    if (Images.getImage(imageData, this) == null) {
      // will make callback to gotImage when we have it
      isLoading = true;
      showLoadingStatus();
    } else {
      // gotImage has already been called
      isLoading = false;
    }
  }

  //     /** @see Images.Listener */
  //     public void gotImageUpdate(Object key, Images.Progress p) {}

  public synchronized void gotImageSize(
      Object imageSrc, int width, int height, long byteSize, int[] ss) {

    // if (imageSrc != mPreviewData) return;

    mImageWidth = width;
    mImageHeight = height;
  }

  /** @see Images.Listener */
  public synchronized void gotImageProgress(Object imageSrc, long bytesSoFar, float pct) {}

  /** @see Images.Listener */
  public synchronized void gotImage(Object imageSrc, Images.Handle handle) {

    // if (imageSrc != mPreviewData) return;

    displayImage(handle.image);
    isLoading = false;
  }
  /** @see Images.Listener */
  public synchronized void gotImageError(Object imageSrc, String msg) {

    // if (imageSrc != mPreviewData) return;

    displayImage(NoImage);
    status("Error: " + msg);
    isLoading = false;
  }

  private void displayImage(Image image) {
    if (DEBUG.RESOURCE || DEBUG.IMAGE) out("displayImage " + Util.tag(image));

    mImage = image;
    if (mImage != null) {
      mImageWidth = mImage.getWidth(null);
      mImageHeight = mImage.getHeight(null);
      if (DEBUG.IMAGE) out("displayImage " + mImageWidth + "x" + mImageHeight);
    }

    clearStatus();
    repaint();
  }

  /*@Override*/ public synchronized void run() {
    // loadPreview(mPreviewData);
    if (!isLoading) loadResource(mResource);
  }

  private static final double MaxZoom = 1.0;
  private static final boolean DrawBorder = false; // todo: doesn't handle cropped / squared off
  private static final int BorderWidth = 1; // width of border (todo: only works as 1)
  private static final int BorderGap = 1; // whitespace around drawn border
  private static final int BorderSpace = BorderWidth + BorderGap;

  private static final boolean CropToSquare = true;

  /*@Override*/ public void paintIcon(Component c, Graphics g, int x, int y) {
    final boolean expandToFit = (mWidth < 1);

    if (DEBUG.IMAGE && DEBUG.META)
      out(
          "paintIcon; onto="
              + GUI.name(c)
              + " painter="
              + GUI.name(mPainter)
              + "@"
              + Integer.toHexString((mPainter.hashCode())));

    if (mPainter == null) {
      // note this means repaint updates would stop in a new parent,
      // tho assuming it's loaded by then, regular paints would work fine.
      mPainter = c;
    }

    if (DrawBorder && !expandToFit) {
      g.setColor(Color.gray);
      g.drawRect(x, y, mWidth - 1, mHeight - 1);
    }

    if (mImage == null) {

      if (!isLoading /*&& mPreviewData != null*/) {
        synchronized (this) {
          if (!isLoading /*&& mPreviewData != null*/)
            VUE.invokeAfterAWT(ResourceIcon.this); // load the preview
        }
      }
      g.setColor(Color.gray);
      g.drawRect(x, y, mWidth - 1, mHeight - 1);
      return;
    }

    int fitWidth, fitHeight;
    final Dimension maxImageSize;

    if (expandToFit) {
      // fill the given component
      fitWidth = c.getWidth();
      fitHeight = c.getHeight();
      maxImageSize = c.getSize();
    } else {
      // paint at our fixed size
      fitWidth = mWidth;
      fitHeight = mHeight;

      if (DrawBorder)
        maxImageSize = new Dimension(fitWidth - BorderSpace * 2, fitHeight - BorderSpace * 2);
      else maxImageSize = new Dimension(fitWidth, fitHeight);

      if (DEBUG.IMAGE && DEBUG.META) out("paintIcon; into " + GUI.name(maxImageSize));
    }

    double zoomFit;
    if (mImage == NoImage && expandToFit) {
      zoomFit = 1;
    } else {
      Rectangle2D imageBounds;
      if (CropToSquare) {
        // square off image, then fit in icon (todo: better; crop to icon)
        int smallestAxis = mImageWidth > mImageHeight ? mImageHeight : mImageWidth;
        imageBounds = new Rectangle2D.Float(0, 0, smallestAxis, smallestAxis);
      } else {
        // fit entire image in icon
        imageBounds = new Rectangle2D.Float(0, 0, mImageWidth, mImageHeight);
      }
      zoomFit = ZoomTool.computeZoomFit(maxImageSize, 0, imageBounds, null, false);
      if (zoomFit > MaxZoom) zoomFit = MaxZoom;
    }

    final int drawW = (int) (mImageWidth * zoomFit + 0.5);
    final int drawH = (int) (mImageHeight * zoomFit + 0.5);

    int xoff = x;
    int yoff = y;

    // center if drawable area is bigger than image
    if (drawW != fitWidth) xoff += (fitWidth - drawW) / 2;
    if (drawH != fitHeight) yoff += (fitHeight - drawH) / 2;

    Shape oldClip = null;
    if (CropToSquare && !expandToFit) {
      oldClip = g.getClip();
      g.clipRect(x, y, mWidth, mHeight);
    }

    if (DEBUG.IMAGE && DEBUG.META)
      out("paintIcon; " + Util.tag(mImage) + " as " + drawW + "x" + drawH);
    g.drawImage(mImage, xoff, yoff, drawW, drawH, null);

    if (DEBUG.BOXES) {
      g.setColor(Color.green);
      ((Graphics2D) g)
          .setComposite(
              java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, 0.2f));
      g.drawRect(x, y, mWidth - 1, mHeight - 1);
      ((Graphics2D) g).setComposite(java.awt.AlphaComposite.SrcOver);
    }

    if (CropToSquare && !expandToFit) g.setClip(oldClip);
  }

  private void out(String s) {
    String name = "ResourceIcon" + "@" + Integer.toHexString(hashCode());
    Log.debug(name + " " + s);
  }
}
Esempio n. 3
0
/**
 * Dies ist ein Intfeld das nur Zahleneingabe zulaesst.<br>
 * Der Code wurde teilweise aus dem Onlinetutorial von SUN uebernommen.<br>
 *
 * @author Thorsten Hell
 * @version 1.0 erstellt am 27.05.1999
 * @since letzte Aenderung am 01.03.2000
 */
public class DateField extends JTextField implements FocusListener {

  // ~ Instance fields --------------------------------------------------------

  private final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(this.getClass());
  private Toolkit toolkit;
  // private NumberFormat integerFormatter;
  private boolean checked = false;
  private DecimalFormat integerFormatter;
  private int maxLength;
  private boolean bringFocus2Next = false;
  private DateField nextField;

  // ~ Constructors -----------------------------------------------------------

  /**
   * Dem Konstruktor wird ein Formatstring uebergeben. Aus diesem Formatstring liesst das Textfeld
   * heraus wieviele Ziffern maximal eingegeben werden koennen, und wie gross die Anzeige sein soll.
   *
   * @param formatString DOCUMENT ME!
   */
  public DateField(final String formatString) {
    super(formatString.length());
    bringFocus2Next = false;
    maxLength = formatString.length();
    integerFormatter = new DecimalFormat(formatString);
    toolkit = Toolkit.getDefaultToolkit();
    // integerFormatter = NumberFormat.getNumberInstance();//Locale.US);
    integerFormatter.setParseIntegerOnly(true);
    addFocusListener(this);
  }

  /**
   * Creates a new DateField object.
   *
   * @param value DOCUMENT ME!
   * @param formatString DOCUMENT ME!
   */
  public DateField(final int value, final String formatString) {
    super(formatString.length());
    bringFocus2Next = false;
    maxLength = formatString.length();
    integerFormatter = new DecimalFormat(formatString);
    toolkit = Toolkit.getDefaultToolkit();
    // integerFormatter = NumberFormat.getNumberInstance();//Locale.US);
    integerFormatter.setParseIntegerOnly(true);
    setValue(value);
    addFocusListener(this);
  }

  // ~ Methods ----------------------------------------------------------------

  /**
   * Mit dieser methode kann man ein IntFeld angeben, zu dem der Focus gehen soll, wenn die
   * entsprechende Anzahl von Ziffern erreicht worden ist.
   *
   * @param nf DOCUMENT ME!
   */
  public void setNextField(final DateField nf) {
    bringFocus2Next = true;
    nextField = nf;
  }
  /**
   * Mit dieser Methode kann der int-Wert des Feldes bestimmt werden.
   *
   * @return DOCUMENT ME!
   */
  public int getValue() {
    int retVal = 0;
    try {
      retVal = integerFormatter.parse(getText()).intValue();
    } catch (ParseException e) {
      // This should never happen because insertString allows
      // only properly formatted data to get in the field.
      toolkit.beep();
    }
    return retVal;
  }
  /**
   * Mit dieser Methode wird der Wert des Feldes mittels eines Integers gesetzt.
   *
   * @param value DOCUMENT ME!
   */
  public void setValue(final int value) {
    setText(integerFormatter.format(value));
  }
  /**
   * Diese Methode liefert zurueck ob sich das Feld seiner pruefung unterzogen hat.
   *
   * @return DOCUMENT ME!
   */
  public boolean checked() {
    return checked;
  }
  /** Diese Methode prueft das Feld. */
  public void check() {
    final boolean tmp = bringFocus2Next;
    bringFocus2Next = false;
    setValue(getValue());
    checked = true;
    bringFocus2Next = tmp;
  }

  /*
   * diese Methode wird aufgerufen wenn das Feld den Focus erhaelt
   */
  @Override
  public void focusGained(final FocusEvent e) {
    return;
  }

  /*
   * diese Methode wird aufgerufen wenn das Feld den Focus verliert
   */
  @Override
  public void focusLost(final FocusEvent e) {
    if (e.isTemporary()) {
      return;
    } else {
      if (!checked()) {
        check();
      }
    }
  }

  /*
   * diese methode liefert ein neues WholeNumberDocument.
   */
  @Override
  protected Document createDefaultModel() {
    return new WholeNumberDocument();
  }

  // ~ Inner Classes ----------------------------------------------------------

  /**
   * diese lokale Klasse braucht man, um die Eingaben in das Feld zu ueberpruefen.
   *
   * @version $Revision$, $Date$
   */
  protected class WholeNumberDocument extends PlainDocument {

    // ~ Methods ------------------------------------------------------------

    @Override
    public void remove(final int offs, final int len) throws BadLocationException {
      checked = false;
      super.remove(offs, len);
    }

    @Override
    public void insertString(final int offs, final String str, final AttributeSet a)
        throws BadLocationException {
      // NavigatorLogger.printMessage("Offset:"+offs+" STr:"+str+"L:"+getLength()+"attr:"+a);

      if ((getLength() + str.length()) <= maxLength) {
        final char[] source = str.toCharArray();
        final char[] result = new char[source.length];
        int j = 0;

        for (int i = 0; i < result.length; i++) {
          if (Character.isDigit(source[i])) {
            result[j++] = source[i];
          } else {
            toolkit.beep();
            if (log.isDebugEnabled()) {
              log.debug("insertString: " + source[i]); // NOI18N
            }
          }
        }
        super.insertString(offs, new String(result, 0, j), a);
        checked = false;
      } else {
        toolkit.beep();
      }
      if ((getLength()) == maxLength) { // getLength() ist schon aktualisiert
        if (bringFocus2Next == true) {
          checked = true;
          nextField.requestFocus();
        }
        // NavigatorLogger.printMessage("Sprung");
        // NavigatorLogger.printMessage(nextField);
      }
    }
  }
}
/**
 * DOCUMENT ME!
 *
 * @author spuhl
 * @version $Revision$, $Date$
 */
public class VerdisCrossoverPanel extends javax.swing.JPanel
    implements MouseListener, ListSelectionListener {

  // ~ Static fields/initializers ---------------------------------------------

  // ToDo defaults für Panel ?
  private static final Logger log = org.apache.log4j.Logger.getLogger(VerdisCrossoverPanel.class);
  private static final String server = "http://localhost:";
  private static final String request = "/gotoKassenzeichen?";
  // ToDo perhaps place in VerdisCrossover
  // Problem: would be the the only dependency to verdis
  // http://localhost:18000/verdis/gotoKassenzeichen?kassenzeichen=6000442
  public static final NameValuePair PARAMETER_KASSENZEICHEN =
      new NameValuePair("kassenzeichen", "");
  private static final String PROGRESS_CARD_NAME = "progress";
  private static final String CONTENT_CARD_NAME = "content";
  private static final String MESSAGE_CARD_NAME = "message";
  private static final String SWITCH_TO_MENU_NAME = "Zu Kassenzeichen wechseln";

  // ~ Instance fields --------------------------------------------------------

  // TODO Jean
  private final KassenzeichenTableModel tableModel = new KassenzeichenTableModel();
  private int verdisCrossoverPort = -1;
  private FadingCardLayout layout = new FadingCardLayout();
  private JPopupMenu switchToKassenzeichenPopup;
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton btnClose;
  private javax.swing.JButton btnLoadSelectedKassenzeichen;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JLabel lblMessage;
  private javax.swing.JPanel panAll;
  private javax.swing.JPanel panContent;
  private javax.swing.JPanel panContentMessage;
  private javax.swing.JPanel panContentProgress;
  private javax.swing.JPanel panControl;
  private javax.swing.JProgressBar pgbProgress;
  private javax.swing.JTable tblKassenzeichen;
  // End of variables declaration//GEN-END:variables

  // ~ Constructors -----------------------------------------------------------

  /**
   * Creates new form VerdisCrossoverPanel.
   *
   * @param verdisCrossoverPort DOCUMENT ME!
   */
  public VerdisCrossoverPanel(final int verdisCrossoverPort) {
    initComponents();
    configurePopupMenue();
    panAll.setLayout(layout);
    panAll.removeAll();
    panAll.add(panContentProgress, PROGRESS_CARD_NAME);
    panAll.add(panContent, CONTENT_CARD_NAME);
    panAll.add(panContentMessage, MESSAGE_CARD_NAME);
    // TODO Jean
    tblKassenzeichen.setModel(tableModel);
    tblKassenzeichen.addMouseListener(this);
    tblKassenzeichen.addMouseListener(new PopupListener());
    tblKassenzeichen.getSelectionModel().addListSelectionListener(this);
    this.verdisCrossoverPort = verdisCrossoverPort;
    pgbProgress.setIndeterminate(true);
    //        this.add(panContentProgress, BorderLayout.CENTER);
    layout.show(panAll, PROGRESS_CARD_NAME);
  }

  // ~ Methods ----------------------------------------------------------------

  /** DOCUMENT ME! */
  public void startSearch() {
    // TODO Jean
    try {
      LagisBroker.getInstance().execute(new KassenzeichenRetriever());
    } catch (Exception ex) {
      log.error("Fehler während dem suchen der Kassenzeichen: ", ex);
      // ToDo Nachricht an benutzer
    }
  }

  /**
   * This method is called from within the constructor to initialize the form. WARNING: Do NOT
   * modify this code. The content of this method is always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {
    panControl = new javax.swing.JPanel();
    btnClose = new javax.swing.JButton();
    btnLoadSelectedKassenzeichen = new javax.swing.JButton();
    panAll = new javax.swing.JPanel();
    panContentProgress = new javax.swing.JPanel();
    pgbProgress = new javax.swing.JProgressBar();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    panContentMessage = new javax.swing.JPanel();
    lblMessage = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    panContent = new javax.swing.JPanel();
    jScrollPane1 = new javax.swing.JScrollPane();
    tblKassenzeichen = new JXTable();

    setPreferredSize(new java.awt.Dimension(500, 200));

    panControl.setMinimumSize(new java.awt.Dimension(50, 50));
    panControl.setPreferredSize(new java.awt.Dimension(300, 50));

    btnClose.setText(
        org.openide.util.NbBundle.getMessage(
            VerdisCrossoverPanel.class, "VerdisCrossoverPanel.btnClose.text")); // NOI18N
    btnClose.addActionListener(
        new java.awt.event.ActionListener() {

          @Override
          public void actionPerformed(final java.awt.event.ActionEvent evt) {
            btnCloseActionPerformed(evt);
          }
        });

    btnLoadSelectedKassenzeichen.setIcon(
        new javax.swing.ImageIcon(
            getClass()
                .getResource("/de/cismet/lagis/ressource/icons/buttons/postion.png"))); // NOI18N
    btnLoadSelectedKassenzeichen.setText(
        org.openide.util.NbBundle.getMessage(
            VerdisCrossoverPanel.class,
            "VerdisCrossoverPanel.btnLoadSelectedKassenzeichen.text")); // NOI18N
    btnLoadSelectedKassenzeichen.setToolTipText(
        org.openide.util.NbBundle.getMessage(
            VerdisCrossoverPanel.class,
            "VerdisCrossoverPanel.btnLoadSelectedKassenzeichen.toolTipText")); // NOI18N
    btnLoadSelectedKassenzeichen.setEnabled(false);
    btnLoadSelectedKassenzeichen.addActionListener(
        new java.awt.event.ActionListener() {

          @Override
          public void actionPerformed(final java.awt.event.ActionEvent evt) {
            btnLoadSelectedKassenzeichenActionPerformed(evt);
          }
        });

    final javax.swing.GroupLayout panControlLayout = new javax.swing.GroupLayout(panControl);
    panControl.setLayout(panControlLayout);
    panControlLayout.setHorizontalGroup(
        panControlLayout
            .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(
                javax.swing.GroupLayout.Alignment.TRAILING,
                panControlLayout
                    .createSequentialGroup()
                    .addContainerGap(378, Short.MAX_VALUE)
                    .addComponent(btnLoadSelectedKassenzeichen)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnClose)
                    .addContainerGap()));
    panControlLayout.setVerticalGroup(
        panControlLayout
            .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(
                panControlLayout
                    .createSequentialGroup()
                    .addContainerGap()
                    .addGroup(
                        panControlLayout
                            .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnClose)
                            .addComponent(btnLoadSelectedKassenzeichen))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

    panControlLayout.linkSize(
        javax.swing.SwingConstants.VERTICAL,
        new java.awt.Component[] {btnClose, btnLoadSelectedKassenzeichen});

    panAll.setPreferredSize(new java.awt.Dimension(400, 251));
    panAll.setLayout(new java.awt.CardLayout());

    panContentProgress.setPreferredSize(new java.awt.Dimension(250, 140));

    jLabel1.setIcon(
        new javax.swing.ImageIcon(
            getClass().getResource("/de/cismet/lagis/ressource/icons/searching.png"))); // NOI18N

    jLabel2.setText(
        org.openide.util.NbBundle.getMessage(
            VerdisCrossoverPanel.class, "VerdisCrossoverPanel.jLabel2.text")); // NOI18N

    final javax.swing.GroupLayout panContentProgressLayout =
        new javax.swing.GroupLayout(panContentProgress);
    panContentProgress.setLayout(panContentProgressLayout);
    panContentProgressLayout.setHorizontalGroup(
        panContentProgressLayout
            .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(
                panContentProgressLayout
                    .createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(
                        panContentProgressLayout
                            .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(
                                pgbProgress,
                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                400,
                                Short.MAX_VALUE)
                            .addComponent(jLabel2))
                    .addContainerGap()));
    panContentProgressLayout.setVerticalGroup(
        panContentProgressLayout
            .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(
                javax.swing.GroupLayout.Alignment.TRAILING,
                panContentProgressLayout
                    .createSequentialGroup()
                    .addContainerGap(49, Short.MAX_VALUE)
                    .addGroup(
                        panContentProgressLayout
                            .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(
                                panContentProgressLayout
                                    .createSequentialGroup()
                                    .addComponent(jLabel2)
                                    .addPreferredGap(
                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(
                                        pgbProgress,
                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(12, 12, 12))
                            .addComponent(
                                jLabel1,
                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                67,
                                javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap()));

    panAll.add(panContentProgress, "card3");

    panContentMessage.setPreferredSize(new java.awt.Dimension(250, 140));

    lblMessage.setText(
        org.openide.util.NbBundle.getMessage(
            VerdisCrossoverPanel.class, "VerdisCrossoverPanel.lblMessage.text")); // NOI18N

    jLabel3.setIcon(
        new javax.swing.ImageIcon(
            getClass().getResource("/de/cismet/lagis/ressource/icons/warn.png"))); // NOI18N
    jLabel3.setText(
        org.openide.util.NbBundle.getMessage(
            VerdisCrossoverPanel.class, "VerdisCrossoverPanel.jLabel3.text")); // NOI18N

    final javax.swing.GroupLayout panContentMessageLayout =
        new javax.swing.GroupLayout(panContentMessage);
    panContentMessage.setLayout(panContentMessageLayout);
    panContentMessageLayout.setHorizontalGroup(
        panContentMessageLayout
            .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(
                javax.swing.GroupLayout.Alignment.TRAILING,
                panContentMessageLayout
                    .createSequentialGroup()
                    .addContainerGap(28, Short.MAX_VALUE)
                    .addComponent(
                        jLabel3,
                        javax.swing.GroupLayout.PREFERRED_SIZE,
                        54,
                        javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(
                        lblMessage,
                        javax.swing.GroupLayout.PREFERRED_SIZE,
                        388,
                        javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap()));
    panContentMessageLayout.setVerticalGroup(
        panContentMessageLayout
            .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(
                javax.swing.GroupLayout.Alignment.TRAILING,
                panContentMessageLayout
                    .createSequentialGroup()
                    .addContainerGap(49, Short.MAX_VALUE)
                    .addGroup(
                        panContentMessageLayout
                            .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(
                                jLabel3,
                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                67,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(
                                lblMessage,
                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                59,
                                javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap()));

    panAll.add(panContentMessage, "card2");

    tblKassenzeichen.setModel(
        new javax.swing.table.DefaultTableModel(
            new Object[][] {
              {null, null, null, null},
              {null, null, null, null},
              {null, null, null, null},
              {null, null, null, null}
            },
            new String[] {"Title 1", "Title 2", "Title 3", "Title 4"}));
    jScrollPane1.setViewportView(tblKassenzeichen);

    final javax.swing.GroupLayout panContentLayout = new javax.swing.GroupLayout(panContent);
    panContent.setLayout(panContentLayout);
    panContentLayout.setHorizontalGroup(
        panContentLayout
            .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(
                panContentLayout
                    .createSequentialGroup()
                    .addContainerGap()
                    .addComponent(
                        jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE)
                    .addContainerGap()));
    panContentLayout.setVerticalGroup(
        panContentLayout
            .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(
                panContentLayout
                    .createSequentialGroup()
                    .addContainerGap()
                    .addComponent(
                        jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE)
                    .addContainerGap()));

    panAll.add(panContent, "card4");

    final javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout
            .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panAll, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
            .addComponent(
                panControl,
                javax.swing.GroupLayout.Alignment.TRAILING,
                javax.swing.GroupLayout.DEFAULT_SIZE,
                500,
                Short.MAX_VALUE));
    layout.setVerticalGroup(
        layout
            .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(
                layout
                    .createSequentialGroup()
                    .addComponent(
                        panAll, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(
                        panControl,
                        javax.swing.GroupLayout.PREFERRED_SIZE,
                        54,
                        javax.swing.GroupLayout.PREFERRED_SIZE)));
  } // </editor-fold>//GEN-END:initComponents

  /**
   * DOCUMENT ME!
   *
   * @param evt DOCUMENT ME!
   */
  private void btnCloseActionPerformed(
      final java.awt.event.ActionEvent evt) { // GEN-FIRST:event_btnCloseActionPerformed
    closeDialog();
  } // GEN-LAST:event_btnCloseActionPerformed

  /**
   * DOCUMENT ME!
   *
   * @param evt DOCUMENT ME!
   */
  private void btnLoadSelectedKassenzeichenActionPerformed(
      final java.awt.event.ActionEvent
          evt) { // GEN-FIRST:event_btnLoadSelectedKassenzeichenActionPerformed
    loadSelectedKassenzeichen();
  } // GEN-LAST:event_btnLoadSelectedKassenzeichenActionPerformed
  /** ToDo ugly. */
  private void closeDialog() {
    ((JDialog) getParent().getParent().getParent().getParent()).dispose();
  }

  /** ToDo make commons. */
  private void configurePopupMenue() {
    switchToKassenzeichenPopup = new JPopupMenu();
    final JMenuItem switchToKassenZeichenItem = new JMenuItem(SWITCH_TO_MENU_NAME);
    switchToKassenZeichenItem.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(final ActionEvent e) {
            if (log.isDebugEnabled()) {
              log.debug("action performed");
            }
            loadSelectedKassenzeichen();
          }
        });
    switchToKassenzeichenPopup.add(switchToKassenZeichenItem);
  }

  @Override
  public void mouseClicked(final MouseEvent e) {
    // TODO Jean
    if (log.isDebugEnabled()) {
      log.debug("Crossover: mouse clicked");
      log.debug("tableModelsize: " + tableModel.getRowCount());
    }
    if (log.isDebugEnabled()) {
      log.debug("tableModel content: " + tableModel.getAllKassenzeichen());
    }
    final Object source = e.getSource();
    if (source instanceof JXTable) {
      if (e.getClickCount() > 1) {
        loadSelectedKassenzeichen();
      } else {
        if (log.isDebugEnabled()) {
          log.debug("Crossover: Kein Multiclick");
        }
      }
    } else {
      if (log.isDebugEnabled()) {
        log.debug("Crossover:Mouselistner nicht für JXTable");
      }
    }
  }

  /**
   * ToDo place query generation in VerdisCrossover. Give key get Query.
   *
   * @param bean e bean DOCUMENT ME!
   */
  private void openKassenzeichenInVerdis(final CidsBean bean) {
    if (bean != null) {
      if ((verdisCrossoverPort < 0) || (verdisCrossoverPort > 65535)) {
        log.warn("Crossover: verdisCrossoverPort ist ungültig: " + verdisCrossoverPort);
      } else {
        // ToDo Thread
        final URL verdisQuery = createQuery(verdisCrossoverPort, bean);
        if (verdisQuery != null) {
          final SwingWorker<Void, Void> openKassenzeichen =
              new SwingWorker<Void, Void>() {

                @Override
                protected Void doInBackground() throws Exception {
                  verdisQuery.openStream();
                  return null;
                }

                @Override
                protected void done() {
                  try {
                    get();
                  } catch (Exception ex) {
                    log.error("Fehler beim öffnen des Kassenzeichens", ex);
                    // ToDo message to user;
                  }
                }
              };
          LagisBroker.getInstance().execute(openKassenzeichen);
        } else {
          log.warn("Crossover: konnte keine Query anlegen. Kein Abruf der Kassenzeichen möglich.");
        }
      }
    } else {
      log.warn("Crossover: Kann angebenes Flurstück nicht öffnwen");
    }
  }

  @Override
  public void mouseEntered(final MouseEvent e) {}

  @Override
  public void mouseExited(final MouseEvent e) {}

  @Override
  public void mousePressed(final MouseEvent e) {}

  @Override
  public void mouseReleased(final MouseEvent e) {}

  /** DOCUMENT ME! */
  // TODO Jean
  private void loadSelectedKassenzeichen() {
    try {
      final int selectedRow = tblKassenzeichen.getSelectedRow();
      if (selectedRow != -1) {
        final int modelIndex = ((JXTable) tblKassenzeichen).convertRowIndexToModel(selectedRow);
        if (modelIndex != -1) {
          final CidsBean selectedKassenzeichen = tableModel.getKassenzeichenAtIndex(modelIndex);
          if (selectedKassenzeichen != null) {
            openKassenzeichenInVerdis(selectedKassenzeichen);
          } else {
            log.warn("Crossover: Kein Kassenzeichen zu angebenen Index.");
          }
        } else {
          log.warn("Crossover: Kein ModelIndex zu angebenen ViewIndex.");
        }
      } else {
        if (log.isDebugEnabled()) {
          log.debug("Crossover: Keine Tabellenzeile selektiert.");
        }
      }
    } catch (Exception ex) {
      log.error("Fehler beim laden des selektierten Kasssenzeichens", ex);
    }
  }

  /**
   * DOCUMENT ME!
   *
   * @param port e port DOCUMENT ME!
   * @param bean DOCUMENT ME!
   * @return DOCUMENT ME!
   */
  // TODO Jean
  public static URL createQuery(final int port, final CidsBean bean) {
    if ((port < 0) || (port > 65535)) {
      log.warn("Crossover: verdisCrossoverPort ist ungültig: " + port);
    } else {
      try {
        // ToDo ugly because is static
        PARAMETER_KASSENZEICHEN.setValue(
            String.valueOf(bean.getProperty("kassenzeichennummer8"))); // kz.getId().toString());
        final GetMethod tmp = new GetMethod(server + port + request);
        tmp.setQueryString(new NameValuePair[] {PARAMETER_KASSENZEICHEN});
        if (log.isDebugEnabled()) {
          log.debug("Crossover: verdisCrossOverQuery: " + tmp.getURI().toString());
        }
        return new URL(tmp.getURI().toString());
      } catch (Exception ex) {
        log.error("Crossover: Fehler beim fernsteuern von VerdIS.", ex);
      }
    }
    return null;
  }

  @Override
  public void valueChanged(final ListSelectionEvent e) {
    if (tblKassenzeichen.getSelectedRowCount() > 0) {
      btnLoadSelectedKassenzeichen.setEnabled(true);
    } else {
      btnLoadSelectedKassenzeichen.setEnabled(false);
    }
  }

  // ~ Inner Classes ----------------------------------------------------------

  /**
   * DOCUMENT ME!
   *
   * @version $Revision$, $Date$
   */
  class PopupListener extends MouseAdapter {

    // ~ Methods ------------------------------------------------------------

    @Override
    public void mouseClicked(final MouseEvent e) {
      // TODO Jean
      showPopup(e);
    }

    @Override
    public void mouseReleased(final MouseEvent e) {
      // TODO Jean
      showPopup(e);
    }

    /**
     * DOCUMENT ME!
     *
     * @param e DOCUMENT ME!
     */
    // TODO Jean
    private void showPopup(final MouseEvent e) {
      if (log.isDebugEnabled()) {
        log.debug("showPopup");
      }
      if (e.isPopupTrigger()) {
        if (log.isDebugEnabled()) {
          // ToDo funktioniert nicht unter linux
          log.debug("popup triggered");
        }
        final int rowAtPoint = tblKassenzeichen.rowAtPoint(new Point(e.getX(), e.getY()));
        if ((rowAtPoint != -1)
            && ((tableModel.getKassenzeichenAtIndex(
                    ((JXTable) tblKassenzeichen).getFilters().convertRowIndexToModel(rowAtPoint)))
                != null)) {
          if (log.isDebugEnabled()) {
            log.debug("KassenzeichenEntity found");
          }
          switchToKassenzeichenPopup.show(e.getComponent(), e.getX(), e.getY());
        }
      }
    }
  }

  /**
   * DOCUMENT ME!
   *
   * @version $Revision$, $Date$
   */
  // TODO Jean
  public class KassenzeichenTableModel extends AbstractTableModel {

    // ~ Instance fields ----------------------------------------------------

    // ~ Instance fields ----------------------------------------------------
    private final String[] COLUMN_HEADER = {"Kassenzeichen"};
    private final ArrayList<CidsBean> data = new ArrayList<CidsBean>();

    // ~ Methods ------------------------------------------------------------

    // ~ Methods ------------------------------------------------------------
    @Override
    public int getColumnCount() {
      return 1;
    }

    @Override
    public int getRowCount() {
      return data.size();
    }

    @Override
    public Object getValueAt(final int rowIndex, final int columnIndex) {
      final CidsBean value = data.get(rowIndex);
      switch (columnIndex) {
        case 0:
          {
            return value.getProperty("kassenzeichennummer8");
          }
        default:
          {
            return "Spalte ist nicht definiert";
          }
      }
    }

    /**
     * * DOCUMENT ME!
     *
     * @param newData DOCUMENT ME!
     */
    public void updateTableModel(final Set newData) {
      data.clear();
      if (newData != null) {
        data.addAll(newData);
      }
      fireTableDataChanged();
    }

    /**
     * * DOCUMENT ME!
     *
     * @param index DOCUMENT ME!
     * @return DOCUMENT ME!
     */
    public CidsBean getKassenzeichenAtIndex(final int index) {
      return data.get(index);
    }

    /**
     * * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public ArrayList getAllKassenzeichen() {
      return data;
    }

    @Override
    public String getColumnName(final int column) {
      return COLUMN_HEADER[column];
    }
  }

  /**
   * DOCUMENT ME!
   *
   * @version $Revision$, $Date$
   */
  // TODO Jean
  class KassenzeichenRetriever extends SwingWorker<Set<CidsBean>, Void> {

    // ~ Methods ------------------------------------------------------------

    // ~ Methods  ------------------------------------------------------------
    @Override
    protected Set<CidsBean> doInBackground() throws Exception {
      final FlurstueckSchluesselCustomBean currentKey =
          LagisBroker.getInstance().getCurrentFlurstueckSchluessel();
      if (currentKey != null) {
        Geometry flurstueckGeom = LagisBroker.getInstance().getInstance().getCurrentWFSGeometry();
        if (flurstueckGeom != null) {
          log.info(
              "Crossover: Geometrie zum bestimmen der Kassenzeichen (vor Transformation): "
                  + flurstueckGeom
                  + ",SRS"
                  + flurstueckGeom.getSRID());
          flurstueckGeom =
              CrsTransformer.transformToGivenCrs(flurstueckGeom, "EPSG:31466"); // Hardcoded FTW
          log.info(
              "Crossover: Geometrie zum bestimmen der Kassenzeichen: "
                  + flurstueckGeom
                  + ",SRS"
                  + flurstueckGeom.getSRID());

          //                    final KassenzeichenFacadeRemote verdisServer =
          // LagisBroker.getInstance().getVerdisServer();

          final String query =
              "SELECT 11, k.id\n"
                  + "FROM  kassenzeichen k, geom\n"
                  + "WHERE k.geometrie = geom.id\n"
                  + "AND not isEmpty(geom.geo_field)\n"
                  + "AND intersects(geom.geo_field,st_buffer(st_buffer(geometryfromtext('"
                  + flurstueckGeom.toText()
                  + "',31466), "
                  + LagisBroker.getInstance().getKassenzeichenBuffer()
                  + "), 0))";

          if (log.isDebugEnabled()) {
            log.debug(query);
          }

          if (isCancelled()) {
            return null;
          }

          final MetaObject[] result =
              CidsBroker.getInstance().getMetaObject(query, "VERDIS_GRUNDIS");
          final HashSet<CidsBean> kassenzeichen =
              new HashSet<CidsBean>((result == null) ? 0 : result.length);

          if (result != null) {
            for (int i = 0; i < result.length; i++) {
              kassenzeichen.add(result[i].getBean());
            }
          }

          //                        kassenzeichen =
          // verdisServer.getIntersectingKassenzeichen(flurstueckGeom,
          //                                LagisBroker.getInstance().getKassenzeichenBuffer());

          if ((kassenzeichen != null) && (kassenzeichen.size() > 0)) {
            if (log.isDebugEnabled()) {
              log.debug("Crossover: Anzahl Kassenzeichen: " + kassenzeichen.size());
            }
          } else {
            log.info("Crossover:Keine geschnittenen Kassenzeichen gefunden."); // ToDo Meldung an
            // benutzer
          }
          return kassenzeichen;
        } else { // ToDo user message !
          lblMessage.setText(
              "<html>Keine Flurstücksgeometrie vorhanden,<br/>bestimmen der Kasssenzeichen nicht möglich.</html>");
          log.warn("Crossover: Keine Geometrie vorhanden zum bestimmen der Kassenzeichen");
        }
      } else {
        // ToDo user message !
        lblMessage.setText(
            "<html>Bitte wählen Sie ein Flurstück aus,<br/>damit Kassenzeichen bestimmt werden können.</html > ");
        log.warn("Crossover: Kein  Flurstück ausgewählt kann Lagis Kassenzeichen nicht bestimmen");
      }
      return null;
    }

    @Override
    protected void done() {
      if (log.isDebugEnabled()) {
        log.debug("KassenzeichenRetriever done.");
      }
      super.done();
      if (isCancelled()) {
        if (log.isDebugEnabled()) {
          log.debug("Kassenzeichen retriever canceled.Nothing to do {}");
        }
      }
      try {
        Set<CidsBean> results = get();
        if (results == null) {
          results = new HashSet<CidsBean>();
          tableModel.updateTableModel(results);
          layout.show(panAll, MESSAGE_CARD_NAME);
        } else {
          tableModel.updateTableModel(results);
          layout.show(panAll, CONTENT_CARD_NAME);
        }
      } catch (Exception ex) {
        log.error("Fehler beim verarbeiten der Ergebnisse: ", ex);
        tableModel.updateTableModel(new HashSet<CidsBean>());
        lblMessage.setText("<html>Fehler beim abfragen<br/>der Kassenzeichen.< /html >");
        layout.show(panAll, MESSAGE_CARD_NAME);
      }
      VerdisCrossoverPanel.this.revalidate();
      VerdisCrossoverPanel.this.repaint();
      ((JDialog) getParent().getParent().getParent().getParent()).repaint();
    }
  }
}
/**
 * Main file for SerialDemo program. This program illustrates many of the abilities of the
 * javax.comm api. This file contains the GUI framework that the program runs in.
 */
public class SerialManager {

  private static final org.apache.log4j.Logger ezlink =
      org.apache.log4j.Logger.getLogger(SerialManager.class);
  private SerialParameters parameters;
  private SerialConnection connection;
  private Properties props = null;
  private static final String CONFIG_BUNDLE_NAME = "SMSConfig";
  static SerialManager serialDemo = null;

  /**
   * Main method. Checks to see if the command line agrument is requesting usage informaition (-h,
   * -help), if it is, display a usage message and exit, otherwise create a new <code>SerialDemo
   * </code> and set it visible.
   */
  public static void main(String[] args) {
    try {

      serialDemo = new SerialManager();
      ETerminalDataDto objETerminalDataDto =
          serialDemo.getDebitCmd(
              "DC7934737E93BE4F",
              "DC7934737E93BE4F",
              "FFFFFE",
              "0203000A820013881000130007177762B20D5307D50E3F3B24D01C4001FD1EFF75004E202556FBDA1E2088881C00A0FFFFFF2570016643544E3536323120550001000400005555000000000000000000000000000000000000000000000000AB273C2F13AFC9FB03F79059E20C3EC73BF7");

      // Commet this after testing with main method;
      // serialDemo.initConfig();
      // serialDemo.connection.sendMessage(ISOUtil.hex2byte("020079600037000002007024058000C10004164999770007848180000000000000011111011000100309020037003237303031393630313638313638313035323934202020000334343400063031313030320388"));
      /*	byte [] debitCommand = serialDemo.connection.sendMessage(ISOUtil.hex2byte(HeaderUtil.getReqHeader("DC7934737E93BE4F","DC7934737E93BE4F","FFFFFE","0203000A820013881000130007177762B20D5307D50E3F3B24D01C4001FD1EFF75004E202556FBDA1E2088881C00A0FFFFFF2570016643544E3536323120550001000400005555000000000000000000000000000000000000000000000000AB273C2F13AFC9FB03F79059E20C3EC73BF7")));
      System.out.println("Debit Command="+ ISOUtil.hexString(debitCommand));

      String strResSplit[] = ISOUtil.hexString(debitCommand).split("1C");
      for(int i=0;i<strResSplit.length;i++)
      {
      strResSplit[i] = strResSplit[i].substring(8);
      System.out.println(strResSplit[i]);
      }*/

      System.out.println("strDebitCmd " + objETerminalDataDto.getDebitCmd());

    } catch (Exception sExp) {
      System.out.println(sExp.getMessage());
    }
  }

  // public String getDebitCmd(String stCardRndNo, String stTerRndNo, String stAmt, String stPurse)
  // throws Exception {
  public ETerminalDataDto getDebitCmd(
      String stCardRndNo, String stTerRndNo, String stAmt, String stPurse) throws Exception {

    ETerminalDataDto objETerminalDataDto = new ETerminalDataDto();

    String strDebitCmd = "";
    String strResHeader = "";
    String strActDebitCmd = "";
    String strUserData = "";
    String strSignSessionKey = "";
    String strDebitSessionKey = "";
    String strRefno = "";
    String strEzlinkString = "";

    // String strDebitCmd=null;
    try {
      ezlink.info("\n-------SerialManager--------------START--------------------------------");
      ezlink.info("getDebitCmd Request received in " + SerialManager.class.getName());
      // Commet this after testing with main method;
      // serialDemo.initConfig()
      // serialDemo.connection.sendMessage(ISOUtil.hex2byte("020079600037000002007024058000C10004164999770007848180000000000000011111011000100309020037003237303031393630313638313638313035323934202020000334343400063031313030320388"));

      // Debit command
      byte[] debitCommand =
          connection.sendMessage(
              ISOUtil.hex2byte(HeaderUtil.getReqHeader(stCardRndNo, stTerRndNo, stAmt, stPurse)));
      System.out.println("Debit Command=" + ISOUtil.hexString(debitCommand));
      ezlink.info("Debit Command= : " + ISOUtil.hexString(debitCommand));

      /*
      byte[] recieptData = connection.sendMessage(ISOUtil.hex2byte(HeaderUtil.getReqRecieptData("EEF6BAADFDDB93685EC111ACD05D7133E9472DA4416D0C079000")));
      System.out.println("Reciept Data =" + ISOUtil.hexString(recieptData));
      ezlink.info("Reciept Data= : " + ISOUtil.hexString(recieptData));
      */
      // debitCommand =
      // ISOUtil.hex2byte("36303030303030303030313132303030301C343100165F332D39907B07D4C9C72441CF93C3461C3432000854495430303031201C3433001647058A8594B61B0707BD7794B3F7078D1C34340016134DBF682CD22C68A60D1F0E71F929D01C34350012DC7934737E93BE4FDC7934731C30303030303031313230303030");
      /*
      String[] strResSplit = ISOUtil.hexString(debitCommand).split("1C");

      for(int i=0;i<strResSplit.length;i++)
      {
      strResSplit[i] = strResSplit[i].substring(8);
      System.out.println(strResSplit[i]);
      ezlink.info("strResSplit [ "+i+" ]" + strResSplit[i]);
      }
      strDebitCmd = "250315021403"+stTerRndNo+strResSplit[1]+strResSplit[2];
      System.out.println("strDebitCmd= "+strDebitCmd +"  Len  "+strDebitCmd.length());
      ezlink.info("strDebitCmd= "+strDebitCmd+" Len : " + strDebitCmd.length());

      */
      // String strResponse = ISOUtil.hexString(recieptData);
      String strResponse = ISOUtil.hexString(debitCommand);
      ezlink.info("+++strResponse Length : " + strResponse.length());
      ezlink.info("+++strResponse  : " + strResponse);
      //          if (strResponse.length() == 222) {
      // ezlink.info("+++Inside IF  :
      // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" );
      /*
      //Old terminal
      strResHeader = strResponse.substring(0, 34);
      strActDebitCmd = strResponse.substring(44, 76);
      strUserData = strResponse.substring(86, 102);
      strSignSessionKey = strResponse.substring(112, 144);
      strDebitSessionKey = strResponse.substring(154, 186);
      strRefno = strResponse.substring(196, 220);
      */
      // New Terminal
      strResHeader = strResponse.substring(0, 34);
      strRefno = strResponse.substring(44, 68); // 24
      strActDebitCmd = strResponse.substring(78, 110); // 32
      strUserData = strResponse.substring(120, 136); // 16
      strSignSessionKey = strResponse.substring(146, 178); // 32
      strDebitSessionKey = strResponse.substring(188, 220); // 32

      strEzlinkString = strResponse.substring(230, strResponse.length() - 2);

      System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++");
      System.out.println("Last two digits: " + strResponse.substring(strResponse.length() - 2));
      System.out.println("Response length : " + strResponse.length());
      System.out.println("Response from terminal DC : " + strResponse);
      System.out.println("Ezlink String : " + strEzlinkString);
      System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++");

      ezlink.info("\n--------SERIAL MANAGER-------RESPONSE--------------------");
      ezlink.info("strResHeader : " + strResHeader);
      ezlink.info("strActDebitCmd : " + strActDebitCmd);
      ezlink.info("strUserData : " + strUserData);
      ezlink.info("strSignSessionKey : " + strSignSessionKey);
      ezlink.info("strDebitSessionKey : " + strDebitSessionKey);
      ezlink.info("strRefno : " + strRefno);
      ezlink.info("strEzlinkString : " + strEzlinkString);
      ezlink.info("\n--------SERIAL MANAGER-------RESPONSE--------------------");

      strDebitCmd = "250315021403" + stTerRndNo + strActDebitCmd + strUserData;
      System.out.println("strDebitCmd= " + strDebitCmd + "  Len  " + strDebitCmd.length());
      ezlink.info("strDebitCmd= " + strDebitCmd + " Len : " + strDebitCmd.length());

      objETerminalDataDto.setDebitCmd(strDebitCmd);
      objETerminalDataDto.setTerminalSessionKey(strSignSessionKey);
      objETerminalDataDto.setDebitSessionKey(strDebitSessionKey);
      objETerminalDataDto.setEzLinkString(strEzlinkString);
      /*
                  } else {
                      //ezlink.info("+++Inside IF  : ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" );
                      System.out.println("Response from the Terminal not received fully...");
                      ezlink.info("Response from the Terminal not received fully...!!!!!!!");
                  }
      */
    } catch (Exception exp) {
      System.out.println(exp);
      ezlink.error(new Object(), exp);
      throw exp;
    }
    // return strDebitCmd;
    return objETerminalDataDto;
  }

  /**
   * Create new <code>SerialDemo</code> and initilizes it. Parses args to find configuration file.
   * If found, initial state it set to parameters in configuration file.
   *
   * @param args command line arguments used when program was invoked.
   */
  public SerialManager(String commPort) throws SerialConnectionException {
    parameters = new SerialParameters();
    parameters.setPortName(commPort);
    connection = new SerialConnection(this, parameters);
    initConfig();
  }

  public SerialManager() throws SerialConnectionException {
    parameters = new SerialParameters();
    connection = new SerialConnection(this, parameters);
    initConfig();
  }

  public String getCommPort() {
    return parameters.getPortName();
  }

  /** Responds to the menu items and buttons. */
  private void initConfig() throws SerialConnectionException {
    loadParams();
    openConnection();
  }

  /**
   * Opening Connection to the serial port.first check whether port is open if not create new
   * connection to the port.
   */
  private void openConnection() {
    try {
      if (connection.isOpen()) {
        System.out.println("Port Open!,Can't open a new connection while a port is open.");
        ezlink.info("Port Open!,Can't open a new connection while a port is open : ");
      }

      connection.openConnection();
    } catch (SerialConnectionException e2) {
      System.out.println(e2);
      ezlink.error(new Object(), e2);
    }
  }

  public byte[] sendAndReceiveData(byte[] requestData) {
    byte[] response = connection.sendMessage(requestData);
    System.out.println("In SerialManager");
    ezlink.info("In SerialManager : ");
    return response;
  }

  // Sends a break signal to the port.
  private void sendBreak() {
    connection.sendBreak();
  }

  /** Cleanly shuts down the applicaion. first closes any open ports and cleans up, then exits. */
  public void shutdown() {
    connection.closeConnection();
    // System.exit(1);
  }

  /** Set the parameters object to the settings in the properties object. */
  private void loadParams() throws SerialConnectionException {

    try {
      PropertyResourceBundle props =
          (PropertyResourceBundle) PropertyResourceBundle.getBundle(CONFIG_BUNDLE_NAME);
      System.out.println("BaudRate=" + props.getString("baudRate"));

      ezlink.info("BaudRate= : " + props.getString("baudRate"));

      parameters.setBaudRate(props.getString("baudRate"));
      parameters.setFlowControlIn(props.getString("flowControlIn"));
      parameters.setFlowControlOut(props.getString("flowControlOut"));
      parameters.setParity(props.getString("parity"));
      parameters.setDatabits(props.getString("databits"));
      parameters.setStopbits(props.getString("stopbits"));
      parameters.setPIN(props.getString("pin"));
      parameters.setSMC(props.getString("smc"));

      parameters.setDriver(props.getString("driver"));
      parameters.setURL(props.getString("url"));
      parameters.setUserName(props.getString("username"));
      parameters.setPassword(props.getString("password"));
      parameters.setPortName(props.getString("portName"));

    } catch (Exception exp) {
      ezlink.info("+++Error While setting parameters : +++");
      ezlink.error(new Object(), exp);
      throw new SerialConnectionException("Error While setting parameters=" + exp.getMessage());
    }
  }
  // --------------------------getDecryptedRecieptData-------------------------------------------------------------
  // public String getDebitCmd(String stCardRndNo, String stTerRndNo, String stAmt, String stPurse)
  // throws Exception {
  public String getDecryptedRecieptData(ETerminalDataDto objETerminalDataDto) throws Exception {

    // ETerminalDataDto objETerminalDataDto=new ETerminalDataDto();

    String strDecryptedRecieptDataRefNo = "";
    String strDecryptedRecieptData = "";
    String strResHeader = "";

    // String strDebitCmd=null;
    try {
      ezlink.info(
          "\n-------SerialManager--------------START----4 decrypting RecieptData-------------------");
      ezlink.info("getDecryptedRecieptData Request received in " + SerialManager.class.getName());
      // Commet this after testing with main method;
      // serialDemo.initConfig()
      // serialDemo.connection.sendMessage(ISOUtil.hex2byte("020079600037000002007024058000C10004164999770007848180000000000000011111011000100309020037003237303031393630313638313638313035323934202020000334343400063031313030320388"));

      // Debit command
      byte[] decRecieptData = null;
      try {
        decRecieptData =
            connection.sendMessage(
                ISOUtil.hex2byte(
                    HeaderUtil.getReqRecieptData(
                        objETerminalDataDto.getRecieptData(),
                        objETerminalDataDto.getTerminalSessionKey(),
                        objETerminalDataDto.getDebitSessionKey(),
                        objETerminalDataDto.getCan(),
                        objETerminalDataDto.getEzLinkString(),
                        "")));
      } catch (Exception e) {
        e.printStackTrace();
      }
      System.out.println("Decrypted Reciept Data=" + ISOUtil.hexString(decRecieptData));
      ezlink.info("Decrypted Reciept Data= : " + ISOUtil.hexString(decRecieptData));
      String strResponse = ISOUtil.hexString(decRecieptData);
      ezlink.info("+++Decrypted Reciept Data strResponse Length : " + strResponse.length());
      ezlink.info("+++Decrypted Reciept Data strResponse  : " + strResponse);
      //          if (strResponse.length() == 222) {
      // ezlink.info("+++Inside IF  :
      // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" );

      strResHeader = strResponse.substring(0, 34);
      strDecryptedRecieptDataRefNo = strResponse.substring(44, 68); // 24

      strDecryptedRecieptData = strResponse.substring(78, strResponse.length() - 2);

      System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++");
      System.out.println("Last two digits: " + strResponse.substring(strResponse.length() - 2));
      System.out.println("Response length : " + strResponse.length());
      System.out.println("Response from terminal DC : " + strResponse);
      System.out.println("Decrypted Ezlink String : " + strDecryptedRecieptData);
      System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++");

      ezlink.info(
          "\n--------SERIAL MANAGER-------RESPONSE----4DecryptedRecieptData----------------");
      ezlink.info("strResHeader : " + strResHeader);

      ezlink.info("strDecryptedRecieptDataRefNo : " + strDecryptedRecieptDataRefNo);
      ezlink.info("strDecryptedRecieptData : " + strDecryptedRecieptData);
      ezlink.info("\n--------SERIAL MANAGER-------RESPONSE--------------------");

      // strDebitCmd = "250315021403" + stTerRndNo + strActDebitCmd + strUserData;
      // System.out.println("strDebitCmd= " + strDebitCmd + "  Len  " + strDebitCmd.length());
      // ezlink.info("strDebitCmd= " + strDebitCmd + " Len : " + strDebitCmd.length());

      /*
                  } else {
                      //ezlink.info("+++Inside IF  : ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" );
                      System.out.println("Response from the Terminal not received fully...");
                      ezlink.info("Response from the Terminal not received fully...!!!!!!!");
                  }
      */
    } catch (Exception exp) {
      System.out.println(exp);
      ezlink.error(new Object(), exp);
      throw exp;
    }

    return strDecryptedRecieptData;
  }
}