Example #1
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;
   }
 }
Example #2
0
  public boolean shutdown(int port, boolean ssl) {
    try {
      String protocol = "http" + (ssl ? "s" : "");
      URL url = new URL(protocol, "127.0.0.1", port, "shutdown");
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setRequestProperty("servicemanager", "shutdown");
      conn.connect();

      StringBuffer sb = new StringBuffer();
      BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
      int n;
      char[] cbuf = new char[1024];
      while ((n = br.read(cbuf, 0, cbuf.length)) != -1) sb.append(cbuf, 0, n);
      br.close();
      String message = sb.toString().replace("<br>", "\n");
      if (message.contains("Goodbye")) {
        cp.appendln("Shutting down the server:");
        String[] lines = message.split("\n");
        for (String line : lines) {
          cp.append("...");
          cp.appendln(line);
        }
        return true;
      }
    } catch (Exception ex) {
    }
    cp.appendln("Unable to shutdown CTP");
    return false;
  }
Example #3
0
  /** Capture an image for all ViewManagers */
  public void captureAll() {
    List vms = getViewManagers();

    String filename = FileManager.getWriteFile(FileManager.FILTER_IMAGE, FileManager.SUFFIX_JPG);
    if (filename == null) {
      return;
    }
    String root = IOUtil.stripExtension(filename);
    String ext = IOUtil.getFileExtension(filename);

    StringBuffer sb = new StringBuffer("<html>");
    sb.append("Since there were multiple images they were written out as:<ul>");
    for (int i = 0; i < vms.size(); i++) {
      ViewManager vm = (ViewManager) vms.get(i);
      String name = vm.getName();
      if ((name == null) || (name.trim().length() == 0)) {
        name = "" + (i + 1);
      }
      if (vms.size() != 1) {
        filename = root + name + ext;
      }

      sb.append("<li> " + filename);
      vm.writeImage(filename);
    }
    sb.append("</ul></html>");
    if (vms.size() > 1) {
      GuiUtils.showDialog("Captured Images", GuiUtils.inset(new JLabel(sb.toString()), 5));
    }
  }
Example #4
0
  private void commit() {
    String serverName = (String) server.getSelectedItem();
    if (serverName == null || serverName.equals("")) {
      vlog.error("No server name specified!");
      if (VncViewer.nViewers == 1)
        if (cc.viewer instanceof VncViewer) {
          ((VncViewer) cc.viewer).exit(1);
        }
      ret = false;
      endDialog();
    }

    // set params
    if (opts.via != null && opts.via.indexOf(':') >= 0) {
      opts.serverName = serverName;
    } else {
      opts.serverName = Hostname.getHost(serverName);
      opts.port = Hostname.getPort(serverName);
    }

    // Update the history list
    String valueStr = UserPreferences.get("ServerDialog", "history");
    String t = (valueStr == null) ? "" : valueStr;
    StringTokenizer st = new StringTokenizer(t, ",");
    StringBuffer sb = new StringBuffer().append((String) server.getSelectedItem());
    while (st.hasMoreTokens()) {
      String str = st.nextToken();
      if (!str.equals((String) server.getSelectedItem()) && !str.equals("")) {
        sb.append(',');
        sb.append(str);
      }
    }
    UserPreferences.set("ServerDialog", "history", sb.toString());
    UserPreferences.save("ServerDialog");
  }
