Esempio n. 1
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);
    }
Esempio n. 2
0
  protected String gettitle(String strFreq) {
    StringBuffer sbufTitle = new StringBuffer().append("VnmrJ  ");
    String strPath = FileUtil.openPath(FileUtil.SYS_VNMR + "/vnmrrev");
    BufferedReader reader = WFileUtil.openReadFile(strPath);
    String strLine;
    String strtype = "";
    if (reader == null) return sbufTitle.toString();

    try {
      while ((strLine = reader.readLine()) != null) {
        strtype = strLine;
      }
      strtype = strtype.trim();
      if (strtype.equals("merc")) strtype = "Mercury";
      else if (strtype.equals("mercvx")) strtype = "Mercury-Vx";
      else if (strtype.equals("mercplus")) strtype = "MERCURY plus";
      else if (strtype.equals("inova")) strtype = "INOVA";
      String strHostName = m_strHostname;
      if (strHostName == null) strHostName = "";
      sbufTitle.append("    ").append(strHostName);
      sbufTitle.append("    ").append(strtype);
      sbufTitle.append(" - ").append(strFreq);
      reader.close();
    } catch (Exception e) {
      // e.printStackTrace();
      Messages.logError(e.toString());
    }

    return sbufTitle.toString();
  }
Esempio n. 3
0
 private ClassLoaderStrategy getClassLoaderStrategy(String fullyQualifiedClassName)
     throws Exception {
   try {
     // Get just the package name
     StringBuffer sb = new StringBuffer(fullyQualifiedClassName);
     sb.delete(sb.lastIndexOf("."), sb.length());
     currentPackage = sb.toString();
     // Retrieve the Java classpath from the system properties
     String cp = System.getProperty("java.class.path");
     String sepChar = System.getProperty("path.separator");
     String[] paths = StringUtils.pieceList(cp, sepChar.charAt(0));
     ClassLoaderStrategy cl =
         ClassLoaderUtil.getClassLoader(ClassLoaderUtil.FILE_SYSTEM_CLASS_LOADER, new String[] {});
     // Iterate through paths until class with the specified name is found
     String classpath = StringUtils.replaceChar(currentPackage, '.', File.separatorChar);
     for (int i = 0; i < paths.length; i++) {
       Class[] classes = cl.getClasses(paths[i] + File.separatorChar + classpath, currentPackage);
       for (int j = 0; j < classes.length; j++) {
         if (classes[j].getName().equals(fullyQualifiedClassName)) {
           return ClassLoaderUtil.getClassLoader(
               ClassLoaderUtil.FILE_SYSTEM_CLASS_LOADER, new String[] {paths[i]});
         }
       }
     }
     throw new Exception("Class could not be found.");
   } catch (Exception e) {
     System.err.println("Exception creating class loader strategy.");
     System.err.println(e.getMessage());
     throw e;
   }
 }
Esempio n. 4
0
 /**
  * Check if the server is ok
  *
  * @return status code
  */
 protected int checkIfServerIsOk() {
   try {
     StringBuffer buff = getUrl(REQ_TEXT);
     appendKeyValue(buff, PROP_FILE, FILE_PUBLICSRV);
     URL url = new URL(buff.toString());
     URLConnection urlc = url.openConnection();
     InputStream is = urlc.getInputStream();
     is.close();
     return STATUS_OK;
   } catch (AddeURLException ae) {
     String aes = ae.toString();
     if (aes.indexOf("Invalid project number") >= 0) {
       LogUtil.userErrorMessage("Invalid project number");
       return STATUS_NEEDSLOGIN;
     }
     if (aes.indexOf("Invalid user id") >= 0) {
       LogUtil.userErrorMessage("Invalid user ID");
       return STATUS_NEEDSLOGIN;
     }
     if (aes.indexOf("Accounting data") >= 0) {
       return STATUS_NEEDSLOGIN;
     }
     if (aes.indexOf("cannot run server 'txtgserv") >= 0) {
       return STATUS_OK;
     }
     LogUtil.userErrorMessage("Error connecting to server. " + ae.getMessage());
     return STATUS_ERROR;
   } catch (Exception exc) {
     logException("Connecting to server:" + getServer(), exc);
     return STATUS_ERROR;
   }
 }
 // -----------------------------------
 public static String array2string(String[] sa) {
   StringBuffer sb = new StringBuffer(255);
   if (sa != null)
     for (int i = 0; i < sa.length; i++) {
       sb.append(sa[i] + " "); // NOI18N
     }
   return new String(sb);
 }
 // -------------------------------------------
 public static String toSpaceSeparatedString(Vector v) {
   StringBuffer sb = new StringBuffer(30);
   for (int i = 0; i < v.size(); i++) {
     Object o = v.elementAt(i);
     sb.append(" " + o); // NOI18N
   }
   return new String(sb);
 }
Esempio n. 7
0
 public String getPropertyName(String name) {
   // Set the first letter of the property name to lower-case
   StringBuffer propertyName = new StringBuffer(name);
   char c = propertyName.charAt(0);
   if (c >= 'A' && c <= 'Z') {
     c -= 'A' - 'a';
     propertyName.setCharAt(0, c);
   }
   return propertyName.toString();
 }
 // -------------------------------------------
 public static String replaceBackslashDollars(String s) {
   int len = s.length();
   StringBuffer sb = new StringBuffer(len);
   for (int i = 0; i < len; i++) {
     char c = s.charAt(i);
     if ((c == '\\') && (i < len - 1) && ('$' == s.charAt(i + 1))) {
       continue;
     }
     sb.append(c);
   }
   return new String(sb);
 }
 // -------------------------------------------
 public static String arrayToSpaceSeparatedString(String[] sa) {
   if (sa == null) {
     return ""; // NOI18N
   }
   StringBuffer sb = new StringBuffer();
   for (int i = 0; i < sa.length; i++) {
     if (sa[i] == null) sa[i] = ""; // NOI18N
     sb.append(sa[i]);
     if (i < sa.length - 1) {
       sb.append(" "); // NOI18N
     }
   }
   return new String(sb);
 }
