public StringBuffer saveStringBuffer() {
   StringBuffer save = new StringBuffer();
   for (java.util.Enumeration<Editor> e = pageList.elements(); e.hasMoreElements(); ) {
     Editor page = e.nextElement();
     save.append(
         "<"
             + name
             + ".Page>\n"
             + "<Type>"
             + typeOfPage(page)
             + "</Type>\n"
             + "<Name>"
             + page.getName()
             + "</Name>\n"
             + "<Active>"
             + page.isActive()
             + "</Active>\n"
             + "<"
             + contentDelim
             + ">\n");
     save.append(page.saveStringBuffer());
     save.append("</" + contentDelim + ">\n" + "</" + name + ".Page>\n");
   }
   return save;
 }
Exemple #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();
  }
Exemple #3
0
 /**
  * Get the <code>String</code> that represents this <code>MetSymbol</code>.
  *
  * @return <code>String</code> representation.
  */
 public String toString() {
   StringBuffer sb = new StringBuffer(super.toString());
   for (String s : paramIds) {
     sb.append(" param:" + s);
   }
   return sb.toString();
 }
Exemple #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 StringBuffer generateCode(int _type, String _info) {
   StringBuffer code = new StringBuffer();
   String genName, passName;
   int index = name.lastIndexOf('.');
   if (index >= 0) genName = name.substring(index + 1).toLowerCase();
   else genName = name.toLowerCase();
   if (_info != null && _info.trim().length() > 0) passName = _info;
   else {
     passName = getName();
     if (passName.startsWith("Osejs.")) passName = passName.substring(6);
   }
   index = 0;
   for (Editor editor : pageList) {
     if (editor instanceof CodeEditor) {
       index++;
       ((CodeEditor) editor).setCodeName(genName + index);
     } else if (editor instanceof EquationEditor) {
       index++;
       ((EquationEditor) editor).setCodeName(genName + index);
     }
     // if (editor.isActive())
     code.append(editor.generateCode(_type, passName));
   }
   return code;
 }
Exemple #6
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;
  }
Exemple #7
0
  private void processKey(char c) {

    if (c == '\n') {

      AppUser user = null;
      try {
        user = m_dlSystem.findPeopleByCard(inputtext.toString());
      } catch (BasicException e) {
        e.printStackTrace();
      }

      if (user == null) {
        // user not found
        MessageInf msg =
            new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.nocard"));
        msg.show(this);
      } else {
        openAppView(user);
      }

      inputtext = new StringBuffer();
    } else {
      inputtext.append(c);
    }
  }
Exemple #8
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));
    }
  }
  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");
  }
    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());
    }
 /**
  * ** Reads a line from the specified socket's input stream ** @param socket The socket to read a
  * line from ** @param maxLen The maximum length of of the line to read ** @param sb The string
  * buffer to use ** @throws IOException if an error occurs or the server has stopped
  */
 protected static String socketReadLine(Socket socket, int maxLen, StringBuffer sb)
     throws IOException {
   if (socket != null) {
     int dataLen = 0;
     StringBuffer data = (sb != null) ? sb : new StringBuffer();
     InputStream input = socket.getInputStream();
     while ((maxLen < 0) || (maxLen > dataLen)) {
       int ch = input.read();
       // Print.logInfo("ReadLine char: " + ch);
       if (ch < 0) {
         // this means that the server has stopped
         throw new IOException("End of input");
       } else if (ch == LineTerminatorChar) {
         // include line terminator in String
         data.append((char) ch);
         dataLen++;
         break;
       } else {
         // append character
         data.append((char) ch);
         dataLen++;
       }
     }
     return data.toString();
   } else {
     return null;
   }
 }
    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();
      }
    }
Exemple #13
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;
  }
    /**
     * 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);
    }
Exemple #15
0
  /**
   * Get the Lincese text from a text file specified in the PropertyBox.
   *
   * @return String - License text.
   */
  public String getLicenseText() {
    StringBuffer textBuffer = new StringBuffer();
    try {
      String fileName = RuntimeProperties.GPL_EN_LICENSE_FILE_NAME;
      if (cbLang != null
          && cbLang.getSelectedItem() != null
          && cbLang.getSelectedItem().toString().equalsIgnoreCase("Eesti")) {
        fileName = RuntimeProperties.GPL_EE_LICENSE_FILE_NAME;
      }

      InputStream is = this.getClass().getClassLoader().getResourceAsStream(fileName);

      if (is == null) return "";

      BufferedReader in = new BufferedReader(new InputStreamReader(is));
      String str;
      while ((str = in.readLine()) != null) {
        textBuffer.append(str);
        textBuffer.append("\n");
      }
      in.close();
    } catch (IOException e) {
      logger.error(null, e);
    }
    return textBuffer.toString();
  } // getLicenseText
