private static final class MessageFormatter {
    private static final Pattern variablePattern =
        Pattern.compile("(?i)\\$(\\{[a-z0-9_]{1,}\\}|[a-z0-9_]{1,})");
    private static final Pattern colorPattern = Pattern.compile("(?i)&[0-9A-FK-OR]");

    private final Map<String, String> variables;

    public MessageFormatter() {
      variables = new HashMap<String, String>();
    }

    public synchronized void setVariable(String variable, String value) {
      if (value == null) variables.remove(value);
      else variables.put(variable, value);
    }

    public synchronized String format(String message) {
      Matcher matcher = variablePattern.matcher(message);
      while (matcher.find()) {
        String variable = matcher.group();
        variable = variable.substring(1);
        if (variable.startsWith("{") && variable.endsWith("}"))
          variable = variable.substring(1, variable.length() - 1);
        String value = variables.get(variable);
        if (value == null) value = "";
        message =
            message.replaceFirst(Pattern.quote(matcher.group()), Matcher.quoteReplacement(value));
      }
      matcher = colorPattern.matcher(message);
      while (matcher.find())
        message =
            message.substring(0, matcher.start()) + "\247" + message.substring(matcher.end() - 1);
      return message;
    }
  }
Esempio n. 2
0
 @Override
 public void actionPerformed(ActionEvent e) {
   if (td.getTabCount() > 0) {
     TextDocument ta = (TextDocument) td.getComponentAt(td.getSelectedIndex());
     Pattern pn = Pattern.compile(tf1.getText());
     Matcher mt = pn.matcher(ta.getText());
     if (e.getSource() == jb2) { // 取代
       ta.setText(mt.replaceAll(tf2.getText()));
     } else if (e.getSource() == jb1) { // 尋找
       Highlighter hl = ta.getHighlighter();
       hl.removeAllHighlights();
       while (mt.find()) {
         try {
           hl.addHighlight(
               mt.start(), mt.end(), new DefaultHighlighter.DefaultHighlightPainter(null));
         } catch (Exception ex) {
         }
       } // 開啟及關閉介面
     } else if (e.getSource() == replace_searchMenuItem) {
       System.out.println("Replace/Search is show:" + !show);
       if (show) {
         getContentPane().remove(jp);
         show = false;
       } else {
         getContentPane().add(jp, BorderLayout.SOUTH);
         show = true;
       }
       validate(); // 刷新容器
     }
   } else if (e.getSource() == replace_searchMenuItem) {
     JOptionPane.showMessageDialog(
         null, "尚無檔案,無法使用!", "Repace/Search error", JOptionPane.ERROR_MESSAGE);
   }
 }
Esempio n. 3
0
  public void setHexColor(String c) // Set edge color
      {
    // Pattern p = new Pattern.compile("#[0-9a-fA-F]{6}");
    // Matcher m = new p.Matcher(c);

    if (Pattern.compile("#[0-9a-fA-F]{6}").matcher(c).matches()) hexColor = c;
  }
Esempio n. 4
0
  public DirectivesEditor(JavaScriptEditor e) {
    editor = e;

    if (frame == null) createFrame();

    // see processing-1.2.0.js
    pjsPattern =
        Pattern.compile("\\/\\*\\s*@pjs\\s+((?:[^\\*]|\\*+[^\\*\\/])*)\\*\\/\\s*", Pattern.DOTALL);
  }
 private String htmlize(String msg) {
   StringBuilder sb = new StringBuilder();
   Pattern patMsgCat = Pattern.compile("\\[(.+?)\\].*");
   msg = msg.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;");
   for (String line : msg.split(lineSep)) {
     Matcher m = patMsgCat.matcher(line);
     String cls = "normal";
     if (m.matches()) {
       cls = m.group(1);
     }
     line = "<span class='" + cls + "'>" + line + "</span>";
     sb.append(line).append("<br>");
   }
   return sb.toString();
 }
 @Override
 @EventHandler
 public void onChatReceived(ChatReceivedEvent event) {
   super.onChatReceived(event);
   String message = Util.stripColors(event.getMessage());
   if (message.startsWith("Please register with \"/register")) {
     String password = Util.generateRandomString(10 + random.nextInt(6));
     bot.say("/register " + password + " " + password);
   } else if (message.contains("You are not member of any faction.")
       && spamMessage != null
       && createFaction) {
     String msg = "/f create " + Util.generateRandomString(7 + random.nextInt(4));
     bot.say(msg);
   }
   for (String s : captchaList) {
     Matcher captchaMatcher = Pattern.compile(s).matcher(message);
     if (captchaMatcher.matches()) bot.say(captchaMatcher.group(1));
   }
 }
 private static List<String> loadAccounts(String fileName) {
   List<String> accounts = new ArrayList<String>();
   try {
     Pattern pattern = Pattern.compile("[\\w]{1,16}");
     BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));
     String line;
     while ((line = reader.readLine()) != null) {
       Matcher matcher = pattern.matcher(line);
       if (!matcher.find()) continue;
       String username = matcher.group();
       if (!matcher.find()) continue;
       String password = matcher.group();
       accounts.add(username + ":" + password);
     }
     reader.close();
   } catch (Exception exception) {
     throw new RuntimeException(exception);
   }
   System.out.println("Loaded " + accounts.size() + " accounts.");
   return accounts;
 }
