예제 #1
0
 /**
  * A utility method to make a name=value part of the adde request string
  *
  * @param buf The buffer to append to
  * @param name The property name
  * @param value The value
  */
 protected void appendKeyValue(StringBuffer buf, String name, String value) {
   if ((buf.length() == 0) || (buf.charAt(buf.length() - 1) != '?')) {
     buf.append("&");
   }
   buf.append(name);
   buf.append("=");
   buf.append(value);
 }
예제 #2
0
  private void onReceiveChar(char character) {

    buffer.append(character);

    if (buffer.charAt(buffer.length() - 1) == '\n') {
      onReceiveLine(buffer.toString());
      buffer.delete(0, buffer.length());
    }
  }
예제 #3
0
    public void run() {
      StringBuffer data = new StringBuffer();
      Print.logDebug("Client:InputThread started");

      while (true) {
        data.setLength(0);
        boolean timeout = false;
        try {
          if (this.readTimeout > 0L) {
            this.socket.setSoTimeout((int) this.readTimeout);
          }
          ClientSocketThread.socketReadLine(this.socket, -1, data);
        } catch (InterruptedIOException ee) { // SocketTimeoutException ee) {
          // error("Read interrupted (timeout) ...");
          if (getRunStatus() != THREAD_RUNNING) {
            break;
          }
          timeout = true;
          // continue;
        } catch (Throwable t) {
          Print.logError("Client:InputThread - " + t);
          t.printStackTrace();
          break;
        }
        if (!timeout || (data.length() > 0)) {
          ClientSocketThread.this.handleMessage(data.toString());
        }
      }

      synchronized (this.threadLock) {
        this.isRunning = false;
        Print.logDebug("Client:InputThread stopped");
        this.threadLock.notify();
      }
    }
예제 #4
0
    /**
     * Create a Transferable to use as the source for a data transfer.
     *
     * @param c The component holding the data to be transfered. This argument is provided to enable
     *     sharing of TransferHandlers by multiple components.
     * @return The representation of the data to be transfered.
     */
    protected Transferable createTransferable(JComponent c) {
      Object[] values = null;
      if (c instanceof JList) {
        values = ((JList) c).getSelectedValues();
      } else if (c instanceof JTable) {
        JTable table = (JTable) c;
        int[] rows = table.getSelectedRows();
        if (rows != null) {
          values = new Object[rows.length];
          for (int i = 0; i < rows.length; i++) {
            values[i] = table.getValueAt(rows[i], 0);
          }
        }
      }
      if (values == null || values.length == 0) {
        return null;
      }

      StringBuffer plainBuf = new StringBuffer();
      StringBuffer htmlBuf = new StringBuffer();

      htmlBuf.append("<html>\n<body>\n<ul>\n");

      for (Object obj : values) {
        String val = ((obj == null) ? "" : obj.toString());
        plainBuf.append(val + "\n");
        htmlBuf.append("  <li>" + val + "\n");
      }

      // remove the last newline
      plainBuf.deleteCharAt(plainBuf.length() - 1);
      htmlBuf.append("</ul>\n</body>\n</html>");

      return new FileTransferable(plainBuf.toString(), htmlBuf.toString(), values);
    }
예제 #5
0
  void applyDirectives() {
    findRemoveDirectives(true);

    StringBuffer buffer = new StringBuffer();
    String head = "", toe = "; \n";

    if (crispBox.isSelected()) buffer.append(head + "crisp=true" + toe);
    if (!fontField.getText().trim().equals(""))
      buffer.append(head + "font=\"" + fontField.getText().trim() + "\"" + toe);
    if (globalKeyEventsBox.isSelected()) buffer.append(head + "globalKeyEvents=true" + toe);
    if (pauseOnBlurBox.isSelected()) buffer.append(head + "pauseOnBlur=true" + toe);
    if (!preloadField.getText().trim().equals(""))
      buffer.append(head + "preload=\"" + preloadField.getText().trim() + "\"" + toe);
    /*if ( transparentBox.isSelected() )
    buffer.append( head + "transparent=true" + toe );*/

    Sketch sketch = editor.getSketch();
    SketchCode code = sketch.getCode(0); // first tab
    if (buffer.length() > 0) {
      code.setProgram("/* @pjs " + buffer.toString() + " */\n\n" + code.getProgram());
      if (sketch.getCurrentCode() == code) // update textarea if on first tab
      {
        editor.setText(sketch.getCurrentCode().getProgram());
        editor.setSelection(0, 0);
      }

      sketch.setModified(false);
      sketch.setModified(true);
    }
  }
  /** EdiDialog constructor comment. */
  public void keyReleased(java.awt.event.KeyEvent e) {
    if (e.getSource() == list) {
      switch (e.getKeyCode()) {
        case KeyEvent.VK_DELETE:
        case KeyEvent.VK_BACK_SPACE:
          if (keys.length() > 0) keys.setLength(keys.length() - 1);
          break;
        case KeyEvent.VK_ESCAPE:
          dispose();
          break;
        case KeyEvent.VK_ENTER:
          dispose();
          actionOK();
          break;
        case KeyEvent.VK_SPACE:
          actionAdd();
          break;
        default:
          // keys.append((char) e.getKeyChar());
          list.ensureIndexIsVisible(list.getSelectedIndex());
      }

      //		if (debug)
      //			System.out.println("keys: " + keys);
      return;
    }

    switch (e.getKeyCode()) {
      case KeyEvent.VK_ENTER:
      case KeyEvent.VK_ESCAPE:
        dispose();
        break;
      default:
        break;
    }

    super.keyReleased(e);
  }