Exemple #16
0
  public static String cleanText(String text) {
    StringBuffer string = new StringBuffer(text.length());
    char chars[] = text.toCharArray();
    for (int x = 0; x < chars.length; x++) {
      if (chars[x] != 1 && chars[x] != 2) string.append(chars[x]);
    }

    return string.toString();
  }
  /** Opens a dialog that displays the operational attributes of the current entry. */
  public void displayOperationalAttributes() {
    JXplorerBrowser jx = null;

    if (owner instanceof JXplorerBrowser) jx = (JXplorerBrowser) owner;
    else return;

    showingOperationalAttributes = !showingOperationalAttributes;

    // EJP 17 August 2010.
    // CB 14 August 2012 - some directories (looking at you Active Directory) don't support the '+'
    // operator... so do it manually as well...
    String[] opAttrs = {
      "+",
      "createTimeStamp",
      "creatorsName",
      "entryFlags",
      "federationBoundary",
      "localEntryID",
      "modifiersName",
      "modifyTimeStamp",
      "structuralObjectClass",
      "subordinateCount",
      "subschemaSubentry"
    };
    DXEntry entry = null;

    if (showingOperationalAttributes) {
      try {
        entry = (jx.getSearchBroker()).unthreadedReadEntry(currentDN, opAttrs);
        StringBuffer buffy = new StringBuffer("DN: " + currentDN.toString() + "\n\n");

        // Get the attribute values...
        // EJP 17 August 2010: use the actual attributes returned.
        NamingEnumeration ne = null;

        try {
          ne = entry.getAll();
          while (ne.hasMore()) {
            DXAttribute att = (DXAttribute) ne.next();
            buffy.append(att.getName() + ": " + att.get().toString() + "\n");

            tableData.insertOperationalAttribute(att);
          }
        } finally {
          if (ne != null) ne.close();
        }

        tableData.fireTableDataChanged();
      } catch (NamingException e) {
        CBUtility.error(
            TableAttributeEditor.this, CBIntText.get("Unable to read entry " + currentDN), e);
      }
    } else {
      tableData.removeOperationalAttributes();
      tableData.fireTableDataChanged();
    }
  }
 {
   StringBuffer sb = new StringBuffer();
   StringTokenizer st = new StringTokenizer(cfg.REQPARAM_CONTACT_LIST_LOGIN_IDS, ",");
   while (st.hasMoreTokens()) {
     sb.append(st.nextToken());
     if (st.hasMoreTokens()) sb.append("\n");
   }
   contactList.setText(sb.toString());
 }