Example #5
0
  protected String getFeatureText() {
    String txt = "";
    try {
      txt = ((HTMLDocument) getDocument()).getText(0, getDocument().getLength()).trim();

      StringBuffer buff = new StringBuffer();
      StringTokenizer tok = new StringTokenizer(txt, "/");
      int ntok = 0;

      while (tok.hasMoreTokens()) {
        String tokTxt = "/" + tok.nextToken().trim();

        int ind = tokTxt.indexOf("=");

        if (ntok != 0 && ind > -1 && qualifier.contains(tokTxt.substring(0, ind + 1)))
          buff.append("\n" + tokTxt);
        else buff.append(tokTxt);

        ntok++;
      }

      txt = buff.toString();
    } catch (BadLocationException ble) {
      ble.printStackTrace();
    }

    return txt;
  }
    public void doActionOnButton3() {
      //            Sector sector = Sector.fromDegrees( 44d, 46d, -123.3d, -123.2d );

      ArrayList<LatLon> latlons = new ArrayList<LatLon>();

      latlons.add(LatLon.fromDegrees(45.50d, -123.3d));
      //            latlons.add( LatLon.fromDegrees( 45.51d, -123.3d ) );
      latlons.add(LatLon.fromDegrees(45.52d, -123.3d));
      //            latlons.add( LatLon.fromDegrees( 45.53d, -123.3d ) );
      latlons.add(LatLon.fromDegrees(45.54d, -123.3d));
      //            latlons.add( LatLon.fromDegrees( 45.55d, -123.3d ) );
      latlons.add(LatLon.fromDegrees(45.56d, -123.3d));
      //            latlons.add( LatLon.fromDegrees( 45.57d, -123.3d ) );
      latlons.add(LatLon.fromDegrees(45.58d, -123.3d));
      //            latlons.add( LatLon.fromDegrees( 45.59d, -123.3d ) );
      latlons.add(LatLon.fromDegrees(45.60d, -123.3d));

      ElevationModel model = this.wwd.getModel().getGlobe().getElevationModel();

      StringBuffer sb = new StringBuffer();
      for (LatLon ll : latlons) {
        double e = model.getElevation(ll.getLatitude(), ll.getLongitude());
        sb.append("\n").append(e);
      }

      Logging.logger().info(sb.toString());
    }
  protected void _save() {
    jEdit.setBooleanProperty("view.showToolbar", showToolbar.isSelected());

    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < listModel.getSize(); i++) {
      if (i != 0) buf.append(' ');
      Button button = (Button) listModel.elementAt(i);
      buf.append(button.actionName);
      jEdit.setProperty(button.actionName + ".icon", button.iconName);
    }
    jEdit.setProperty("view.toolbar", buf.toString());
  }
 // this.finalized() needs to be called before
 // getColumnCount()/getRowCount()/toString()
 public void finalized() {
   int num_lines;
   strbuf2str = strbuf.toString();
   num_lines = this.getNumOfLines();
   if (num_lines <= 3) num_rows = 3;
   else num_rows = 4;
 }
    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();
      }
    }
Example #10
0
 private String replace(String string, Properties table) {
   try {
     Pattern pattern = Pattern.compile("\\$\\{\\w+\\}");
     Matcher matcher = pattern.matcher(string);
     StringBuffer sb = new StringBuffer();
     while (matcher.find()) {
       String group = matcher.group();
       String key = group.substring(2, group.length() - 1).trim();
       String repl = table.getProperty(key);
       if (repl == null) repl = matcher.quoteReplacement(group);
       matcher.appendReplacement(sb, repl);
     }
     matcher.appendTail(sb);
     return sb.toString();
   } catch (Exception ex) {
     return string;
   }
 }
Example #11
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);
 }
Example #12
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;
 }
Example #13
0
 private String physReadTextFile(File file) {
   // physically read text file
   try {
     BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
     StringBuffer tmp = new StringBuffer();
     while (input.ready()) {
       tmp.append(input.readLine());
       tmp.append("\n");
     }
     return tmp.toString();
   } catch (FileNotFoundException e) {
     // not sure how this can happen
     showErrorDialog("Unable to load \"" + file.getName() + "\" (file not found)");
   } catch (IOException e) {
     // This happens if e.g. file already exists and
     // we do not have write permissions
     showErrorDialog("Unable to load \"" + file.getName() + "\" (I/O error)");
   }
   return new String("");
 }
    // For Real Primitive
    public void setPrimitiveText(final Primitive prime) {
      this.setCoordsText(prime.getVertices(), "");

      String info_str;
      info_str = prime.toInfoBoxString().trim();
      if (info_str.length() > 0) {
        strbuf.append("\n" + info_str);
        num_rows++;
      }

      Drawable prime_parent;
      prime_parent = prime.getParent();
      if (prime_parent != null) {
        info_str = prime_parent.toInfoBoxString().trim();
        if (info_str.length() > 0) {
          strbuf.append("\n" + info_str);
          num_rows++;
        }
      }
    }