Esempio n. 10
0
 // Dump the content of this bean returning it as a String
 public void dump(StringBuffer str, String indent) {
   String s;
   Object o;
   org.netbeans.modules.schema2beans.BaseBean n;
   str.append(indent);
   str.append("FileEntry[" + this.sizeFileEntry() + "]"); // NOI18N
   for (int i = 0; i < this.sizeFileEntry(); i++) {
     str.append(indent + "\t");
     str.append("#" + i + ":");
     n = (org.netbeans.modules.schema2beans.BaseBean) this.getFileEntry(i);
     if (n != null) n.dump(str, indent + "\t"); // NOI18N
     else str.append(indent + "\tnull"); // NOI18N
     this.dumpAttributes(FILE_ENTRY, i, str, indent);
   }
 }
Esempio n. 11
0
    protected void writeAuditTrail(String strPath, String strUser, StringBuffer sbValues) {
      BufferedReader reader = WFileUtil.openReadFile(strPath);
      String strLine;
      ArrayList aListData = WUtil.strToAList(sbValues.toString(), false, "\n");
      StringBuffer sbData = sbValues;
      String strPnl = (this instanceof DisplayTemplate) ? "Data Template " : "Data Dir ";
      if (reader == null) {
        Messages.postDebug("Error opening file " + strPath);
        return;
      }

      try {
        while ((strLine = reader.readLine()) != null) {
          // if the line in the file is not in the arraylist,
          // then that line has been deleted
          if (!aListData.contains(strLine))
            WUserUtil.writeAuditTrail(new Date(), strUser, "Deleted " + strPnl + strLine);

          // remove the lines that are also in the file or those which
          // have been deleted.
          aListData.remove(strLine);
        }

        // Traverse through the remaining new lines in the arraylist,
        // and write it to the audit trail
        for (int i = 0; i < aListData.size(); i++) {
          strLine = (String) aListData.get(i);
          WUserUtil.writeAuditTrail(new Date(), strUser, "Added " + strPnl + strLine);
        }
        reader.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
Esempio n. 12
0
 // -------------------------------------------
 public static String arrayToString(String[] sa) {
   if (sa == null) {
     return ""; // NOI18N
   }
   StringBuffer sb = new StringBuffer();
   sb.append("["); // NOI18N
   for (int i = 0; i < sa.length; i++) {
     if (sa[i] == null) sa[i] = ""; // NOI18N
     sb.append(sa[i]);
     if (i < sa.length - 1) {
       sb.append(","); // NOI18N
     }
   }
   sb.append("]"); // NOI18N
   return new String(sb);
 }
Esempio n. 13
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);
 }
  /**
   * Attempts to insert a string into the document. Produces a system beep if the input does not
   * represent a positive (or zero) integer.
   */
  public void insertString(int offset, String str, AttributeSet a) throws BadLocationException {
    StringBuffer intString;

    // Ignore zero-length and null strings
    if (str == null || str.length() == 0) return;

    intString = new StringBuffer(getText(0, getLength()));
    intString.insert(offset, str);

    try {
      int theInt = new Integer(intString.toString()).intValue();
      if (theInt < 0 || !allowZero && theInt == 0) {
        throw new NumberFormatException();
      }
      super.insertString(offset, str, a);
    } catch (NumberFormatException e) {
      Toolkit.getDefaultToolkit().beep();
    }
  }
Esempio n. 15
0
 /**
  * Read the groups from the public.srv file on the server
  *
  * @return List of groups
  */
 protected List readGroups() {
   List groups = new ArrayList();
   try {
     String dataType = getDataType();
     String type = ((dataType.length() > 0) ? "TYPE=" + dataType : "TYPE=NOTYPE");
     StringBuffer buff = getUrl(REQ_TEXT);
     appendKeyValue(buff, PROP_FILE, FILE_PUBLICSRV);
     List lines = readTextLines(buff.toString());
     //            System.err.println ("lines:" + StringUtil.join("\n",lines));
     if (lines == null) {
       return null;
     }
     Hashtable seen = new Hashtable();
     for (int i = 0; i < lines.size(); i++) {
       String line = lines.get(i).toString();
       if (line.indexOf(type) < 0) {
         continue;
       }
       List toks = StringUtil.split(line, ",", true, true);
       if (toks.size() == 0) {
         continue;
       }
       String tok = (String) toks.get(0);
       int idx = tok.indexOf("=");
       if (idx < 0) {
         continue;
       }
       if (!tok.substring(0, idx).trim().equals("N1")) {
         continue;
       }
       String group = tok.substring(idx + 1).trim();
       if (seen.get(group) != null) {
         continue;
       }
       seen.put(group, group);
       groups.add(group);
     }
   } catch (Exception e) {
     return null;
   }
   return groups;
 }