Exemple #19
0
 /**
  * ** Returns the bean method name for the specified field ** @param prefix Either "get" or "set"
  * ** @param fieldName The field name ** @return The 'getter'/'setter' method name
  */
 protected static String _beanMethodName(String prefix, String fieldName) {
   if ((prefix != null) && (fieldName != null)) {
     StringBuffer sb = new StringBuffer(prefix);
     sb.append(fieldName.substring(0, 1).toUpperCase());
     sb.append(fieldName.substring(1));
     return sb.toString();
   } else {
     return "";
   }
 }
 private String bigIntToHexString(BigInteger bi) {
   StringBuffer buf = new StringBuffer();
   buf.append("0x");
   String val = bi.toString(16);
   for (int i = 0; i < ((2 * addressSize) - val.length()); i++) {
     buf.append('0');
   }
   buf.append(val);
   return buf.toString();
 }
    private void outdentText(JTextComponent textComponent) throws BadLocationException {
      int tabSize =
          ((Integer) textComponent.getDocument().getProperty(PlainDocument.tabSizeAttribute))
              .intValue();

      String selectedText = textComponent.getSelectedText();
      int newLineIndex = selectedText != null ? selectedText.indexOf('\n') : -1;

      if (newLineIndex >= 0) {
        int originalSelectionStart = textComponent.getSelectionStart();
        int selectionStart = originalSelectionStart;
        int selectionEnd = textComponent.getSelectionEnd();

        int lastNewLineBeforeSelection = textComponent.getText(0, selectionStart).lastIndexOf('\n');
        int begin = lastNewLineBeforeSelection >= 0 ? lastNewLineBeforeSelection : 0;
        int end = selectionEnd;

        String text = textComponent.getText(begin, end - begin);
        if (lastNewLineBeforeSelection < 0) {
          text = "\n" + text;
        }
        int len = text.length();
        StringBuffer out = new StringBuffer(len);
        for (int i = 0; i < len; i++) {
          char ch = text.charAt(i);
          out.append(ch);
          if (ch == '\n' && i < len - 1) {
            char next = text.charAt(i + 1);
            int stripCount = 0;
            if (next == '\t') {
              stripCount = 1;
            } else {
              for (; stripCount < tabSize && i + 1 + stripCount < len; stripCount++) {
                next = text.charAt(i + 1 + stripCount);
                if (next != ' ' && next != '\t') {
                  break;
                }
              }
            }

            selectionEnd -= stripCount;
            if (i + begin < originalSelectionStart - 1) {
              selectionStart -= stripCount;
            }
            i += stripCount;
          }
        }

        textComponent.select(begin, end);
        textComponent.replaceSelection(
            lastNewLineBeforeSelection < 0 ? out.toString().substring(1) : out.toString());

        textComponent.select(selectionStart, selectionEnd);
      }
    }
 public String getSelectionText() {
   RenderablePoint start = this.startSelection;
   RenderablePoint end = this.endSelection;
   if (start != null && end != null) {
     StringBuffer buffer = new StringBuffer();
     this.rblock.extractSelectionText(buffer, false, start, end);
     return buffer.toString();
   } else {
     return null;
   }
 }
 void setTextFromTile(TileI tile) {
   StringBuffer text = new StringBuffer();
   if (Util.hasValue(tile.getExternalId())) {
     text.append("<HTML><BODY>" + tile.getExternalId());
     if (tile.countFreeTiles() != -1) {
       text.append("<BR> (" + tile.countFreeTiles() + ")");
     }
     text.append("</BODY></HTML>");
   }
   this.setText(text.toString());
 }
  public String getSelectedRobotsAsString() {
    StringBuffer sb = new StringBuffer();

    for (int i = 0; i < selectedRobots.size(); i++) {
      if (i != 0) {
        sb.append(',');
      }
      sb.append(selectedRobots.get(i).getItem().getUniqueFullClassNameWithVersion());
    }
    return 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());
  }