Example #15
0
 private boolean checkServer(int port, boolean ssl) {
   try {
     URL url = new URL("http://127.0.0.1:" + port);
     HttpURLConnection conn = (HttpURLConnection) url.openConnection();
     conn.setRequestMethod("GET");
     conn.connect();
     int length = conn.getContentLength();
     StringBuffer text = new StringBuffer();
     InputStream is = conn.getInputStream();
     InputStreamReader isr = new InputStreamReader(is);
     int size = 256;
     char[] buf = new char[size];
     int len;
     while ((len = isr.read(buf, 0, size)) != -1) text.append(buf, 0, len);
     isr.close();
     if (programName.equals("ISN")) return !shutdown(port, ssl);
     return true;
   } catch (Exception ex) {
     return false;
   }
 }
  /** 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);
  }
    public void doActionOnButton2() {
      ArrayList<LatLon> latlons = new ArrayList<LatLon>();

      latlons.add(LatLon.fromDegrees(45.50d, -123.3d));
      //            latlons.add( LatLon.fromDegrees( 45.51d, -123.3d ) );
      latlons.add(LatLon.fromDegrees(45.52d, -123.3d));
      //            latlons.add( LatLon.fromDegrees( 45.53d, -123.3d ) );
      latlons.add(LatLon.fromDegrees(45.54d, -123.3d));
      //            latlons.add( LatLon.fromDegrees( 45.55d, -123.3d ) );
      latlons.add(LatLon.fromDegrees(45.56d, -123.3d));
      //            latlons.add( LatLon.fromDegrees( 45.57d, -123.3d ) );
      latlons.add(LatLon.fromDegrees(45.58d, -123.3d));
      //            latlons.add( LatLon.fromDegrees( 45.59d, -123.3d ) );
      latlons.add(LatLon.fromDegrees(45.60d, -123.3d));

      Sector sector = Sector.fromDegrees(44d, 46d, -123d, -121d);
      //            Sector sector = Sector.boundingSector( latlons );

      double[] elevations = new double[latlons.size()];

      // request resolution of DTED2 (1degree / 3600 )
      double targetResolution = Angle.fromDegrees(1d).radians / 3600;

      double resolutionAchieved =
          this.wwd
              .getModel()
              .getGlobe()
              .getElevationModel()
              .getElevations(sector, latlons, targetResolution, elevations);

      StringBuffer sb = new StringBuffer();
      for (double e : elevations) {
        sb.append("\n").append(e);
      }
      sb.append("\nresolutionAchieved = ").append(resolutionAchieved);
      sb.append(", requested resolution = ").append(targetResolution);

      Logging.logger().info(sb.toString());
    }
  /**
   * ************************************************************************ Initialize Table
   * access - create SQL, dateColumn. <br>
   * The driving table is "hdr", e.g. for hdr.C_BPartner_ID=.. The line table is "lin", e.g. for
   * lin.M_Product_ID=.. You use the dateColumn/qtyColumn variable directly as it is table specific.
   * <br>
   * The sql is dependent on MatchMode: - If Matched - all (fully or partially) matched records are
   * listed - If Not Matched - all not fully matched records are listed
   *
   * @param display (Invoice, Shipment, Order) see MATCH_*
   * @param matchToType (Invoice, Shipment, Order) see MATCH_*
   */
  private static void tableInit() {
    m_sql = new StringBuffer();

    if (tableInit_option == 0) {
      m_sql.append(
          "SELECT value,tab.M_Product_ID,tab.Name "
              + "FROM M_Product tab "
              + "WHERE XX_VMR_VENDORPRODREF_ID="
              + LineRefProv.getXX_VMR_VendorProdRef_ID()
              + " "
              + "AND ISACTIVE='Y' "
              + "AND M_ATTRIBUTESET_ID = "
              + Env.getCtx().getContextAsInt("#XX_L_P_ATTRIBUTESETST_ID"));

      /*//Si caracteristica larga es null
      if(LineRefProv.getXX_VMR_LongCharacteristic_ID()!=0)
      {
      	m_sql.append("AND XX_VMR_LONGCHARACTERISTIC_ID="+LineRefProv.getXX_VMR_LongCharacteristic_ID()+" ");
      }
      else{
      	m_sql.append("AND XX_VMR_LONGCHARACTERISTIC_ID IS NULL ");
      }*/

      m_orderBy = " order by M_Product_ID";
    } else if (tableInit_option == 1) {
      m_sql.append(
          "SELECT value,tab.M_Product_ID,tab.Name "
              + "FROM M_Product tab "
              + "WHERE tab.M_Product_ID IN "
              + "(select M_Product from XX_VMR_REFERENCEMATRIX where XX_VMR_PO_LINEREFPROV_ID="
              + (Integer) LineRefProv.getXX_VMR_PO_LineRefProv_ID()
              + ")");
    } else if (tableInit_option == 2) {
      m_sql.append(
          "SELECT value,tab.M_Product_ID,tab.Name "
              + "FROM M_Product tab "
              + "WHERE XX_VMR_VENDORPRODREF_ID = 0 AND M_PRODUCT_ID = 0");
    }
  } //  tableInit
    // For Real Composite
    public void setCompositeText(final Composite cmplx) {
      Coord[] cmplx_coords;
      cmplx_coords = new Coord[] {cmplx.getStartVertex(), cmplx.getFinalVertex()};
      this.setCoordsText(cmplx_coords, "");

      String info_str;
      info_str = cmplx.toInfoBoxString().trim();
      if (info_str.length() > 0) {
        strbuf.append("\n" + info_str);
        num_rows++;
      }

      Drawable cmplx_parent;
      cmplx_parent = cmplx.getParent();
      if (cmplx_parent != null) {
        info_str = cmplx_parent.toInfoBoxString().trim();
        if (info_str.length() > 0) {
          strbuf.append("\n" + info_str);
          num_rows++;
        }
      }
    }
  /**
   * Fill the table using m_sql
   *
   * @param table table
   */
  private static void tableLoad(MiniTable table) {
    //	log.finest(m_sql + " - " +  m_groupBy);
    String sql =
        MRole.getDefault()
                .addAccessSQL(m_sql.toString(), "tab", MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO)
            + m_groupBy
            + m_orderBy;

    log.finest(sql);
    try {
      Statement stmt = DB.createStatement();
      ResultSet rs = stmt.executeQuery(sql);
      table.loadTable(rs);
      stmt.close();
    } catch (SQLException e) {
      log.log(Level.SEVERE, sql, e);
    }
  } //  tableLoad