예제 #7
0
  /**
   * Construct an appropriate external representation of the object and write it to a file. Errors
   * are returned by throwing an IOException containing the cause of the problem as its message.
   *
   * <p>DataType is responsible for validating that the given text text from a Popup JTextArea can
   * be converted to an object. This text-to-object conversion is the same as
   * validateAndConvertInPopup, which may be used internally by the object to do the validation.
   *
   * <p>The DataType object must flush and close the output stream before returning. Typically it
   * will create another object (e.g. an OutputWriter), and that is the object that must be flushed
   * and closed.
   *
   * <p>File is assumed to be and ASCII string of digits representing a value of this data type.
   */
  public void exportObject(FileOutputStream outStream, String text) throws IOException {

    OutputStreamWriter outWriter = new OutputStreamWriter(outStream);

    // check that the text is a valid representation
    StringBuffer messageBuffer = new StringBuffer();
    validateAndConvertInPopup(text, null, messageBuffer);
    if (messageBuffer.length() > 0) {
      // there was an error in the conversion
      throw new IOException(new String(messageBuffer));
    }

    // just send the text to the output file
    outWriter.write(text);
    outWriter.flush();
    outWriter.close();
  }
예제 #8
0
  /**
   * Get a default value for the table used to input data for a new row to be inserted into the DB.
   */
  public Object getDefaultValue(String dbDefaultValue) {
    if (dbDefaultValue != null) {
      // try to use the DB default value
      StringBuffer mbuf = new StringBuffer();
      Object newObject = validateAndConvert(dbDefaultValue, null, mbuf);

      // if there was a problem with converting, then just fall through
      // and continue as if there was no default given in the DB.
      // Otherwise, use the converted object
      if (mbuf.length() == 0) return newObject;
    }

    // no default in DB.  If nullable, use null.
    if (_isNullable) return null;

    // field is not nullable, so create a reasonable default value
    return new Time(new java.util.Date().getTime());
  }
예제 #9
0
  /**
   * Read a file and construct a valid object from its contents. Errors are returned by throwing an
   * IOException containing the cause of the problem as its message.
   *
   * <p>DataType is responsible for validating that the imported data can be converted to an object,
   * and then must return a text string that can be used in the Popup window text area. This
   * object-to-text conversion is the same as is done by the DataType object internally in the
   * getJTextArea() method.
   *
   * <p>File is assumed to be and ASCII string of digits representing a value of this data type.
   */
  public String importObject(FileInputStream inStream) throws IOException {

    InputStreamReader inReader = new InputStreamReader(inStream);

    int fileSize = inStream.available();

    char charBuf[] = new char[fileSize];

    int count = inReader.read(charBuf, 0, fileSize);

    if (count != fileSize)
      throw new IOException(
          "Could read only "
              + count
              + " chars from a total file size of "
              + fileSize
              + ". Import failed.");

    // convert file text into a string
    // Special case: some systems tack a newline at the end of
    // the text read.  Assume that if last char is a newline that
    // we want everything else in the line.
    String fileText;
    if (charBuf[count - 1] == KeyEvent.VK_ENTER) fileText = new String(charBuf, 0, count - 1);
    else fileText = new String(charBuf);

    // test that the string is valid by converting it into an
    // object of this data type
    StringBuffer messageBuffer = new StringBuffer();
    validateAndConvertInPopup(fileText, null, messageBuffer);
    if (messageBuffer.length() > 0) {
      // convert number conversion issue into IO issue for consistancy
      throw new IOException(
          "Text does not represent data of type " + getClassName() + ".  Text was:\n" + fileText);
    }

    // return the text from the file since it does
    // represent a valid data value
    return fileText;
  }