Esempio n. 8
0
/**
 * This view allows the input and evaluation of queries and documents.
 *
 * @author BaseX Team 2005-12, BSD License
 * @author Christian Gruen
 */
public final class EditorView extends View {
  /** Error string. */
  private static final String ERRSTRING =
      STOPPED_AT + ' ' + (LINE_X + ", " + COLUMN_X).replaceAll("%", "([0-9]+)");
  /** XQuery error pattern. */
  private static final Pattern XQERROR =
      Pattern.compile(ERRSTRING + ' ' + IN_FILE_X.replaceAll("%", "(.*?)") + COL);
  /** XML error pattern. */
  private static final Pattern XMLERROR =
      Pattern.compile(LINE_X.replaceAll("%", "(.*?)") + COL + ".*");

  /** History Button. */
  final BaseXButton hist;
  /** Execute Button. */
  final BaseXButton stop;
  /** Info label. */
  final BaseXLabel info;
  /** Position label. */
  final BaseXLabel pos;
  /** Query area. */
  final BaseXTabs tabs;
  /** Execute button. */
  final BaseXButton go;
  /** Thread counter. */
  int threadID;

  /** File in which the most recent error occurred. */
  String errFile;
  /** Most recent error position; used for clicking on error message. */
  int errPos;

  /** Header string. */
  private final BaseXLabel header;
  /** Filter button. */
  private final BaseXButton filter;

  /** Search panel. */
  public final SearchPanel search;