Example #21
0
 /**
  * Get the miscellaneous URL keywords
  *
  * @return the key value pairs
  */
 public String getMiscKeywords() {
   StringBuffer buff = new StringBuffer();
   appendMiscKeyValues(buff);
   return buff.toString();
 }
    /**
     * Write the file by writing the values from the labels, and the values list.
     *
     * @param strFile the file to be written.
     * @param aListLabels arraylist of texfields of labels.
     * @param aListValues arraylist of texfields of values.
     */
    protected void writeFile(
        String strUser, String strFile, ArrayList aListLabels, ArrayList aListValues) {
      String strPath = FileUtil.openPath(strFile);
      String strLabel = "";
      String strValue = "";
      StringBuffer sbValues = new StringBuffer();
      JTextField txfLabel = null;
      JTextField txfValue = null;
      boolean bNewFile = false;
      int nFDAMode = Util.getPart11Mode();

      // if it's the part11 pnl and the mode is nonFDA,
      // then don't write the file for this panel
      // the other way is not true.
      if (this instanceof DisplayParentDirectory) {
        if ((isPart11Pnl() && nFDAMode == Util.NONFDA)) {
          return;
        }
      }

      if (strPath == null) {
        strPath = FileUtil.savePath(strFile);
        bNewFile = true;
      }

      if (strPath == null || aListLabels == null) return;

      if (aListValues == null) aListValues = new ArrayList();

      // Get the list of the textfields for values and labels.
      int nLblSize = aListLabels.size();
      int nValueSize = aListValues.size();
      ArrayList<String> labelList = new ArrayList<String>();

      // Get the value from each textfield, and add it to the buffer.
      for (int i = 0; i < nLblSize; i++) {
        txfLabel = (JTextField) aListLabels.get(i);
        txfValue = (i < nValueSize) ? (JTextField) aListValues.get(i) : null;

        strLabel = (txfLabel != null) ? txfLabel.getText() : null;
        strValue = (txfValue != null) ? txfValue.getText() : "";

        // We need to be sure they don't have two data directories with
        // the same labels.  Save the label list if we are writing to
        // the "data" file.
        if (strFile.indexOf("data") != -1) {
          if (labelList.contains(strLabel)) {
            Messages.postError(
                "The Data Directory specifications "
                    + "must not have duplicate Label names. "
                    + "The Label \""
                    + strLabel
                    + "\" is duplicated.  "
                    + "Skipping the second instance.  Please "
                    + "specify a new Label.");
            continue;
          } else labelList.add(strLabel);
        }

        if (strLabel == null || strLabel.trim().length() <= 0 || strValue.equals(INFOSTR)) continue;

        // for user template tab, don't need to parse the value
        if (!(this instanceof DisplayTemplate)) strValue = getValue(strUser, strValue);
        strLabel = strLabel.trim();
        if (strValue != null) strValue = strValue.trim();

        // sbValues.append("\"");
        sbValues.append(strLabel);
        // sbValues.append("\"  ");

        sbValues.append(File.pathSeparator);
        sbValues.append(strValue);
        sbValues.append("\n");
      }

      if (Util.isPart11Sys()) writeAuditTrail(strPath, strUser, sbValues);

      // write the data to the file.
      BufferedWriter writer = WFileUtil.openWriteFile(strPath);
      WFileUtil.writeAndClose(writer, sbValues);

      // if it's a template file, then make it writable for everyone.
      if (bNewFile) {
        String strCmd = "chmod 755 ";
        if (this instanceof DisplayTemplate) strCmd = "chmod 777 ";
        if (Util.iswindows()) strPath = UtilB.windowsPathToUnix(strPath);
        String[] cmd = {WGlobal.SHTOOLCMD, WGlobal.SHTOOLOPTION, strCmd + strPath};
        WUtil.runScriptInThread(cmd);
      }
    }
    // For Shadow Primitive
    public void setShadowText(final Shadow shade, final Category type) {
      this.setEndCoordsText(
          shade.getStartVertex(),
          shade.getFinalVertex(),
          shade.getEarliestTime(),
          shade.getLatestTime(),
          shade.getVertices().length);
      strbuf.append("\n\n");
      this.setCoordsText(shade.getVertices(), " (ave)");
      strbuf.append("\n");

      StringBuffer linebuf;
      Topology shade_topo;
      CategoryWeight[] twgts;
      CategoryWeight twgt;
      String twgt_str;
      int print_status;
      int idx;

      shade_topo = shade.getCategory().getTopology();

      // linebuf = new StringBuffer( "Number of Real Drawables = " );
      linebuf = new StringBuffer("Number of Real ");
      linebuf.append(shade_topo + "s = ");
      linebuf.append(shade.getNumOfRealObjects());
      if (num_cols < linebuf.length()) num_cols = linebuf.length();
      num_rows++;
      strbuf.append("\n" + linebuf.toString());
      strbuf.append("\n");

      print_status = getPrintStatus(shade_topo);
      strbuf.append("\n" + CategoryWeight.getPrintTitle(print_status));
      twgts = shade.arrayOfCategoryWeights();
      for (idx = 0; idx < twgts.length; idx++) {
        twgt = twgts[idx];
        twgt_str = twgt.toInfoBoxString(print_status);
        if (twgt.getCategory().equals(type)) {
          twgt_str += "  <---";
          if (num_cols < twgt_str.length() + 6) num_cols = twgt_str.length() + 6;
        } else {
          if (num_cols < twgt_str.length()) num_cols = twgt_str.length();
        }
        num_rows++;
        strbuf.append("\n" + twgt_str);
      }
    }