Esempio n. 16
0
 /** Set the label text. */
 private void setLabelText() {
   if (!active) {
     return;
   }
   StringBuffer buf = new StringBuffer();
   buf.append(" ");
   buf.append(getRangeName());
   buf.append(": ");
   buf.append(StringUtil.padLeft(rangeReadout.getNumericString(), 6));
   buf.append(" ");
   buf.append(getBearingName());
   buf.append(": ");
   buf.append(StringUtil.padLeft(bearingReadout.getNumericString(), 6));
   String text = buf.toString();
   valueDisplay.setText(text);
   if (myOwnLabel) {
     FontMetrics fm = valueDisplay.getFontMetrics(valueDisplay.getFont());
     valueDisplay.setPreferredSize(new Dimension(fm.stringWidth(text), fm.getHeight()));
   }
 }
  /** Add import statements to the current tab for all of packages inside the specified jar file. */
  public void handleImportLibrary(String jarPath) {
    // make sure the user didn't hide the sketch folder
    sketch.ensureExistence();

    // import statements into the main sketch file (code[0])
    // if the current code is a .java file, insert into current
    // if (current.flavor == PDE) {
    if (mode.isDefaultExtension(sketch.getCurrentCode())) {
      sketch.setCurrentCode(0);
    }

    // could also scan the text in the file to see if each import
    // statement is already in there, but if the user has the import
    // commented out, then this will be a problem.
    String[] list = Base.packageListFromClassPath(jarPath);
    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < list.length; i++) {
      buffer.append("import ");
      buffer.append(list[i]);
      buffer.append(".*;\n");
    }
    buffer.append('\n');
    buffer.append(getText());
    setText(buffer.toString());
    setSelection(0, 0); // scroll to start
    sketch.setModified(true);
  }
Esempio n. 18
0
  // Dump the content of this bean returning it as a String
  public void dump(StringBuffer str, String indent) {
    String s;
    Object o;
    org.netbeans.modules.schema2beans.BaseBean n;
    str.append(indent);
    str.append("PropertyOne"); // NOI18N
    str.append(indent + "\t"); // NOI18N
    str.append("<"); // NOI18N
    s = this.getPropertyOne();
    str.append((s == null ? "null" : s.trim())); // NOI18N
    str.append(">\n"); // NOI18N
    this.dumpAttributes(PROPERTY_ONE, 0, str, indent);

    str.append(indent);
    str.append("PropertyTwo"); // NOI18N
    str.append(indent + "\t"); // NOI18N
    str.append("<"); // NOI18N
    s = this.getPropertyTwo();
    str.append((s == null ? "null" : s.trim())); // NOI18N
    str.append(">\n"); // NOI18N
    this.dumpAttributes(PROPERTY_TWO, 0, str, indent);
  }
Esempio n. 19
0
    /** Saves the data in the following format: Label:value e.g. Password Retries:3 */
    protected void saveData() {
      StringBuffer sbData = new StringBuffer();
      Component[] comps = getComponents();
      String strLabel = null;
      String strValue = null;
      String strCmd = null;

      for (int i = 0; i < comps.length; i++) {
        Component comp = comps[i];
        boolean bCmd = false;
        if (comp instanceof JLabel) {
          strLabel = ((JLabel) comp).getText();
          sbData.append(strLabel);
          sbData.append(":");

          // append to the cmd string
          if (strLabel.equalsIgnoreCase("Password Retries")) strCmd = RETRIES;
          else if (strLabel.indexOf("Default Expiration") >= 0) strCmd = MAXWEEKS;
          else if (strLabel.indexOf("Minimum Length") >= 0) strCmd = PASSLENGTH;
          else strCmd = "";
        } else if (comp instanceof JTextField) {
          strValue = ((JTextField) comp).getText();
          if (strValue == null) strValue = "";
          sbData.append(strValue);
          sbData.append("\n");

          // append to the cmd string
          if ((strCmd.indexOf(RETRIES) >= 0)
              || (strCmd.indexOf(MAXWEEKS) >= 0)
              || (strCmd.indexOf(PASSLENGTH) >= 0)) {
            strCmd = strCmd + "= " + strValue;
            bCmd = true;
          }
        } else if (comp instanceof JCheckBox) {
          strValue = ((JCheckBox) comp).isSelected() ? "yes" : "no";
          sbData.append(strValue);
          sbData.append("\n");
        }

        // call the unix script that can set these values
        if (bCmd) {
          String[] cmd = {
            WGlobal.SHTOOLCMD,
            WGlobal.SHTOOLOPTION,
            WGlobal.SUDO + WGlobal.SBIN + "auredt" + " " + strCmd
          };
          WUtil.runScript(cmd);
        }
      }
      // write to the file
      BufferedWriter writer = WFileUtil.openWriteFile(m_strPath);
      WFileUtil.writeAndClose(writer, sbData);
    }
 private String fileNameString(File[] files) {
   StringBuffer buf = new StringBuffer();
   for (int i = 0; files != null && i < files.length; i++) {
     if (i > 0) {
       buf.append(" ");
     }
     if (files.length > 1) {
       buf.append("\"");
     }
     buf.append(fileNameString(files[i]));
     if (files.length > 1) {
       buf.append("\"");
     }
   }
   return buf.toString();
 }
Esempio n. 21
0
 public String info(String prefix_) {
   if (runtime == null)
     return StringUtil.lastSubstring(prefix_ + super.toString(), ".") + "," + "<orphan>";
   StringBuffer sb_ =
       new StringBuffer(
           prefix_
               + StringUtil.lastSubstring(super.toString(), ".")
               + ", "
               + state
               + (sleepOn == null || sleepOn == this
                   ? ""
                   : " on "
                       + sleepOn
                       + (waitPack != null && waitPack.target != null ? "(waiting/locking)" : ""))
               + (state == State_SLEEPING ? " until " + wakeUpTime : "")
               + "\n"
               + prefix_
               + "Context="
               + mainContext()
               + (mainContext == null ? ", " : "\n" + prefix_)
               + "Next_Task="
               + (nextTask != null ? nextTask.toString() : "<null>")
               + "\n");
   if (currentContext != mainContext)
     sb_.append(prefix_ + "CurrentContext: " + _currentContext() + "\n");
   if (returnPort != null) sb_.append(prefix_ + "return_port: " + returnPort + "\n");
   if (sendingPort != null) sb_.append(prefix_ + "sending_port: " + sendingPort + "\n");
   sb_.append(prefix_ + "Locks: " + locks());
   sb_.append(prefix_ + "#arrivals: " + totalNumEvents + "\n");
   sb_.append(prefix_ + "last_sleepOn: " + lastsleepon + "\n");
   sb_.append(
       prefix_
           + "last_wkUp_thread: "
           + (lastwakeupthread == null ? null : currentThread(lastwakeupthread))
           + "\n");
   return sb_.toString();
 }