  /**
   * Default constructor.
   *
   * @param man view manager
   */
  public EditorView(final ViewNotifier man) {
    super(EDITORVIEW, man);
    if (Prop.langright) applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

    border(6, 6, 6, 6).layout(new BorderLayout(0, 2)).setFocusable(false);

    header = new BaseXLabel(EDITOR, true, false);

    final BaseXButton srch = new BaseXButton(gui, "search", H_REPLACE);
    final BaseXButton openB = BaseXButton.command(GUICommands.C_EDITOPEN, gui);
    final BaseXButton saveB = new BaseXButton(gui, "save", H_SAVE);
    hist = new BaseXButton(gui, "hist", H_RECENTLY_OPEN);

    final BaseXBack buttons = new BaseXBack(Fill.NONE);
    buttons.layout(new TableLayout(1, 4, 1, 0));
    buttons.add(srch);
    buttons.add(openB);
    buttons.add(saveB);
    buttons.add(hist);

    final BaseXBack b = new BaseXBack(Fill.NONE).layout(new BorderLayout(8, 0));
    if (Prop.langright) {
      b.add(header, BorderLayout.EAST);
      b.add(buttons, BorderLayout.WEST);
    } else {
      b.add(header, BorderLayout.CENTER);
      b.add(buttons, BorderLayout.EAST);
    }
    add(b, BorderLayout.NORTH);

    tabs = new BaseXTabs(gui);
    tabs.setFocusable(false);
    final SearchEditor se = new SearchEditor(gui, tabs, null).button(srch);
    search = se.panel();
    addCreateTab();
    add(se, BorderLayout.CENTER);

    // status and query pane
    search.editor(addTab(), false);

    info = new BaseXLabel().setText(OK, Msg.SUCCESS);
    pos = new BaseXLabel(" ");
    posCode.invokeLater();

    stop = new BaseXButton(gui, "stop", H_STOP_PROCESS);
    stop.addKeyListener(this);
    stop.setEnabled(false);

    go = new BaseXButton(gui, "go", H_EXECUTE_QUERY);
    go.addKeyListener(this);

    filter = BaseXButton.command(GUICommands.C_FILTER, gui);
    filter.addKeyListener(this);
    filter.setEnabled(false);

    final BaseXBack status = new BaseXBack(Fill.NONE).layout(new BorderLayout(4, 0));
    status.add(info, BorderLayout.CENTER);
    status.add(pos, BorderLayout.EAST);

    final BaseXBack query = new BaseXBack(Fill.NONE).layout(new TableLayout(1, 3, 1, 0));
    query.add(stop);
    query.add(go);
    query.add(filter);

    final BaseXBack south = new BaseXBack(Fill.NONE).border(4, 0, 0, 0);
    south.layout(new BorderLayout(8, 0));
    south.add(status, BorderLayout.CENTER);
    south.add(query, BorderLayout.EAST);
    add(south, BorderLayout.SOUTH);

    refreshLayout();

    // add listeners
    saveB.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(final ActionEvent e) {
            final JPopupMenu pop = new JPopupMenu();
            final StringBuilder mnem = new StringBuilder();
            final JMenuItem sa = GUIMenu.newItem(GUICommands.C_EDITSAVE, gui, mnem);
            final JMenuItem sas = GUIMenu.newItem(GUICommands.C_EDITSAVEAS, gui, mnem);
            GUICommands.C_EDITSAVE.refresh(gui, sa);
            GUICommands.C_EDITSAVEAS.refresh(gui, sas);
            pop.add(sa);
            pop.add(sas);
            pop.show(saveB, 0, saveB.getHeight());
          }
        });
    hist.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(final ActionEvent e) {
            final JPopupMenu pm = new JPopupMenu();
            final ActionListener al =
                new ActionListener() {
                  @Override
                  public void actionPerformed(final ActionEvent ac) {
                    open(new IOFile(ac.getActionCommand()));
                  }
                };
            final StringList sl = new StringList();
            for (final EditorArea ea : editors()) sl.add(ea.file.path());
            for (final String en :
                new StringList().add(gui.gprop.strings(GUIProp.EDITOR)).sort(!Prop.WIN, true)) {
              final JMenuItem it = new JMenuItem(en);
              it.setEnabled(!sl.contains(en));
              pm.add(it).addActionListener(al);
            }
            pm.show(hist, 0, hist.getHeight());
          }
        });
    refreshHistory(null);
    info.addMouseListener(
        new MouseAdapter() {
          @Override
          public void mouseClicked(final MouseEvent e) {
            EditorArea ea = getEditor();
            if (errFile != null) {
              ea = find(IO.get(errFile), false);
              if (ea == null) ea = open(new IOFile(errFile));
              tabs.setSelectedComponent(ea);
            }
            if (errPos == -1) return;
            ea.jumpError(errPos);
            posCode.invokeLater();
          }
        });
    stop.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(final ActionEvent e) {
            stop.setEnabled(false);
            go.setEnabled(false);
            gui.stop();
          }
        });
    go.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(final ActionEvent e) {
            getEditor().release(Action.EXECUTE);
          }
        });
    tabs.addChangeListener(
        new ChangeListener() {
          @Override
          public void stateChanged(final ChangeEvent e) {
            final EditorArea ea = getEditor();
            if (ea == null) return;
            search.editor(ea, true);
            gui.refreshControls();
            posCode.invokeLater();
          }
        });

    BaseXLayout.addDrop(
        this,
        new DropHandler() {
          @Override
          public void drop(final Object file) {
            if (file instanceof File) open(new IOFile((File) file));
          }
        });
  }

  @Override
  public void refreshInit() {}

  @Override
  public void refreshFocus() {}

  @Override
  public void refreshMark() {
    final EditorArea edit = getEditor();
    go.setEnabled(edit.script || edit.xquery && !gui.gprop.is(GUIProp.EXECRT));
    final Nodes mrk = gui.context.marked;
    filter.setEnabled(!gui.gprop.is(GUIProp.FILTERRT) && mrk != null && mrk.size() != 0);
  }

  @Override
  public void refreshContext(final boolean more, final boolean quick) {}

  @Override
  public void refreshLayout() {
    header.setFont(GUIConstants.lfont);
    for (final EditorArea edit : editors()) edit.setFont(GUIConstants.mfont);
    search.refreshLayout();
  }

  @Override
  public void refreshUpdate() {}

  @Override
  public boolean visible() {
    return gui.gprop.is(GUIProp.SHOWEDITOR);
  }

  @Override
  public void visible(final boolean v) {
    gui.gprop.set(GUIProp.SHOWEDITOR, v);
  }

  @Override
  protected boolean db() {
    return false;
  }

  /** Opens a new file. */
  public void open() {
    // open file chooser for XML creation
    final BaseXFileChooser fc = new BaseXFileChooser(OPEN, gui.gprop.get(GUIProp.WORKPATH), gui);
    fc.filter(BXS_FILES, IO.BXSSUFFIX);
    fc.filter(XQUERY_FILES, IO.XQSUFFIXES);
    fc.filter(XML_DOCUMENTS, IO.XMLSUFFIXES);

    final IOFile[] files = fc.multi().selectAll(Mode.FOPEN);
    for (final IOFile f : files) open(f);
  }

  /** Reverts the contents of the currently opened editor. */
  public void reopen() {
    getEditor().reopen(true);
  }

  /**
   * Saves the contents of the currently opened editor.
   *
   * @return {@code false} if operation was canceled
   */
  public boolean save() {
    final EditorArea edit = getEditor();
    return edit.opened() ? save(edit.file) : saveAs();
  }

  /**
   * Saves the contents of the currently opened editor under a new name.
   *
   * @return {@code false} if operation was canceled
   */
  public boolean saveAs() {
    // open file chooser for XML creation
    final EditorArea edit = getEditor();
    final BaseXFileChooser fc =
        new BaseXFileChooser(SAVE_AS, edit.file.path(), gui).filter(XQUERY_FILES, IO.XQSUFFIXES);

    final IOFile file = fc.select(Mode.FSAVE);
    return file != null && save(file);
  }

  /** Creates a new file. */
  public void newFile() {
    addTab();
    refreshControls(true);
  }

  /**
   * Opens the specified query file.
   *
   * @param file query file
   * @return opened editor
   */
  public EditorArea open(final IOFile file) {
    if (!visible()) GUICommands.C_SHOWEDITOR.execute(gui);

    EditorArea edit = find(file, true);
    try {
      if (edit != null) {
        // display open file
        tabs.setSelectedComponent(edit);
        edit.reopen(true);
      } else {
        // get current editor
        edit = getEditor();
        // create new tab if current text is stored on disk or has been modified
        if (edit.opened() || edit.modified) edit = addTab();
        edit.initText(file.read());
        edit.file(file);
      }
    } catch (final IOException ex) {
      BaseXDialog.error(gui, FILE_NOT_OPENED);
    }
    return edit;
  }

  /**
   * Refreshes the list of recent query files and updates the query path.
   *
   * @param file new file
   */
  void refreshHistory(final IOFile file) {
    final StringList sl = new StringList();
    String path = null;
    if (file != null) {
      path = file.path();
      gui.gprop.set(GUIProp.WORKPATH, file.dirPath());
      sl.add(path);
      tabs.setToolTipTextAt(tabs.getSelectedIndex(), path);
    }
    final String[] qu = gui.gprop.strings(GUIProp.EDITOR);
    for (int q = 0; q < qu.length && q < 19; q++) {
      final String f = qu[q];
      if (!f.equalsIgnoreCase(path) && IO.get(f).exists()) sl.add(f);
    }
    // store sorted history
    gui.gprop.set(GUIProp.EDITOR, sl.toArray());
    hist.setEnabled(!sl.isEmpty());
  }

  /**
   * Closes an editor.
   *
   * @param edit editor to be closed. {@code null} closes the currently opened editor.
   * @return {@code true} if editor was closed
   */
  public boolean close(final EditorArea edit) {
    final EditorArea ea = edit != null ? edit : getEditor();
    if (!confirm(ea)) return false;

    tabs.remove(ea);
    final int t = tabs.getTabCount();
    final int i = tabs.getSelectedIndex();
    if (t == 1) {
      // reopen single tab
      addTab();
    } else if (i + 1 == t) {
      // if necessary, activate last editor tab
      tabs.setSelectedIndex(i - 1);
    }
    return true;
  }

  /** Jumps to a specific line. */
  public void gotoLine() {
    final EditorArea edit = getEditor();
    final int ll = edit.last.length;
    final int cr = edit.getCaret();
    int l = 1;
    for (int e = 0; e < ll && e < cr; e += cl(edit.last, e)) {
      if (edit.last[e] == '\n') ++l;
    }
    final DialogLine dl = new DialogLine(gui, l);
    if (!dl.ok()) return;
    final int el = dl.line();
    int p = 0;
    l = 1;
    for (int e = 0; e < ll && l < el; e += cl(edit.last, e)) {
      if (edit.last[e] != '\n') continue;
      p = e + 1;
      ++l;
    }
    edit.setCaret(p);
    posCode.invokeLater();
  }

  /** Starts a thread, which shows a waiting info after a short timeout. */
  public void start() {
    final int thread = threadID;
    new Thread() {
      @Override
      public void run() {
        Performance.sleep(200);
        if (thread == threadID) {
          info.setText(PLEASE_WAIT_D, Msg.SUCCESS).setToolTipText(null);
          stop.setEnabled(true);
        }
      }
    }.start();
  }

  /**
   * Evaluates the info message resulting from a parsed or executed query.
   *
   * @param msg info message
   * @param ok {@code true} if evaluation was successful
   * @param up update
   */
  public void info(final String msg, final boolean ok, final boolean up) {
    ++threadID;
    errPos = -1;
    errFile = null;
    getEditor().resetError();

    final String m =
        msg.replaceAll("^.*\r?\n\\[.*?\\]", "")
            .replaceAll(".*" + LINE_X.replaceAll("%", ".*?") + COL, "");
    if (ok) {
      info.setCursor(GUIConstants.CURSORARROW);
      info.setText(m, Msg.SUCCESS).setToolTipText(null);
    } else {
      info.setCursor(error(msg) ? GUIConstants.CURSORHAND : GUIConstants.CURSORARROW);
      info.setText(m, Msg.ERROR).setToolTipText(msg);
    }

    if (up) {
      stop.setEnabled(false);
      refreshMark();
    }
  }

  /**
   * Handles info messages resulting from a query execution.
   *
   * @param msg info message
   * @return true if error was found
   */
  private boolean error(final String msg) {
    final String line = msg.replaceAll("[\\r\\n].*", "");
    Matcher m = XQERROR.matcher(line);
    int el, ec = 2;
    if (!m.matches()) {
      m = XMLERROR.matcher(line);
      if (!m.matches()) return true;
      el = Integer.parseInt(m.group(1));
      errFile = getEditor().file.path();
    } else {
      el = Integer.parseInt(m.group(1));
      ec = Integer.parseInt(m.group(2));
      errFile = m.group(3);
    }

    final EditorArea edit = find(IO.get(errFile), false);
    if (edit == null) return true;

    // find approximate error position
    final int ll = edit.last.length;
    int ep = ll;
    for (int e = 1, l = 1, c = 1; e < ll; ++c, e += cl(edit.last, e)) {
      if (l > el || l == el && c == ec) {
        ep = e;
        break;
      }
      if (edit.last[e] == '\n') {
        ++l;
        c = 0;
      }
    }
    if (ep < ll && Character.isLetterOrDigit(cp(edit.last, ep))) {
      while (ep > 0 && Character.isLetterOrDigit(cp(edit.last, ep - 1))) ep--;
    }
    edit.error(ep);
    errPos = ep;
    return true;
  }

  /**
   * Shows a quit dialog for all modified query files.
   *
   * @return {@code false} if confirmation was canceled
   */
  public boolean confirm() {
    for (final EditorArea edit : editors()) {
      tabs.setSelectedComponent(edit);
      if (!close(edit)) return false;
    }
    return true;
  }

  /**
   * Checks if the current text can be saved or reverted.
   *
   * @param rev revert flag
   * @return result of check
   */
  public boolean modified(final boolean rev) {
    final EditorArea edit = getEditor();
    return edit.modified || !rev && !edit.opened();
  }

  /**
   * Returns the current editor.
   *
   * @return editor
   */
  public EditorArea getEditor() {
    final Component c = tabs.getSelectedComponent();
    return c instanceof EditorArea ? (EditorArea) c : null;
  }

  /**
   * Refreshes the query modification flag.
   *
   * @param force action
   */
  void refreshControls(final boolean force) {
    // update modification flag
    final EditorArea edit = getEditor();
    final boolean oe = edit.modified;
    edit.modified = edit.hist != null && edit.hist.modified();
    if (edit.modified == oe && !force) return;

    // update tab title
    String title = edit.file.name();
    if (edit.modified) title += '*';
    edit.label.setText(title);

    // update components
    gui.refreshControls();
    posCode.invokeLater();
  }

  /** Code for setting cursor position. */
  final GUICode posCode =
      new GUICode() {
        @Override
        public void eval(final Object arg) {
          final int[] lc = getEditor().pos();
          pos.setText(lc[0] + " : " + lc[1]);
        }
      };

  /**
   * Finds the editor that contains the specified file.
   *
   * @param file file to be found
   * @param opened considers only opened files
   * @return editor
   */
  EditorArea find(final IO file, final boolean opened) {
    for (final EditorArea edit : editors()) {
      if (edit.file.eq(file) && (!opened || edit.opened())) return edit;
    }
    return null;
  }

  /**
   * Saves the specified editor contents.
   *
   * @param file file to write
   * @return {@code false} if confirmation was canceled
   */
  private boolean save(final IOFile file) {
    try {
      final EditorArea edit = getEditor();
      file.write(edit.getText());
      edit.file(file);
      return true;
    } catch (final IOException ex) {
      BaseXDialog.error(gui, FILE_NOT_SAVED);
      return false;
    }
  }

  /**
   * Choose a unique tab file.
   *
   * @return io reference
   */
  private IOFile newTabFile() {
    // collect numbers of existing files
    final BoolList bl = new BoolList();
    for (final EditorArea edit : editors()) {
      if (edit.opened()) continue;
      final String n = edit.file.name().substring(FILE.length());
      bl.set(n.isEmpty() ? 1 : Integer.parseInt(n), true);
    }
    // find first free file number
    int c = 0;
    while (++c < bl.size() && bl.get(c)) ;
    // create io reference
    return new IOFile(gui.gprop.get(GUIProp.WORKPATH), FILE + (c == 1 ? "" : c));
  }

  /**
   * Adds a new editor tab.
   *
   * @return editor reference
   */
  EditorArea addTab() {
    final EditorArea edit = new EditorArea(this, newTabFile());
    edit.setFont(GUIConstants.mfont);

    final BaseXBack tab = new BaseXBack(new BorderLayout(10, 0)).mode(Fill.NONE);
    tab.add(edit.label, BorderLayout.CENTER);

    final BaseXButton close = tabButton("e_close");
    close.setRolloverIcon(BaseXLayout.icon("e_close2"));
    close.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(final ActionEvent e) {
            close(edit);
          }
        });
    tab.add(close, BorderLayout.EAST);

    tabs.add(edit, tab, tabs.getComponentCount() - 2);
    return edit;
  }

  /** Adds a tab for creating new tabs. */
  private void addCreateTab() {
    final BaseXButton add = tabButton("e_new");
    add.setRolloverIcon(BaseXLayout.icon("e_new2"));
    add.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(final ActionEvent e) {
            addTab();
            refreshControls(true);
          }
        });
    tabs.add(new BaseXBack(), add, 0);
    tabs.setEnabledAt(0, false);
  }

  /**
   * Adds a new tab button.
   *
   * @param icon button icon
   * @return button
   */
  private BaseXButton tabButton(final String icon) {
    final BaseXButton b = new BaseXButton(gui, icon, null);
    b.border(2, 2, 2, 2).setContentAreaFilled(false);
    b.setFocusable(false);
    return b;
  }

  /**
   * Shows a quit dialog for the specified editor.
   *
   * @param edit editor to be saved
   * @return {@code false} if confirmation was canceled
   */
  private boolean confirm(final EditorArea edit) {
    if (edit.modified && (edit.opened() || edit.getText().length != 0)) {
      final Boolean ok = BaseXDialog.yesNoCancel(gui, Util.info(CLOSE_FILE_X, edit.file.name()));
      if (ok == null || ok && !save()) return false;
    }
    return true;
  }

  /**
   * Returns all editors.
   *
   * @return editors
   */
  EditorArea[] editors() {
    final ArrayList<EditorArea> edits = new ArrayList<EditorArea>();
    for (final Component c : tabs.getComponents()) {
      if (c instanceof EditorArea) edits.add((EditorArea) c);
    }
    return edits.toArray(new EditorArea[edits.size()]);
  }
}
Esempio n. 9
0
  void openButton_actionPerformed(ActionEvent e) {
    String name = nameTextField.getText().trim();
    if (mode == ProfileChooser.MODE_OPEN) { // open
      if (name.equals("")) {
        JOptionPane.showMessageDialog(
            this, SanBootView.res.getString("ProfileChooser.errMsg.notSelect"));
        return;
      }

      UniProfile prof = isSameProfile(name);
      if (prof == null) {
        JOptionPane.showMessageDialog(
            this, SanBootView.res.getString("ProfileChooser.errMsg.notExist") + ": " + name);
        return;
      }

      values = new Object[1];
      values[0] = prof;
    } else { // save as 或 save
      if (name.equals("")) {
        JOptionPane.showMessageDialog(
            this, SanBootView.res.getString("ProfileChooser.errMsg.notName"));
        return;
      }

      String tmpName = name;
      Pattern pattern = Pattern.compile(".+\\.prf");
      Matcher matcher = pattern.matcher(tmpName);
      if (!matcher.find()) {
        tmpName += ".prf";
      }

      UniProfile pf = isSameProfile(tmpName);
      if (pf != null) { // 存 在 相 同 的 名 字 的profile ( pf )
        if (view.initor.mdb.getSchNumOnProfName(pf.getProfileName()) > 0) {
          JOptionPane.showMessageDialog(
              this, SanBootView.res.getString("EditProfileDialog.error.hasSch"));
          return;
        }

        if (JOptionPane.showConfirmDialog( // 提示信息更换
                (Dialog) bakable,
                SanBootView.res.getString("ProfileChooser.confirmmsg1"),
                SanBootView.res.getString("common.confirm"),
                JOptionPane.OK_CANCEL_OPTION)
            == JOptionPane.CANCEL_OPTION) {
          return;
        } else {
          values = new Object[2];
          values[0] = pf;
          values[1] = saveAsProfile;
        }
      } else { // 不 存 在 相 同 的 名 字
        String pname = ResourceCenter.PROFILE_DIR + name + ".prf";

        if (pname.indexOf("\"") >= 0
            || pname.indexOf("'") >= 0
            || pname.indexOf(' ') >= 0
            || pname.indexOf('\t') >= 0) {
          JOptionPane.showMessageDialog(
              this, SanBootView.res.getString("ProfileChooser.errmsg.badname"));
          return;
        }

        if (pname.getBytes().length >= 1000) {
          JOptionPane.showMessageDialog(
              this, SanBootView.res.getString("ProfileChooser.errmsg.tooLargePname"));
          return;
        }

        values = new Object[1];
        saveAsProfile.setProfileName(pname);
        values[0] = saveAsProfile;
      }
    }

    dispose();
  }