Example #24
0
 private static String toString(Node node) {
   StringBuffer sb = new StringBuffer();
   renderNode(sb, node);
   return sb.toString();
 }
Example #25
0
  // Recursively walk the tree and write the nodes to a StringWriter.
  private static void renderNode(StringBuffer sb, Node node) {
    if (node == null) {
      sb.append("null");
      return;
    }
    switch (node.getNodeType()) {
      case Node.DOCUMENT_NODE:
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        Node root = ((Document) node).getDocumentElement();
        renderNode(sb, root);
        break;

      case Node.ELEMENT_NODE:
        String name = getNodeNameWithNamespace(node);
        NamedNodeMap attributes = node.getAttributes();
        if (attributes.getLength() == 0) {
          sb.append("<" + name + ">");
        } else {
          sb.append("<" + name + " ");
          int attrlen = attributes.getLength();
          for (int i = 0; i < attrlen; i++) {
            Node attr = attributes.item(i);
            String attrName = getNodeNameWithNamespace(attr);
            sb.append(attrName + "=\"" + escapeChars(attr.getNodeValue()));
            if (i < attrlen - 1) sb.append("\" ");
            else sb.append("\">");
          }
        }
        NodeList children = node.getChildNodes();
        if (children != null) {
          for (int i = 0; i < children.getLength(); i++) {
            renderNode(sb, children.item(i));
          }
        }
        sb.append("</" + name + ">");
        break;

      case Node.TEXT_NODE:
        sb.append(escapeChars(node.getNodeValue()));
        break;

      case Node.CDATA_SECTION_NODE:
        sb.append("<![CDATA[" + node.getNodeValue() + "]]>");
        break;

      case Node.PROCESSING_INSTRUCTION_NODE:
        sb.append("<?" + node.getNodeName() + " " + escapeChars(node.getNodeValue()) + "?>");
        break;

      case Node.ENTITY_REFERENCE_NODE:
        sb.append("&" + node.getNodeName() + ";");
        break;

      case Node.DOCUMENT_TYPE_NODE:
        // Ignore document type nodes
        break;

      case Node.COMMENT_NODE:
        sb.append("<!--" + node.getNodeValue() + "-->");
        break;
    }
    return;
  }
    /** 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());
      }
    }
 /** 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);
 }
    private void setEndCoordsText(
        final Coord start_vtx,
        final Coord final_vtx,
        double earliest_time,
        double latest_time,
        int coords_length) {
      StringBuffer linebuf;
      Coord vertex;
      YaxisTreeNode node;
      TreeNode[] nodes;
      Integer lineID;
      double duration;
      int idx, ii;

      duration = latest_time - earliest_time;
      linebuf = new StringBuffer();
      linebuf.append("duration (max) = " + tfmt.format(duration));
      if (num_cols < linebuf.length()) num_cols = linebuf.length();
      num_rows++;
      strbuf.append(linebuf.toString());

      idx = 0;
      linebuf = new StringBuffer("[" + idx + "]: ");
      vertex = start_vtx;
      lineID = new Integer(vertex.lineID);
      node = (YaxisTreeNode) map_line2treenodes.get(lineID);
      nodes = node.getPath();
      linebuf.append("time (min) = " + fmt.format(earliest_time));
      for (ii = 1; ii < nodes.length; ii++)
        linebuf.append(", " + y_colnames[ii - 1] + " = " + nodes[ii]);
      if (num_cols < linebuf.length()) num_cols = linebuf.length();
      num_rows++;
      strbuf.append("\n" + linebuf.toString());

      idx = coords_length - 1;
      linebuf = new StringBuffer("[" + idx + "]: ");
      vertex = final_vtx;
      lineID = new Integer(vertex.lineID);
      node = (YaxisTreeNode) map_line2treenodes.get(lineID);
      nodes = node.getPath();
      linebuf.append("time (max) = " + fmt.format(latest_time));
      for (ii = 1; ii < nodes.length; ii++)
        linebuf.append(", " + y_colnames[ii - 1] + " = " + nodes[ii]);
      if (num_cols < linebuf.length()) num_cols = linebuf.length();
      num_rows++;
      strbuf.append("\n" + linebuf.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);
    }
  }
 private static String generatePassword() {
   StringBuffer sb = new StringBuffer();
   for (int i = 0; i < 4; i++) sb.append((char) (random.nextInt(26) + 'a'));
   return new String(sb);
 }