Esempio n. 22
0
 private String formatName(String name) {
   StringBuffer propertyName = new StringBuffer();
   if (lowerCase) propertyName.append(name.toLowerCase());
   else propertyName.append(name);
   char c = propertyName.charAt(0);
   if (firstLetterUpperCase) {
     if (c >= 'a' && c <= 'z') {
       c += 'A' - 'a';
     }
   } else {
     if (c >= 'A' && c <= 'Z') {
       c -= 'A' - 'a';
     }
   }
   propertyName.setCharAt(0, c);
   return propertyName.toString();
 }
  private VirtualMachine launch(DebuggerInfo info) throws DebuggerException {
    // create process & read password for local debugging

    // create main class & arguments ...............................................
    StringBuffer sb = new StringBuffer();
    sb.append(mainClassName);
    String[] infoArgs = info.getArguments();
    int i, k = infoArgs.length;
    for (i = 0; i < k; i++) sb.append(" \"").append(infoArgs[i]).append('"'); // NOI18N
    String main = new String(sb);

    // create connector ..............................................................
    VirtualMachineManager vmm = Bootstrap.virtualMachineManager();
    java.util.List lcs = vmm.launchingConnectors();
    k = lcs.size();
    for (i = 0; i < k; i++)
      if (((LaunchingConnector) lcs.get(i)).name().indexOf("RawCommandLineLaunch") >= 0) // NOI18N
      break;
    if (i == k) {
      finishDebugger();
      throw new DebuggerException(
          new MessageFormat(bundle.getString("EXC_Cannot_find_launcher"))
              .format(
                  new Object[] {
                    "RawCommandLineLaunch" // NOI18N
                  }));
    }
    LaunchingConnector lc = (LaunchingConnector) lcs.get(i);
    String transport = lc.transport().name();

    // create commandLine & NbProcessDescriptor ..............................
    NbProcessDescriptor debugerProcess;
    if (info instanceof ProcessDebuggerInfo)
      debugerProcess = ((ProcessDebuggerInfo) info).getDebuggerProcess();
    else debugerProcess = ProcessDebuggerType.DEFAULT_DEBUGGER_PROCESS;

    // generate password
    String password;
    if (transport.equals("dt_shmem")) { // NOI18N
      connector = getAttachingConnectorFor("dt_shmem");
      password = generatePassword();
      args = connector.defaultArguments();
      ((Argument) args.get("name")).setValue(password);
    } else {
      try {
        java.net.ServerSocket ss = new java.net.ServerSocket(0);
        password = "" + ss.getLocalPort(); // NOI18N
        ss.close();
      } catch (java.io.IOException e) {
        finishDebugger();
        throw new DebuggerException(
            new MessageFormat(bundle.getString("EXC_Cannot_find_empty_local_port"))
                .format(new Object[] {e.toString()}));
      }
      connector = getAttachingConnectorFor("dt_socket");
      args = connector.defaultArguments();
      ((Argument) args.get("port")).setValue(password);
    }
    HashMap map =
        Utils.processDebuggerInfo(
            info,
            "-Xdebug -Xnoagent -Xrunjdwp:transport="
                + // NOI18N
                transport
                + ",address="
                + // NOI18N
                password
                + ",suspend=y ", // NOI18N
            main);
    MapFormat format = new MapFormat(map);
    String commandLine =
        format.format(
            debugerProcess.getProcessName()
                + " "
                + // NOI18N
                debugerProcess.getArguments());
    println(commandLine, ERR_OUT);
    /*
    We mus wait on process start to connect...
    try {
      process = debugerProcess.exec (format);
    } catch (java.io.IOException exc) {
      finishDebugger ();
      throw new DebuggerException (
        new MessageFormat (bundle.getString ("EXC_While_create_debuggee")).
          format (new Object[] {
            debugerProcess.getProcessName (),
            exc.toString ()
          }),
        exc
      );
    }
    return connect (
      null,
      connector,
      args
    );*/

    /*      S ystem.out.println ("attaching: ");
    Utils.showConnectors (vmm.attachingConnectors ());

    S ystem.out.println ("launching: ");
    Utils.showConnectors (vmm.launchingConnectors ());

    S ystem.out.println ("listening: ");
    Utils.showConnectors (vmm.listeningConnectors ());*/

    // set debugger-start arguments
    Map params = lc.defaultArguments();
    ((Argument) params.get("command"))
        .setValue( // NOI18N
            commandLine);
    ((Argument) params.get("address"))
        .setValue( // NOI18N
            password);

    // launch VM
    try {
      return lc.launch(params);
    } catch (VMStartException exc) {
      showOutput(process = exc.process(), ERR_OUT, ERR_OUT);
      finishDebugger();
      throw new DebuggerException(
          new MessageFormat(bundle.getString("EXC_While_create_debuggee"))
              .format(
                  new Object[] {format.format(debugerProcess.getProcessName()), exc.toString()}),
          exc);
    } catch (Exception exc) {
      finishDebugger();
      throw new DebuggerException(
          new MessageFormat(bundle.getString("EXC_While_create_debuggee"))
              .format(
                  new Object[] {format.format(debugerProcess.getProcessName()), exc.toString()}),
          exc);
    }
  }