Exemple #26
0
 /**
  * This method is activated on the Keystrokes we are listening to in this implementation. Here it
  * listens for Copy and Paste ActionCommands. Selections comprising non-adjacent cells result in
  * invalid selection and then copy action cannot be performed. Paste is done by aligning the upper
  * left corner of the selection with the 1st element in the current selection of the JTable.
  */
 public void actionPerformed(ActionEvent e) {
   if (e.getActionCommand().compareTo("Copy") == 0) {
     StringBuffer sbf = new StringBuffer();
     // Check to ensure we have selected only a contiguous block of
     // cells
     int numcols = jTable1.getSelectedColumnCount();
     int numrows = jTable1.getSelectedRowCount();
     int[] rowsselected = jTable1.getSelectedRows();
     int[] colsselected = jTable1.getSelectedColumns();
     if (!((numrows - 1 == rowsselected[rowsselected.length - 1] - rowsselected[0]
             && numrows == rowsselected.length)
         && (numcols - 1 == colsselected[colsselected.length - 1] - colsselected[0]
             && numcols == colsselected.length))) {
       JOptionPane.showMessageDialog(
           null, "Invalid Copy Selection", "Invalid Copy Selection", JOptionPane.ERROR_MESSAGE);
       return;
     }
     for (int i = 0; i < numrows; i++) {
       for (int j = 0; j < numcols; j++) {
         sbf.append(jTable1.getValueAt(rowsselected[i], colsselected[j]));
         if (j < numcols - 1) sbf.append("\t");
       }
       sbf.append("\n");
     }
     stsel = new StringSelection(sbf.toString());
     system = Toolkit.getDefaultToolkit().getSystemClipboard();
     system.setContents(stsel, stsel);
   }
   if (e.getActionCommand().compareTo("Paste") == 0) {
     System.out.println("Trying to Paste");
     int startRow = (jTable1.getSelectedRows())[0];
     int startCol = (jTable1.getSelectedColumns())[0];
     try {
       String trstring =
           (String) (system.getContents(this).getTransferData(DataFlavor.stringFlavor));
       System.out.println("String is:" + trstring);
       StringTokenizer st1 = new StringTokenizer(trstring, "\n");
       for (int i = 0; st1.hasMoreTokens(); i++) {
         rowstring = st1.nextToken();
         StringTokenizer st2 = new StringTokenizer(rowstring, "\t");
         for (int j = 0; st2.hasMoreTokens(); j++) {
           value = (String) st2.nextToken();
           if (startRow + i < jTable1.getRowCount() && startCol + j < jTable1.getColumnCount())
             jTable1.setValueAt(value, startRow + i, startCol + j);
           System.out.println(
               "Putting " + value + "at row = " + startRow + i + "column = " + startCol + j);
         }
       }
     } catch (Exception ex) {
       ex.printStackTrace();
     }
   }
 }
 public static String getArtistName(String st) throws Exception {
   st = new File(st).toURL().toString();
   String st2[] = st.split("/");
   StringBuffer stb = new StringBuffer(st2[st2.length - 1]);
   StringBuffer stb2 = stb.reverse();
   String st3 = new String(stb2);
   int i = 0;
   while (st3.charAt(i) != '.') i++;
   String a = st3.substring(i + 1, st3.length());
   if (a.length() >= 21) a = "..." + a.substring(a.length() - 21, a.length());
   return (new String(new StringBuffer(a).reverse()));
 }
Exemple #28
0
  private String readLine(FileReader fileReader) throws IOException {

    StringBuffer line = new StringBuffer();

    int c;

    while ((c = fileReader.read()) != '\n') {
      line.append((char) c);
    }

    return line.toString();
  }
 private String safe(String src) {
   StringBuffer sb = new StringBuffer();
   for (int i = 0; i < src.length(); i++) {
     char c = src.charAt(i);
     if (c >= 32 && c < 128) {
       sb.append(c);
     } else {
       sb.append("<" + (int) c + ">");
     }
   }
   return sb.toString();
 }
  void findRemoveDirectives(boolean clean) {
    // if ( clean ) editor.startCompoundEdit();

    Sketch sketch = editor.getSketch();
    for (int i = 0; i < sketch.getCodeCount(); i++) {
      SketchCode code = sketch.getCode(i);
      String program = code.getProgram();
      StringBuffer buffer = new StringBuffer();

      Matcher m = pjsPattern.matcher(program);
      while (m.find()) {
        String mm = m.group();

        // TODO this urgently needs tests ..

        /* remove framing */
        mm = mm.replaceAll("^\\/\\*\\s*@pjs", "").replaceAll("\\s*\\*\\/\\s*$", "");
        /* fix multiline nice formatting */
        mm = mm.replaceAll("[\\s]*([^;\\s\\n\\r]+)[\\s]*,[\\s]*[\\n\\r]+", "$1,");
        /* fix multiline version without semicolons */
        mm = mm.replaceAll("[\\s]*([^;\\s\\n\\r]+)[\\s]*[\\n\\r]+", "$1;");
        mm = mm.replaceAll("\n", " ").replaceAll("\r", " ");

        // System.out.println(mm);

        if (clean) {
          m.appendReplacement(buffer, "");
        } else {
          String[] directives = mm.split(";");
          for (String d : directives) {
            // System.out.println(d);
            parseDirective(d);
          }
        }
      }

      if (clean) {
        m.appendTail(buffer);

        // TODO: not working!
        code.setProgram(buffer.toString());
        code.setModified(true);
      }
    }

    if (clean) {
      // editor.stopCompoundEdit();
      editor.setText(sketch.getCurrentCode().getProgram());
      sketch.setModified(false);
      sketch.setModified(true);
    }
  }