Esempio n. 10
0
    public void setPattern(String globPattern) {
      char[] gPat = globPattern.toCharArray();
      char[] rPat = new char[gPat.length * 2];
      boolean isWin32 = (File.separatorChar == '\\');
      boolean inBrackets = false;
      int j = 0;

      this.globPattern = globPattern;

      if (isWin32) {
        // On windows, a pattern ending with *.* is equal to ending with *
        int len = gPat.length;
        if (globPattern.endsWith("*.*")) {
          len -= 2;
        }
        for (int i = 0; i < len; i++) {
          switch (gPat[i]) {
            case '*':
              rPat[j++] = '.';
              rPat[j++] = '*';
              break;

            case '?':
              rPat[j++] = '.';
              break;

            case '\\':
              rPat[j++] = '\\';
              rPat[j++] = '\\';
              break;

            default:
              if ("+()^$.{}[]".indexOf(gPat[i]) >= 0) {
                rPat[j++] = '\\';
              }
              rPat[j++] = gPat[i];
              break;
          }
        }
      } else {
        for (int i = 0; i < gPat.length; i++) {
          switch (gPat[i]) {
            case '*':
              if (!inBrackets) {
                rPat[j++] = '.';
              }
              rPat[j++] = '*';
              break;

            case '?':
              rPat[j++] = inBrackets ? '?' : '.';
              break;

            case '[':
              inBrackets = true;
              rPat[j++] = gPat[i];

              if (i < gPat.length - 1) {
                switch (gPat[i + 1]) {
                  case '!':
                  case '^':
                    rPat[j++] = '^';
                    i++;
                    break;

                  case ']':
                    rPat[j++] = gPat[++i];
                    break;
                }
              }
              break;

            case ']':
              rPat[j++] = gPat[i];
              inBrackets = false;
              break;

            case '\\':
              if (i == 0 && gPat.length > 1 && gPat[1] == '~') {
                rPat[j++] = gPat[++i];
              } else {
                rPat[j++] = '\\';
                if (i < gPat.length - 1 && "*?[]".indexOf(gPat[i + 1]) >= 0) {
                  rPat[j++] = gPat[++i];
                } else {
                  rPat[j++] = '\\';
                }
              }
              break;

            default:
              // if ("+()|^$.{}<>".indexOf(gPat[i]) >= 0) {
              if (!Character.isLetterOrDigit(gPat[i])) {
                rPat[j++] = '\\';
              }
              rPat[j++] = gPat[i];
              break;
          }
        }
      }
      this.pattern = Pattern.compile(new String(rPat, 0, j), Pattern.CASE_INSENSITIVE);
    }
  public void actionPerformed(ActionEvent ae) {
    os = a.getText();
    Pattern pat = Pattern.compile("[ .]");
    String ms[] = pat.split(os), v; // Get whole String from Text area in tokens form

    Pattern pat1 = Pattern.compile("[ ]");
    String ms1[] = pat1.split(os); // for string aaray

    int hcode[] = {100, 102, 220, 110, 111},
        ecode[] = new int[20],
        j,
        p = 0; // p for check entry & hcode=Hindi lang.code  ecode=English lang. code
    ResultSet rs;
    b.setText("");
    try {
      Class.forName("oracle.jdbc.driver.OracleDriver");
      Connection con =
          DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "student");
      Statement stmt = con.createStatement();
      for (i = 0; i <= ms.length; i++) {
        v = "'" + ms[i] + "'";
        p = 0;
        if (p == 0) {
          rs = stmt.executeQuery("select hnoun from noun where enoun=" + v);
          while (rs.next()) {
            ms1[i] = (rs.getString(1));
            p++;
            ecode[i] = 100;
          }
        }

        if (p == 0) {
          rs = stmt.executeQuery("select hhv from hv where ehv=" + v);
          while (rs.next()) {
            ms1[i] = (rs.getString(1));
            p++;
            ecode[i] = 111;
          }
        }

        if (p == 0) {
          rs = stmt.executeQuery("select hneg from neg where eneg=" + v);
          while (rs.next()) {
            ms1[i] = (rs.getString(1));
            p++;
            ecode[i] = 220;
          }
        }

        if (p == 0) {
          rs = stmt.executeQuery("select hverb from verb where everb=" + v);
          while (rs.next()) {
            ms1[i] = (rs.getString(1));
            p++;
            ecode[i] = 110;
          }
        }

        if (p == 0) {
          rs = stmt.executeQuery("select hpre from pre where epre=" + v);
          while (rs.next()) {
            ms1[i] = (rs.getString(1));
            p++;
            ecode[i] = 140;
          }
        }
        if (p == 0) {
          rs = stmt.executeQuery("select hpro from pro where epro=" + v);
          while (rs.next()) {
            ms1[i] = (rs.getString(1));
            p++;
            ecode[i] = 102;
          }
        }

        if (p == 0) {
          rs = stmt.executeQuery("select hart from art where eart=" + v);
          while (rs.next()) {
            ms1[i] = (rs.getString(1));
            p++;
            ecode[i] = 123;
          }
        }
      }

      con.close();

    } catch (Exception e) {
      System.out.println(e);
    }

    for (i = 0; i < 5; i++) {
      for (j = 0; j < ms.length; j++) {
        if (hcode[i] == ecode[j]) {
          b.append(ms1[j] + " "); // print to hindi code wise
        }
      }
    }
  }