예제 #10
0
  /**
   * Searches the contact list when any key, different from "space", "+" or "-" is typed. Selects
   * the Contact name closest to the typed string. The time between two button presses is checked to
   * determine whether the user makes a new search or a continuous search. When user types the same
   * letter consecutively the search mechanism selects the next Contact name starting with the same
   * letter.
   */
  public void keyTyped(KeyEvent e) {

    // Nothing to do if the contact list is empty
    if (contactList.getModel().getSize() <= 0) return;

    long eventTimestamp = e.getWhen();
    char keyChar = e.getKeyChar();

    if (keyChar == ' ') {
      openOrCloseGroup();
    } else if (keyChar == '+') {
      openGroup();
    } else if (keyChar == '-') {
      closeGroup();
    } else {

      if ((lastTypedTimestamp - eventTimestamp) > 1000) {
        keyBuffer.delete(0, keyBuffer.length() - 1);
      }
      this.lastTypedTimestamp = eventTimestamp;
      this.keyBuffer.append(keyChar);

      boolean selectedSameLetterContact = false;

      int selectedIndex = this.contactList.getSelectedIndex();

      // Check if there's any selected contact node and get its name.
      if (selectedIndex != -1) {
        Object selectedObject = this.contactList.getSelectedValue();

        if (selectedObject instanceof MetaContact) {
          String selectedContactName = ((MetaContact) selectedObject).getDisplayName();

          if (selectedContactName != null) {
            selectedSameLetterContact =
                selectedContactName.substring(0, 1).equalsIgnoreCase(keyBuffer.toString());
          }
        } else if (selectedObject instanceof ConferenceChatContact) {
          String selectedContactName = ((ConferenceChatContact) selectedObject).getName();

          if (selectedContactName != null) {
            selectedSameLetterContact =
                selectedContactName.substring(0, 1).equalsIgnoreCase(keyBuffer.toString());
          }
        }
      }
      // The search starts from the beginning if:
      // 1) the newly entered character is different from the last one
      // or
      // 2) the currently selected contact starts with a different letter
      int contactIndex =
          contactList.getNextMatch(
              keyBuffer.toString(),
              (lastTypedKey != keyChar || !selectedSameLetterContact) ? 0 : selectedIndex + 1,
              Position.Bias.Forward);

      int currentlySelectedIndex = this.contactList.getSelectedIndex();

      if (currentlySelectedIndex != contactIndex && contactIndex != -1) {
        this.contactList.setSelectedIndex(contactIndex);
        currentlySelectedIndex = contactList.getSelectedIndex();
      }

      this.contactList.ensureIndexIsVisible(currentlySelectedIndex);

      this.lastTypedKey = keyChar;
    }
  }
예제 #11
0
  // The main procedure
  public static void main(String args[]) {
    String s;

    initGUI();

    while (true) {
      try { // Poll every ~10 ms
        Thread.sleep(10);
      } catch (InterruptedException e) {
      }

      switch (connectionStatus) {
        case BEGIN_CONNECT:
          try {
            // Try to set up a server if host
            if (isHost) {
              hostServer = new ServerSocket(port);
              socket = hostServer.accept();
            }

            // If guest, try to connect to the server
            else {
              socket = new Socket(hostIP, port);
            }

            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            changeStatusTS(CONNECTED, true);
          }
          // If error, clean up and output an error message
          catch (IOException e) {
            cleanUp();
            changeStatusTS(DISCONNECTED, false);
          }
          break;

        case CONNECTED:
          try {
            // Send data
            if (toSend.length() != 0) {
              out.print(toSend);
              out.flush();
              toSend.setLength(0);
              changeStatusTS(NULL, true);
            }

            // Receive data
            if (in.ready()) {
              s = in.readLine();
              if ((s != null) && (s.length() != 0)) {
                // Check if it is the end of a trasmission
                if (s.equals(END_CHAT_SESSION)) {
                  changeStatusTS(DISCONNECTING, true);
                }

                // Otherwise, receive what text
                else {
                  appendToChatBox("INCOMING: " + s + "\n");
                  changeStatusTS(NULL, true);
                }
              }
            }
          } catch (IOException e) {
            cleanUp();
            changeStatusTS(DISCONNECTED, false);
          }
          break;

        case DISCONNECTING:
          // Tell other chatter to disconnect as well
          out.print(END_CHAT_SESSION);
          out.flush();

          // Clean up (close all streams/sockets)
          cleanUp();
          changeStatusTS(DISCONNECTED, true);
          break;

        default:
          break; // do nothing
      }
    }
  }
 /** Reflow XML */
 public void doFormat() {
   Vector parts = new Vector();
   char[] chars = original.toCharArray();
   int index = 0;
   int first = 0;
   String part = null;
   while (index < chars.length) {
     // Check for start of tag
     if (chars[index] == '<') {
       // Did we have data before this tag?
       if (first < index) {
         part = new String(chars, first, index - first);
         part = part.trim();
         // Save non-whitespace data
         if (part.length() > 0) {
           parts.addElement(part);
         }
       }
       // Save the start of tag
       first = index;
     }
     // Check for end of tag
     if (chars[index] == '>') {
       // Save the tag
       part = new String(chars, first, index - first + 1);
       parts.addElement(part);
       first = index + 1;
     }
     // Check for end of line
     if ((chars[index] == '\n') || (chars[index] == '\r')) {
       // Was there data on this line?
       if (first < index) {
         part = new String(chars, first, index - first);
         part = part.trim();
         // Save non-whitespace data
         if (part.length() > 0) {
           parts.addElement(part);
         }
       }
       first = index + 1;
     }
     index++;
   }
   // Reflow as XML
   StringBuffer buf = new StringBuffer();
   Object[] list = parts.toArray();
   int indent = 0;
   int pad = 0;
   index = 0;
   while (index < list.length) {
     part = (String) list[index];
     if (buf.length() == 0) {
       // Just add first tag (should be XML header)
       buf.append(part);
     } else {
       // All other parts need to start on a new line
       buf.append('\n');
       // If we're at an end tag then decrease indent
       if (part.startsWith("</")) {
         indent--;
       }
       // Add any indent
       for (pad = 0; pad < indent; pad++) {
         buf.append("  ");
       }
       // Add the tag or data
       buf.append(part);
       // If this is a start tag then increase indent
       if (part.startsWith("<") && !part.startsWith("</") && !part.endsWith("/>")) {
         indent++;
         // Check for special <tag>data</tag> case
         if ((index + 2) < list.length) {
           part = (String) list[index + 2];
           if (part.startsWith("</")) {
             part = (String) list[index + 1];
             if (!part.startsWith("<")) {
               buf.append(part);
               part = (String) list[index + 2];
               buf.append(part);
               index = index + 2;
               indent--;
             }
           }
         }
       }
     }
     index++;
   }
   formatted = new String(buf);
 }