Esempio n. 24
0
  /**
   * Save the data to the file. Read the data from the file, and copy everything to the
   * stringbuffer. The lines in the file are of the form:
   * auditDir:system:/vnmr/part11/auditTrails:system file:standard:text:yes Based on these formats,
   * get the value of either the directory or the checkbox from the corresponding components, and
   * replace that value in the stringbuffer.
   */
  protected void saveData() {
    BufferedReader reader = WFileUtil.openReadFile(m_strPath);
    String strLine = null;
    StringBuffer sbData = new StringBuffer();
    if (reader == null) return;

    int nLineInd = 0;
    try {
      while ((strLine = reader.readLine()) != null) {
        // if the line starts with a comment from sccs, add '#' to it,
        // to make it a comment
        if (strLine.startsWith("%") || strLine.startsWith("@")) strLine = "# " + strLine;

        if (strLine.startsWith("#")) {
          sbData.append(strLine + "\n");
          continue;
        }
        StringTokenizer sTok = new StringTokenizer(strLine, File.pathSeparator);
        boolean bFile = false;
        boolean bLineEnd = false;
        boolean bDir = false;

        for (int i = 0; sTok.hasMoreTokens(); i++) {
          String strValue = sTok.nextToken();
          if (i == 0) {
            bFile = strValue.equalsIgnoreCase("file") ? true : false;
            bDir = false;
            if (strValue.equalsIgnoreCase("dir")) bDir = true;
          } else {
            // Case => file:standard:procpar:yes
            // skip over 'standard', 'procpar',
            // and get the value 'yes' or 'no' from the checkbox
            if (bFile) {
              if (i == 3) {
                String strNewValue = getValue(nLineInd);
                if (strNewValue != null) strValue = strNewValue;
                bLineEnd = true;
              } else bLineEnd = false;
            } else if (bDir) {
              bLineEnd = false;
              if (i == 3) bLineEnd = true;
            }
            // Case => part11Dir:/vnmr/part11/data 0r
            // Case => dataType:FDA
            // skip over 'part11Dir'
            // and get the value of the directory from the textfield,
            // or from the combobox
            else {
              if (i == 1) {
                String strNewValue = getValue(nLineInd);
                if (strNewValue != null) strValue = strNewValue;
                bLineEnd = true;
              } else bLineEnd = false;
            }
          }
          // copy the value to the stringbuffer
          sbData.append(strValue);
          if (!bLineEnd) sbData.append(File.pathSeparator);
        }
        nLineInd++;
        sbData.append("\n");
      }
      // write the data to the file
      reader.close();
      BufferedWriter writer = WFileUtil.openWriteFile(m_strPath);
      WFileUtil.writeAndClose(writer, sbData);
      m_objTimer =
          new javax.swing.Timer(
              200,
              new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                  VItemAreaIF.firePropertyChng(Global.PART11_CONFIG_FILE, "all", "");
                  m_objTimer.stop();
                }
              });
      m_objTimer.start();
    } catch (Exception e) {
      Messages.writeStackTrace(e);
      // e.printStackTrace();
      Messages.postDebug(e.toString());
    }
  }