Esempio n. 12
0
/* A generic class to manage reading/writing to a console. Keeps the code simpler (although the Sleep code to do this is
simpler than this Java code. *sigh* */
public class ConsoleClient implements Runnable, ActionListener {
  protected RpcConnection connection;
  protected Console window;
  protected String readCommand;
  protected String writeCommand;
  protected String destroyCommand;
  protected String session;
  protected LinkedList listeners = new LinkedList();
  protected boolean echo = true;
  protected boolean go_read = true;
  protected boolean swallow = false;
  protected ActionListener sessionListener = null; /* one off listener to catch "sessions -i ##" */

  public void setSessionListener(ActionListener l) {
    sessionListener = l;
  }

  public void kill() {
    synchronized (listeners) {
      go_read = false;
    }
  }

  public Console getWindow() {
    return window;
  }

  public void setEcho(boolean b) {
    echo = b;
  }

  public void setWindow(Console console) {
    synchronized (this) {
      window = console;
      setupListener();
    }
  }

  public void addSessionListener(ConsoleCallback l) {
    listeners.add(l);
  }

  public void fireSessionReadEvent(String text) {
    Iterator i = listeners.iterator();
    while (i.hasNext()) {
      ((ConsoleCallback) i.next()).sessionRead(session, text);
    }
  }