예제 #13
0
    /** Reads the file, and sets the label and the values in the hashmap. */
    protected void setHM(String strPath, HashMap hmPnl) {
      BufferedReader reader = WFileUtil.openReadFile(strPath);
      boolean bFileEmpty = true;
      boolean bPart11Pnl = isPart11Pnl();
      boolean bDefaultFile = isDefaultFile();

      // if the file is empty, then create an empty set of textfields.
      if (reader == null) {
        // displayNewTxf("","");
        return;
      }

      String strLine = null;
      StringTokenizer strTok;

      try {
        // read the file, and create a new set of textfields,
        // with the values from the file.
        while ((strLine = reader.readLine()) != null) {
          String strLabel = "";
          String strValue = "";
          bFileEmpty = false;

          if (strLine.startsWith("#")
              || strLine.startsWith("@")
              || strLine.startsWith("%")
              || strLine.startsWith("\"@")) continue;

          if (strLine.startsWith("\"")) strTok = new StringTokenizer(strLine, "\"");
          else strTok = new StringTokenizer(strLine, File.pathSeparator + ",\n");

          if (!strTok.hasMoreTokens()) continue;

          strLabel = strTok.nextToken();

          // the format for the part11 Default file is a little different
          // only parse out the part11Dir, and don't display other defaults
          if (bPart11Pnl && bDefaultFile) {
            if (!strLabel.equalsIgnoreCase("part11Dir")) continue;
          }

          if (strTok.hasMoreTokens()) {
            while (strTok.hasMoreTokens()) {
              strValue += strTok.nextToken();
              if (strTok.hasMoreTokens()) strValue += " ";
            }
          }

          // append "/data/$name" to part11Dir
          if (bPart11Pnl && bDefaultFile && strLabel.equalsIgnoreCase("part11Dir")) {
            StringBuffer sbDir = new StringBuffer(strValue);
            if (sbDir.lastIndexOf(File.separator) < sbDir.length() - 1)
              sbDir.append(File.separator);
            sbDir.append("data" + File.separator + "$");
            sbDir.append(WGlobal.NAME);
            strValue = sbDir.toString();
          }

          // displayNewTxf(strLabel, strValue);
          if (strLabel != null && strLabel.trim().length() > 0) hmPnl.put(strLabel, strValue);
        }
        reader.close();
      } catch (Exception e) {
        Messages.writeStackTrace(e);
        // e.printStackTrace();
        Messages.postDebug(e.toString());
      }
    }
예제 #14
0
 private void addParam(StringBuffer s, String par) {
   if (s.length() > 0) s.append("; ");
   s.append(par);
 }