Esempio n. 25
0
 private Object createObject(
     Node node, String name, String classPackage, String type, String value, boolean setProperty) {
   Bean parentBean = null;
   if (beansStack.size() > 0) parentBean = (Bean) beansStack.peek();
   Object object = null;
   // param is either an XSD type or a bean,
   // check if it can be converted to an XSD type
   XSDatatype dt = null;
   try {
     dt = DatatypeFactory.getTypeByName(type);
   } catch (DatatypeException dte) {
     // the type is not a valid XSD data type
   }
   // convert null value to default
   if ((dt != null) && (value == null)) {
     Class objType = dt.getJavaObjectType();
     if (objType == String.class) value = "";
     else if ((objType == java.math.BigInteger.class)
         || (objType == Long.class)
         || (objType == Integer.class)
         || (objType == Short.class)
         || (objType == Byte.class)) value = "0";
     else if ((objType == java.math.BigDecimal.class)
         || (objType == Double.class)
         || (objType == Float.class)) value = "0.0";
     else if (objType == Boolean.class) value = "false";
     else if (objType == java.util.Date.class) value = DateUtils.getCurrentDate();
     else if (objType == java.util.Calendar.class) value = DateUtils.getCurrentDateTime();
   }
   //  check whether the type was converted to an XSD datatype
   if ((dt != null) && dt.isValid(value, null)) {
     // create and return an XSD Java object (e.g. String, Integer, Boolean, etc)
     object = dt.createJavaObject(value, null);
     if (object instanceof java.util.Calendar) {
       // check that the object is truly a Calendar
       // because DatatypeFactory converts xsd:date
       // types to GregorianCalendar instead of Date.
       if (type.equals("date")) {
         java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd");
         try {
           object = df.parse(value);
         } catch (java.text.ParseException pe) {
           object = new java.util.Date();
         }
       }
     }
   } else {
     // Create a bean object
     if (topLevelBean == null) topLevelBean = parentBean;
     object = pushBeanOnStack(classPackage, type);
     // Check fields to see if this property is the 'value' for the object
     Field[] fields = object.getClass().getDeclaredFields();
     for (int i = 0; i < fields.length; i++) {
       if (fields[i].isAnnotationPresent(ObjectXmlAsValue.class)) {
         try {
           StringBuffer fieldName = new StringBuffer(fields[i].getName());
           char c = fieldName.charAt(0);
           if (c >= 'a' && c <= 'z') {
             c += 'A' - 'a';
           }
           fieldName.setCharAt(0, c);
           fieldName.insert(0, "set");
           Method method =
               object
                   .getClass()
                   .getMethod(fieldName.toString(), new Class[] {fields[i].getType()});
           method.invoke(object, value);
           break;
         } catch (Exception e) {
           System.err.println(e.getMessage());
         }
       }
     }
     NamedNodeMap nodeAttrs = node.getAttributes();
     // iterate attributes and set field values for property attributes
     for (int i = 0; i < nodeAttrs.getLength(); i++) {
       String nodePrefix = nodeAttrs.item(i).getPrefix();
       if (nodePrefix.equals(nsPrefix)) {
         String nodeName = nodeAttrs.item(i).getLocalName();
         String nodeValue = nodeAttrs.item(i).getNodeValue();
         try {
           Field field = object.getClass().getDeclaredField(nodeName);
           if (field.isAnnotationPresent(ObjectXmlAsAttribute.class)) {
             StringBuffer fieldName = new StringBuffer(field.getName());
             char c = fieldName.charAt(0);
             if (c >= 'a' && c <= 'z') {
               c += 'A' - 'a';
             }
             fieldName.setCharAt(0, c);
             fieldName.insert(0, "set");
             Method method =
                 object.getClass().getMethod(fieldName.toString(), new Class[] {field.getType()});
             if (field.getType() == String.class) method.invoke(object, nodeValue);
             else if (field.getType() == Boolean.TYPE)
               method.invoke(object, StringUtils.strToBool(nodeValue, "true"));
             else if (field.getType() == Byte.TYPE)
               method.invoke(object, Byte.valueOf(nodeValue).byteValue());
             else if (field.getType() == Character.TYPE)
               method.invoke(object, Character.valueOf(nodeValue.charAt(0)));
             else if (field.getType() == Double.TYPE)
               method.invoke(object, Double.valueOf(nodeValue).doubleValue());
             else if (field.getType() == Float.TYPE)
               method.invoke(object, Float.valueOf(nodeValue).floatValue());
             else if (field.getType() == Integer.TYPE)
               method.invoke(object, Integer.valueOf(nodeValue).intValue());
             else if (field.getType() == Long.TYPE)
               method.invoke(object, Long.valueOf(nodeValue).longValue());
             else if (field.getType() == Short.TYPE)
               method.invoke(object, Short.valueOf(nodeValue).shortValue());
           }
         } catch (Exception e) {
           System.err.println(e.getMessage());
         }
       }
     }
   }
   if ((parentBean != null) && (setProperty)) {
     parentBean.setProperty(name, object);
   }
   return object;
 }
Esempio n. 26
0
  // Dump the content of this bean returning it as a String
  public void dump(StringBuffer str, String indent) {
    String s;
    Object o;
    org.netbeans.modules.schema2beans.BaseBean n;
    str.append(indent);
    str.append("Description[" + this.sizeDescription() + "]"); // NOI18N
    for (int i = 0; i < this.sizeDescription(); i++) {
      str.append(indent + "\t");
      str.append("#" + i + ":");
      str.append(indent + "\t"); // NOI18N
      str.append("<"); // NOI18N
      s = this.getDescription(i);
      str.append((s == null ? "null" : s.trim())); // NOI18N
      str.append(">\n"); // NOI18N
      this.dumpAttributes(DESCRIPTION, i, str, indent);
    }

    str.append(indent);
    str.append("EjbRefName"); // NOI18N
    str.append(indent + "\t"); // NOI18N
    str.append("<"); // NOI18N
    s = this.getEjbRefName();
    str.append((s == null ? "null" : s.trim())); // NOI18N
    str.append(">\n"); // NOI18N
    this.dumpAttributes(EJB_REF_NAME, 0, str, indent);

    str.append(indent);
    str.append("EjbRefType"); // NOI18N
    str.append(indent + "\t"); // NOI18N
    str.append("<"); // NOI18N
    s = this.getEjbRefType();
    str.append((s == null ? "null" : s.trim())); // NOI18N
    str.append(">\n"); // NOI18N
    this.dumpAttributes(EJB_REF_TYPE, 0, str, indent);

    str.append(indent);
    str.append("Home"); // NOI18N
    str.append(indent + "\t"); // NOI18N
    str.append("<"); // NOI18N
    s = this.getHome();
    str.append((s == null ? "null" : s.trim())); // NOI18N
    str.append(">\n"); // NOI18N
    this.dumpAttributes(HOME, 0, str, indent);

    str.append(indent);
    str.append("Remote"); // NOI18N
    str.append(indent + "\t"); // NOI18N
    str.append("<"); // NOI18N
    s = this.getRemote();
    str.append((s == null ? "null" : s.trim())); // NOI18N
    str.append(">\n"); // NOI18N
    this.dumpAttributes(REMOTE, 0, str, indent);

    str.append(indent);
    str.append("EjbLink"); // NOI18N
    str.append(indent + "\t"); // NOI18N
    str.append("<"); // NOI18N
    s = this.getEjbLink();
    str.append((s == null ? "null" : s.trim())); // NOI18N
    str.append(">\n"); // NOI18N
    this.dumpAttributes(EJB_LINK, 0, str, indent);
  }