  public void fireSessionWroteEvent(String text) {
    Iterator i = listeners.iterator();
    while (i.hasNext()) {
      ((ConsoleCallback) i.next()).sessionWrote(session, text);
    }
  }

  public ConsoleClient(
      Console window,
      RpcConnection connection,
      String readCommand,
      String writeCommand,
      String destroyCommand,
      String session,
      boolean swallow) {
    this.window = window;
    this.connection = connection;
    this.readCommand = readCommand;
    this.writeCommand = writeCommand;
    this.destroyCommand = destroyCommand;
    this.session = session;
    this.swallow = swallow;

    setupListener();

    new Thread(this).start();
  }

  /* call this if the console client is referencing a metasploit console with tab completion */
  public void setMetasploitConsole() {
    window.addActionForKey(
        "ctrl pressed Z",
        new AbstractAction() {
          public void actionPerformed(ActionEvent ev) {
            sendString("background\n");
          }
        });

    new TabCompletion(window, connection, session, "console.tabs");
  }

  /* called when the associated tab is closed */
  public void actionPerformed(ActionEvent ev) {
    if (destroyCommand != null) {
      ((RpcAsync) connection).execute_async(destroyCommand, new Object[] {session});
    }

    /* we don't need to keep reading from this console */
    kill();
  }