Esempio n. 27
0
  /* PROTECTED METHODS */
  protected void getBeanElements(
      Element parentElement, String objectName, String objectType, Object bean)
      throws IntrospectionException, IllegalAccessException {
    if (objectName == null) {
      // Get just the class name by lopping off the package name
      StringBuffer sb = new StringBuffer(bean.getClass().getName());
      sb.delete(0, sb.lastIndexOf(".") + 1);
      objectName = sb.toString();
    }

    // Check if the bean is a standard Java object type or a byte[] (encoded as a base 64 array)
    Element element = getStandardObjectElement(document, bean, objectName);
    // If the body element object is null then the bean is not a standard Java object type
    if (element != null) {
      if (includeNullValues
          || !element
              .getAttribute(
                  NamespaceConstants.NSPREFIX_SCHEMA_XSI
                      + ":"
                      + org.apache.axis.Constants.ATTR_TYPE)
              .equals("anyType")) {
        if (!includeTypeInfo) {
          element.removeAttribute(
              NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + org.apache.axis.Constants.ATTR_TYPE);
          element.removeAttribute(NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null");
        }
        parentElement.appendChild(element);
      }
    } else {
      // Analyze the bean
      Class classOfBean = null;
      if (bean != null) classOfBean = bean.getClass();
      // If the object is an array, then serialize each of the beans in the array.
      if ((classOfBean != null) && (classOfBean.isArray())) {
        String[] arrayInfo = getXsdSoapArrayInfo(classOfBean.getCanonicalName(), nsPrefix);
        int arrayLen = Array.getLength(bean);
        StringBuffer arrayType = new StringBuffer(arrayInfo[1]);
        arrayType.insert(arrayType.indexOf("[]") + 1, arrayLen);
        if (objectName.charAt(objectName.length() - 1) == ';')
          objectName =
              new StringBuffer(objectName).deleteCharAt(objectName.length() - 1).toString();
        element = document.createElement(objectName);
        parentElement.appendChild(element);
        // Get the bean objects from the array and serialize each
        for (int i = 0; i < arrayLen; i++) {
          Object b = Array.get(bean, i);
          if (b != null) {
            String name = null;
            if (objectName.charAt(objectName.length() - 1) == 's') {
              name = formatName(objectName.substring(0, objectName.length() - 1));
            }
            getBeanElements(element, name, b.getClass().getName(), b);
          } else {
            // Array element is null, so don't include it and decrement the # elements in the array
            int index = arrayType.indexOf("[");
            arrayType.replace(index + 1, index + 2, String.valueOf(--arrayLen));
          }
          if (includeTypeInfo) {
            element.setAttributeNS(
                NamespaceConstants.NSURI_SCHEMA_XSI,
                NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE,
                NamespaceConstants.NSPREFIX_SOAP_ENCODING + ":Array");
            element.setAttributeNS(
                NamespaceConstants.NSURI_SOAP_ENCODING,
                NamespaceConstants.NSPREFIX_SOAP_ENCODING + ":" + Constants.ATTR_ARRAY_TYPE,
                arrayInfo[0] + ":" + arrayType.toString());
          }
        }
      } else {
        int beanType = 0;
        String beanName = null;
        if (classOfBean != null) {
          if (classOfBean == Vector.class) {
            beanType = 1;
            beanName = "Vector";
          } else if (classOfBean == ArrayList.class) {
            beanType = 2;
            beanName = "ArrayList";
          } else if (classOfBean == LinkedList.class) {
            beanType = 3;
            beanName = "LinkedList";
          } else if (classOfBean == Hashtable.class) {
            beanType = 4;
            beanName = "Hashtable";
          } else if (classOfBean == Properties.class) {
            beanType = 5;
            beanName = "Properties";
          } else if ((classOfBean == HashMap.class) || (classOfBean == SortedMap.class)) {
            beanType = 6;
            beanName = "Map";
          }
        }
        if (beanType > 0) {
          String prefix = null;
          if ((beanType == 1) || (beanType == 5))
            prefix = NamespaceConstants.NSPREFIX_SOAP_ENCODING;
          if (beanType == 6) prefix = Constants.NS_PREFIX_XMLSOAP;
          else prefix = DEFAULT_NS_PREFIX;
          element = document.createElement(objectName);
          if (includeTypeInfo) {
            element.setAttributeNS(
                NamespaceConstants.NSURI_SCHEMA_XSI,
                NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE,
                prefix + ":" + beanName);
            if (bean == null)
              element.setAttributeNS(
                  NamespaceConstants.NSURI_SCHEMA_XSI,
                  NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null",
                  "true");
          }
          parentElement.appendChild(element);
          if ((beanType >= 1) && (beanType <= 3)) {
            AbstractCollection collection = (AbstractCollection) bean;
            // Get the bean objects from the vector and serialize each
            Iterator it = collection.iterator();
            while (it.hasNext()) {
              Object b = it.next();
              String name = null;
              if (b != null) {
                if (objectName.charAt(objectName.length() - 1) == 's') {
                  name = formatName(objectName.substring(0, objectName.length() - 1));
                } else name = "item";
              }
              getBeanElements(element, name, b.getClass().getName(), b);
            }
          } else if ((beanType == 4) || (beanType == 5)) {
            Hashtable hashtable = (Hashtable) bean;
            // Get the bean objects from the hashtable or properties and serialize each
            Enumeration en = hashtable.keys();
            while (en.hasMoreElements()) {
              Object key = en.nextElement();
              String keyClassName = key.getClass().getName();
              Object value = hashtable.get(key);
              String beanClassName = null;
              if (value != null) beanClassName = value.getClass().getName();
              Element itemElement = document.createElement("item");
              element.appendChild(itemElement);
              getBeanElements(itemElement, "key", keyClassName, key);
              getBeanElements(itemElement, "value", beanClassName, value);
            }
          } else if (beanType == 6) {
            Map map = null;
            if (classOfBean == HashMap.class) map = (HashMap) bean;
            else if (classOfBean == SortedMap.class) map = (SortedMap) bean;
            // Get the bean objects from the hashmap and serialize each
            Set set = map.keySet();
            Iterator it = set.iterator();
            while (it.hasNext()) {
              Object key = it.next();
              String keyClassName = key.getClass().getName();
              Object value = map.get(key);
              String beanClassName = null;
              if (value != null) beanClassName = value.getClass().getName();
              Element itemElement = document.createElement("item");
              element.appendChild(itemElement);
              getBeanElements(itemElement, "key", keyClassName, key);
              getBeanElements(itemElement, "value", beanClassName, value);
            }
          }
        } else {
          // Create a parent element for this bean's properties
          if (objectName.charAt(objectName.length() - 1) == ';')
            objectName =
                new StringBuffer(objectName).deleteCharAt(objectName.length() - 1).toString();
          objectName = formatName(objectName);
          element = document.createElement(objectName);
          parentElement.appendChild(element);
          if (includeTypeInfo) {
            StringBuffer className = new StringBuffer(objectType);
            element.setAttributeNS(
                NamespaceConstants.NSURI_SCHEMA_XSI,
                NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE,
                nsPrefix + ":" + className.delete(0, className.lastIndexOf(".") + 1).toString());
          }
          if (classOfBean != null) {
            // Get an array of property descriptors
            BeanInfo bi = Introspector.getBeanInfo(classOfBean);
            PropertyDescriptor[] pds = bi.getPropertyDescriptors();
            // For each property of the bean, get a SOAPBodyElement that
            // represents the individual property. Append that SOAPBodyElement
            // to the class name element of the SOAP body.
            for (int i = 0; i < pds.length; i++) {
              PropertyDescriptor pd = pds[i];
              getBeanElementProperties(element, bean, pd);
            }
          } else {
            if (includeTypeInfo)
              element.setAttributeNS(
                  NamespaceConstants.NSURI_SCHEMA_XSI,
                  NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null",
                  "true");
          }
        }
      }
    }
  }
Esempio n. 28
0
 // Serialize the bean using the specified namespace prefix & uri
 public String serialize(Object bean) throws IntrospectionException, IllegalAccessException {
   // Use the class name as the name of the root element
   String className = bean.getClass().getName();
   String rootElementName = null;
   if (bean.getClass().isAnnotationPresent(ObjectXmlAlias.class)) {
     AnnotatedElement annotatedElement = bean.getClass();
     ObjectXmlAlias aliasAnnotation = annotatedElement.getAnnotation(ObjectXmlAlias.class);
     rootElementName = aliasAnnotation.value();
   }
   // Use the package name as the namespace URI
   Package pkg = bean.getClass().getPackage();
   nsURI = pkg.getName();
   // Remove a trailing semi-colon (;) if present (i.e. if the bean is an array)
   className = StringUtils.deleteTrailingChar(className, ';');
   StringBuffer sb = new StringBuffer(className);
   String objectName = sb.delete(0, sb.lastIndexOf(".") + 1).toString();
   domDocument = createDomDocument(objectName);
   document = domDocument.getDocument();
   Element root = document.getDocumentElement();
   // Parse the bean elements
   getBeanElements(root, rootElementName, className, bean);
   StringBuffer xml = new StringBuffer();
   if (prettyPrint)
     xml.append(domDocument.serialize(lineSeperator, indentChars, includeXmlProlog));
   else xml.append(domDocument.serialize(includeXmlProlog));
   if (!includeTypeInfo) {
     int index = xml.indexOf(root.getNodeName());
     xml.delete(index - 1, index + root.getNodeName().length() + 2);
     xml.delete(xml.length() - root.getNodeName().length() - 4, xml.length());
   }
   return xml.toString();
 }
  protected static String getStatusToolTip() {
    StringBuffer result = new StringBuffer("<html>"); // NOI18N
    result.append("<table cellspacing=\"0\" border=\"0\">"); // NOI18N

    final CollabManager manager = CollabManager.getDefault();

    if (manager != null) {
      Set sessions =
          new TreeSet(
              new Comparator() {
                public int compare(Object o1, Object o2) {
                  String s1 = ((CollabSession) o1).getUserPrincipal().getDisplayName();
                  String s2 = ((CollabSession) o2).getUserPrincipal().getDisplayName();

                  return s1.compareTo(s2);
                }
              });

      sessions.addAll(Arrays.asList(manager.getSessions()));

      if (sessions.size() == 0) {
        result.append("<tr><td>"); // NOI18N
        result.append(getStatusDescription(CollabPrincipal.STATUS_OFFLINE));
        result.append("</td></tr>"); // NOI18N
      } else {
        for (Iterator i = sessions.iterator(); i.hasNext(); ) {
          CollabPrincipal principal = ((CollabSession) i.next()).getUserPrincipal();

          result.append("<tr>"); // NOI18N
          result.append("<td>"); // NOI18N
          result.append("<b>"); // NOI18N
          result.append(principal.getDisplayName());
          result.append(": "); // NOI18N
          result.append("</b>"); // NOI18N
          result.append("</td>"); // NOI18N
          result.append("<td>"); // NOI18N
          result.append(getStatusDescription(principal.getStatus()));
          result.append("</td>"); // NOI18N
          result.append("</tr>"); // NOI18N
        }
      }
    }

    result.append("</table>"); // NOI18N

    return result.toString();
  }
Esempio n. 30
0
 public String dumpBeanNode() {
   StringBuffer str = new StringBuffer();
   str.append("EjbRefType\n"); // NOI18N
   this.dump(str, "\n  "); // NOI18N
   return str.toString();
 }