  protected void finalize() {
    actionPerformed(null);
  }

  private static final Pattern interact = Pattern.compile("sessions -i (\\d+)\n");

  public void _sendString(String text) {
    if (writeCommand == null) return;

    /* intercept sessions -i and deliver it to a listener within armitage */
    if (sessionListener != null) {
      Matcher m = interact.matcher(text);
      if (m.matches()) {
        sessionListener.actionPerformed(new ActionEvent(this, 0, m.group(1)));
        return;
      }
    }

    Map read = null;

    try {
      synchronized (this) {
        if (window != null && echo) {
          window.append(window.getPromptText() + text);
        }
      }

      if ("armitage.push".equals(writeCommand)) {
        read = (Map) connection.execute(writeCommand, new Object[] {session, text});
      } else {
        connection.execute(writeCommand, new Object[] {session, text});
        read = readResponse();
      }
      processRead(read);

      fireSessionWroteEvent(text);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  protected void setupListener() {
    synchronized (this) {
      if (window != null) {
        window
            .getInput()
            .addActionListener(
                new ActionListener() {
                  public void actionPerformed(ActionEvent ev) {
                    final String text = window.getInput().getText() + "\n";
                    window.getInput().setText("");
                    sendString(text);
                  }
                });
      }
    }
  }

  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();
  }

  private Map readResponse() throws Exception {
    try {
      return (Map) (connection.execute(readCommand, new Object[] {session}));
    } catch (java.net.SocketException sex) {
      /* this definitely means we were disconnected */
      return null;
    } catch (NullPointerException nex) {
      /* this probably means we were disconnected, which means it's a good time
      to quietly kill this thread */
      return null;
    }
  }

  private long lastRead = 0L;

  private void processRead(Map read) throws Exception {
    if (!"".equals(read.get("data"))) {
      String text = read.get("data") + "";

      synchronized (this) {
        if (window != null) window.append(text);
      }
      fireSessionReadEvent(text);
      lastRead = System.currentTimeMillis();
    }

    synchronized (this) {
      if (!"".equals(read.get("prompt")) && window != null) {
        window.updatePrompt(cleanText(read.get("prompt") + ""));
      }
    }
  }

  protected LinkedList commands = new LinkedList();

  public void sendString(String text) {
    synchronized (listeners) {
      commands.add(text);
    }
  }

  public void run() {
    Map read;
    boolean shouldRead = go_read;
    String command = null;
    long last = 0;

    try {
      /* swallow the banner if requested to do so */
      if (swallow) {
        readResponse();
      }

      while (shouldRead) {
        synchronized (listeners) {
          if (commands.size() > 0) {
            command = (String) commands.removeFirst();
          }
        }

        if (command != null) {
          _sendString(command);
          command = null;
          lastRead = System.currentTimeMillis();
        }

        long now = System.currentTimeMillis();
        if (this.window != null && !this.window.isShowing() && (now - last) < 1500) {
          /* check if our window is not showing... if not, then we're going to switch to a very reduced
          read schedule. */
        } else {
          read = readResponse();
          if (read == null || "failure".equals(read.get("result") + "")) {
            break;
          }

          processRead(read);
          last = System.currentTimeMillis();
        }

        Thread.sleep(100);

        synchronized (listeners) {
          shouldRead = go_read;
        }
      }
    } catch (Exception javaSucksBecauseItMakesMeCatchEverythingFuckingThing) {
      javaSucksBecauseItMakesMeCatchEverythingFuckingThing.printStackTrace();
    }
  }
}