示例#1
0
  @Override
  public void keyTyped(final KeyEvent e) {
    if (!hist.active()
        || control(e)
        || DELNEXT.is(e)
        || DELPREV.is(e)
        || ESCAPE.is(e)
        || CUT2.is(e)) return;

    final int caret = editor.pos();

    // remember if marked text is to be deleted
    final StringBuilder sb = new StringBuilder(1).append(e.getKeyChar());
    final boolean indent = TAB.is(e) && editor.indent(sb, e.isShiftDown());

    // delete marked text
    final boolean selected = editor.selected() && !indent;
    if (selected) editor.delete();

    final int move = ENTER.is(e) ? editor.enter(sb) : editor.add(sb, selected);

    // refresh history and adjust cursor position
    hist.store(editor.text(), caret, editor.pos());
    if (move != 0) editor.pos(Math.min(editor.size(), caret + move));

    // adjust text height
    scrollCode.invokeLater(true);
    e.consume();
  }
  /**
   * Move up or down the history tree.
   *
   * @param direction less than 0 to move up the tree, down otherwise
   */
  private final boolean moveHistory(final boolean next) throws IOException {
    if (next && !history.next()) {
      return false;
    } else if (!next && !history.previous()) {
      return false;
    }

    setBuffer(history.current());

    return true;
  }
示例#3
0
  private void processMessage(Message message) throws IOException {
    if (message.getType().equals("SimpleMessage")) {
      MessageType messageType = (MessageType) message.getValue();
      String receiver = messageType.getToUser();
      history.get(receiver).add(messageType);
    }

    if (message.getType().equals("ConnectUserMessage")) {
      String user = (String) message.getValue();
      Messages messages = history.get(user);
      Operations.sendHistory(messages.getLastFiveWith(user), out);
    }
  }
  /**
   * Returns the cached recent messages history.
   *
   * @return
   * @throws IOException
   */
  private History getHistory() throws IOException {
    synchronized (historyID) {
      HistoryService historyService =
          MessageHistoryActivator.getMessageHistoryService().getHistoryService();

      if (history == null) {
        history = historyService.createHistory(historyID, recordStructure);

        // lets check the version if not our version, re-create
        // history (delete it)
        HistoryReader reader = history.getReader();
        boolean delete = false;
        QueryResultSet<HistoryRecord> res = reader.findLast(1);
        if (res != null && res.hasNext()) {
          HistoryRecord hr = res.next();
          if (hr.getPropertyValues().length >= 4) {
            if (!hr.getPropertyValues()[3].equals(RECENT_MSGS_VER)) delete = true;
          } else delete = true;
        }

        if (delete) {
          // delete it
          try {
            historyService.purgeLocallyStoredHistory(historyID);

            history = historyService.createHistory(historyID, recordStructure);
          } catch (IOException ex) {
            logger.error("Cannot delete recent_messages history", ex);
          }
        }
      }

      return history;
    }
  }
示例#5
0
  /** Sorts text. */
  public final void sort() {
    final int caret = editor.pos();
    final DialogSort ds = new DialogSort(gui);
    if (!ds.ok() || !editor.sort()) return;

    hist.store(editor.text(), caret, editor.pos());
    scrollCode.invokeLater(true);
    repaint();
  }
示例#6
0
  private void writeHistory(History history, BundleContext context) throws IOException {
    List<String> list = history.get();
    File log = context.getDataFile("log.txt");

    if (log.exists() && !log.delete()) {
      throw new IOException("Unable to delete previous log file!");
    }
    write(list, log);
  }
  /**
   * Searches for contact ids in history of recent messages.
   *
   * @param provider
   * @param after
   * @return
   */
  List<String> getRecentContactIDs(String provider, Date after) {
    List<String> res = new ArrayList<String>();

    try {
      History history = getHistory();

      if (history != null) {
        Iterator<HistoryRecord> recs = history.getReader().findLast(NUMBER_OF_MSGS_IN_HISTORY);
        SimpleDateFormat sdf = new SimpleDateFormat(HistoryService.DATE_FORMAT);

        while (recs.hasNext()) {
          HistoryRecord hr = recs.next();

          String contact = null;
          String recordProvider = null;
          Date timestamp = null;

          for (int i = 0; i < hr.getPropertyNames().length; i++) {
            String propName = hr.getPropertyNames()[i];

            if (propName.equals(STRUCTURE_NAMES[0])) recordProvider = hr.getPropertyValues()[i];
            else if (propName.equals(STRUCTURE_NAMES[1])) contact = hr.getPropertyValues()[i];
            else if (propName.equals(STRUCTURE_NAMES[2])) {
              try {
                timestamp = sdf.parse(hr.getPropertyValues()[i]);
              } catch (ParseException e) {
                timestamp = new Date(Long.parseLong(hr.getPropertyValues()[i]));
              }
            }
          }

          if (recordProvider == null || contact == null) continue;

          if (after != null && timestamp != null && timestamp.before(after)) continue;

          if (recordProvider.equals(provider)) res.add(contact);
        }
      }
    } catch (IOException ex) {
      logger.error("cannot create recent_messages history", ex);
    }

    return res;
  }
  /**
   * Clear the buffer and add its contents to the history.
   *
   * @return the former contents of the buffer.
   */
  final String finishBuffer() {
    String str = buf.buffer.toString();

    // we only add it to the history if the buffer is not empty
    // and if mask is null, since having a mask typically means
    // the string was a password. We clear the mask after this call
    if (str.length() > 0) {
      if (mask == null && useHistory) {
        history.addToHistory(str);
      } else {
        mask = null;
      }
    }

    history.moveToEnd();

    buf.buffer.setLength(0);
    buf.cursor = 0;

    return str;
  }
示例#9
0
文件: History.java 项目: hurims/yobi
 private static void buildPostingHistory(
     String userName, Project project, List<Posting> postings, List<History> histories) {
   for (Posting posting : postings) {
     History postingHistory = new History();
     String authorName = posting.authorName;
     postingHistory.setWho(authorName);
     setUserPageUrl(postingHistory, User.findByLoginId(posting.authorLoginId));
     postingHistory.setWhen(posting.createdDate);
     postingHistory.setWhere(project.name);
     postingHistory.setWhat("post");
     postingHistory.setShortTitle("#" + posting.number);
     postingHistory.setHow(posting.title);
     postingHistory.setUrl("/" + userName + "/" + project.name + "/post/" + posting.number);
     histories.add(postingHistory);
   }
 }
示例#10
0
文件: History.java 项目: hurims/yobi
 private static void buildPullRequestsHistory(
     String userName, Project project, List<PullRequest> pullRequests, List<History> histories) {
   for (PullRequest pull : pullRequests) {
     History pullHistory = new History();
     User contributor = pull.contributor;
     pullHistory.setWho(contributor.loginId);
     setUserPageUrl(pullHistory, User.findByLoginId(contributor.loginId));
     pullHistory.setWhen(pull.created);
     pullHistory.setWhere(project.name);
     pullHistory.setWhat("pullrequest");
     pullHistory.setShortTitle("#" + pull.number);
     pullHistory.setHow(pull.title);
     pullHistory.setUrl("/" + userName + "/" + project.name + "/pullRequest/" + pull.number);
     histories.add(pullHistory);
   }
 }
示例#11
0
  /** Adds recent message in history. */
  private void saveRecentMessageToHistory(ComparableEvtObj msc) {
    synchronized (historyID) {
      // and create it
      try {
        History history = getHistory();
        HistoryWriter writer = history.getWriter();

        SimpleDateFormat sdf = new SimpleDateFormat(HistoryService.DATE_FORMAT);

        writer.addRecord(
            new String[] {
              msc.getProtocolProviderService().getAccountID().getAccountUniqueID(),
              msc.getContactAddress(),
              sdf.format(msc.getTimestamp()),
              RECENT_MSGS_VER
            },
            NUMBER_OF_MSGS_IN_HISTORY);
      } catch (IOException ex) {
        logger.error("cannot create recent_messages history", ex);
        return;
      }
    }
  }
示例#12
0
文件: History.java 项目: hurims/yobi
 private static void buildIssueHistory(
     String userName, Project project, List<Issue> issues, List<History> histories) {
   for (Issue issue : issues) {
     History issueHistory = new History();
     String authorName = issue.authorName;
     issueHistory.setWho(authorName);
     setUserPageUrl(issueHistory, User.findByLoginId(issue.authorLoginId));
     issueHistory.setWhen(issue.createdDate);
     issueHistory.setWhere(project.name);
     issueHistory.setWhat("issue");
     issueHistory.setShortTitle("#" + issue.number);
     issueHistory.setHow(issue.title);
     issueHistory.setUrl("/" + userName + "/" + project.name + "/issue/" + issue.number);
     histories.add(issueHistory);
   }
 }
示例#13
0
  private void prepareClient() throws IOException {
    logger.info("Waiting for client's name");
    Message mes = Operations.receive(in);
    setClientName((String) mes.getValue());
    logger.info("Username for " + s.getInetAddress() + " received: " + userName);

    users.add(this);
    logger.info("User " + getClientName() + " has been added to the userlist.");

    messages = new Messages();
    logger.info("Message list created");

    if (!history.containsKey(userName)) {
      history.put(userName, messages);
    } else {
      messages = history.get(userName);
    }
    messages.addObserver(this);
    logger.info("Message list assigned to history");

    logger.info("Sending the list of users.");
    Operations.sendUserNamesList(users.getUserNames(), out);
    logger.info("Userlist has been sent");
  }
示例#14
0
 /**
  * Sets the output text.
  *
  * @param text output text
  * @param size text size
  */
 public final void setText(final byte[] text, final int size) {
   byte[] txt = text;
   if (Token.contains(text, '\r')) {
     // remove carriage returns
     int ns = 0;
     for (int r = 0; r < size; ++r) {
       final byte b = text[r];
       if (b != '\r') text[ns++] = b;
     }
     // new text is different...
     txt = Arrays.copyOf(text, ns);
   } else if (text.length != size) {
     txt = Arrays.copyOf(text, size);
   }
   if (editor.text(txt)) {
     if (hist != null) hist.store(txt, editor.pos(), 0);
   }
   if (isShowing()) resizeCode.invokeLater();
 }
示例#15
0
文件: History.java 项目: hurims/yobi
 private static void buildCommitHistory(
     String userName, Project project, List<Commit> commits, List<History> histories) {
   if (commits != null) {
     for (Commit commit : commits) {
       History commitHistory = new History();
       String authorEmail = commit.getAuthorEmail();
       if (User.isEmailExist(authorEmail)) {
         setUserPageUrl(commitHistory, User.findByEmail(authorEmail));
       } else {
         commitHistory.setWho(commit.getAuthorName());
       }
       commitHistory.setWhen(commit.getCommitterDate());
       commitHistory.setWhere(project.name);
       commitHistory.setWhat("commit");
       commitHistory.setShortTitle(commit.getShortId());
       commitHistory.setHow(commit.getShortMessage());
       commitHistory.setUrl("/" + userName + "/" + project.name + "/commit/" + commit.getId());
       histories.add(commitHistory);
     }
   }
 }
示例#16
0
  @Override
  public void keyPressed(final KeyEvent e) {
    // ignore modifier keys
    if (specialKey(e) || modifier(e)) return;

    // re-animate cursor
    caret(true);

    // operations without cursor movement...
    final int fh = rend.fontHeight();
    if (SCROLLDOWN.is(e)) {
      scroll.pos(scroll.pos() + fh);
      return;
    }
    if (SCROLLUP.is(e)) {
      scroll.pos(scroll.pos() - fh);
      return;
    }

    // set cursor position
    final boolean selected = editor.selected();
    final int pos = editor.pos();

    final boolean shift = e.isShiftDown();
    boolean down = true, consumed = true;

    // move caret
    int lc = Integer.MIN_VALUE;
    final byte[] txt = editor.text();
    if (NEXTWORD.is(e)) {
      editor.nextWord(shift);
    } else if (PREVWORD.is(e)) {
      editor.prevWord(shift);
      down = false;
    } else if (TEXTSTART.is(e)) {
      editor.textStart(shift);
      down = false;
    } else if (TEXTEND.is(e)) {
      editor.textEnd(shift);
    } else if (LINESTART.is(e)) {
      editor.lineStart(shift);
      down = false;
    } else if (LINEEND.is(e)) {
      editor.lineEnd(shift);
    } else if (PREVPAGE_RO.is(e) && !hist.active()) {
      lc = editor.linesUp(getHeight() / fh, false, lastCol);
      down = false;
    } else if (NEXTPAGE_RO.is(e) && !hist.active()) {
      lc = editor.linesDown(getHeight() / fh, false, lastCol);
    } else if (PREVPAGE.is(e) && !sc(e)) {
      lc = editor.linesUp(getHeight() / fh, shift, lastCol);
      down = false;
    } else if (NEXTPAGE.is(e) && !sc(e)) {
      lc = editor.linesDown(getHeight() / fh, shift, lastCol);
    } else if (NEXTLINE.is(e) && !MOVEDOWN.is(e)) {
      lc = editor.linesDown(1, shift, lastCol);
    } else if (PREVLINE.is(e) && !MOVEUP.is(e)) {
      lc = editor.linesUp(1, shift, lastCol);
      down = false;
    } else if (NEXTCHAR.is(e)) {
      editor.next(shift);
    } else if (PREVCHAR.is(e)) {
      editor.previous(shift);
      down = false;
    } else {
      consumed = false;
    }
    lastCol = lc == Integer.MIN_VALUE ? -1 : lc;

    // edit text
    if (hist.active()) {
      if (COMPLETE.is(e)) {
        complete();
        return;
      }

      if (MOVEDOWN.is(e)) {
        editor.move(true);
      } else if (MOVEUP.is(e)) {
        editor.move(false);
      } else if (DELLINE.is(e)) {
        editor.deleteLine();
      } else if (DELNEXTWORD.is(e)) {
        editor.deleteNext(true);
      } else if (DELLINEEND.is(e)) {
        editor.deleteNext(false);
      } else if (DELNEXT.is(e)) {
        editor.delete();
      } else if (DELPREVWORD.is(e)) {
        editor.deletePrev(true);
        down = false;
      } else if (DELLINESTART.is(e)) {
        editor.deletePrev(false);
        down = false;
      } else if (DELPREV.is(e)) {
        editor.deletePrev();
        down = false;
      } else {
        consumed = false;
      }
    }
    if (consumed) e.consume();

    final byte[] tmp = editor.text();
    if (txt != tmp) {
      // text has changed: add old text to history
      hist.store(tmp, pos, editor.pos());
      scrollCode.invokeLater(down);
    } else if (pos != editor.pos() || selected != editor.selected()) {
      // cursor position or selection state has changed
      cursorCode.invokeLater(down ? 2 : 0);
    }
  }
  /**
   * Read a line from the <i>in</i> {@link InputStream}, and return the line (without any trailing
   * newlines).
   *
   * @param prompt the prompt to issue to the console, may be null.
   * @return a line that is read from the terminal, or null if there was null input (e.g.,
   *     <i>CTRL-D</i> was pressed).
   */
  public String readLine(final String prompt, final Character mask) throws IOException {
    this.mask = mask;
    if (prompt != null) this.prompt = prompt;

    try {
      terminal.beforeReadLine(this, this.prompt, mask);

      if ((this.prompt != null) && (this.prompt.length() > 0)) {
        out.write(this.prompt);
        out.flush();
      }

      // if the terminal is unsupported, just use plain-java reading
      if (!terminal.isSupported()) {
        return readLine(in);
      }

      while (true) {
        int[] next = readBinding();

        if (next == null) {
          return null;
        }

        int c = next[0];
        int code = next[1];

        if (c == -1) {
          return null;
        }

        boolean success = true;

        switch (code) {
          case EXIT: // ctrl-d
            if (buf.buffer.length() == 0) {
              return null;
            }

          case COMPLETE: // tab
            success = complete();
            break;

          case MOVE_TO_BEG:
            success = setCursorPosition(0);
            break;

          case KILL_LINE: // CTRL-K
            success = killLine();
            break;

          case CLEAR_SCREEN: // CTRL-L
            success = clearScreen();
            break;

          case KILL_LINE_PREV: // CTRL-U
            success = resetLine();
            break;

          case NEWLINE: // enter
            moveToEnd();
            printNewline(); // output newline
            return finishBuffer();

          case DELETE_PREV_CHAR: // backspace
            success = backspace();
            break;

          case DELETE_NEXT_CHAR: // delete
            success = deleteCurrentCharacter();
            break;

          case MOVE_TO_END:
            success = moveToEnd();
            break;

          case PREV_CHAR:
            success = moveCursor(-1) != 0;
            break;

          case NEXT_CHAR:
            success = moveCursor(1) != 0;
            break;

          case NEXT_HISTORY:
            success = moveHistory(true);
            break;

          case PREV_HISTORY:
            success = moveHistory(false);
            break;

          case REDISPLAY:
            break;

          case PASTE:
            success = paste();
            break;

          case DELETE_PREV_WORD:
            success = deletePreviousWord();
            break;

          case PREV_WORD:
            success = previousWord();
            break;

          case NEXT_WORD:
            success = nextWord();
            break;

          case START_OF_HISTORY:
            success = history.moveToFirstEntry();
            if (success) setBuffer(history.current());
            break;

          case END_OF_HISTORY:
            success = history.moveToLastEntry();
            if (success) setBuffer(history.current());
            break;

          case CLEAR_LINE:
            moveInternal(-(buf.buffer.length()));
            killLine();
            break;

          case INSERT:
            buf.setOvertyping(!buf.isOvertyping());
            break;

          case UNKNOWN:
          default:
            if (c != 0) { // ignore null chars
              ActionListener action =
                  (ActionListener) triggeredActions.get(new Character((char) c));
              if (action != null) action.actionPerformed(null);
              else putChar(c, true);
            } else success = false;
        }

        if (!(success)) {
          beep();
        }

        flushConsole();
      }
    } finally {
      terminal.afterReadLine(this, this.prompt, mask);
    }
  }
示例#18
0
  /**
   * Get the decision from the database, given its name
   *
   * @param name the decision name
   */
  public void fromDatabase(String name) {
    String findQuery = "";
    RationaleDB db = RationaleDB.getHandle();
    Connection conn = db.getConnection();

    this.name = name;
    name = RationaleDBUtil.escape(name);

    Statement stmt = null;
    ResultSet rs = null;
    try {
      stmt = conn.createStatement();
      findQuery = "SELECT *  FROM " + "PATTERNDECISIONS where name = '" + name + "'";
      //			***			System.out.println(findQuery);
      rs = stmt.executeQuery(findQuery);

      if (rs.next()) {
        id = rs.getInt("id");
        description = RationaleDBUtil.decode(rs.getString("description"));
        type = (DecisionType) DecisionType.fromString(rs.getString("type"));
        devPhase = (Phase) Phase.fromString(rs.getString("phase"));
        ptype = RationaleElementType.fromString(rs.getString("ptype"));
        parent = rs.getInt("parent");
        //				artifact = rs.getString("artifact");
        //				enabled = rs.getBoolean("enabled");
        status = (DecisionStatus) DecisionStatus.fromString(rs.getString("status"));
        String subdecs = rs.getString("subdecreq");
        if (subdecs.compareTo("Yes") == 0) {
          alts = false;
        } else {
          alts = true;
        }

        try {
          int desID = rs.getInt("designer");
          designer = new Designer();
          designer.fromDatabase(desID);
        } catch (SQLException ex) {
          designer = null; // nothing...
        }
      }
      rs.close();
      // need to read in the rest - recursive routines?
      subDecisions.removeAllElements();
      alternatives.removeAllElements();
      if (!alts) {
        Vector<String> decNames = new Vector<String>();
        findQuery =
            "SELECT name from PATTERNDECISIONS where "
                + "ptype = '"
                + RationaleElementType.DECISION.toString()
                + "' and parent = "
                + new Integer(id).toString();
        //				***					System.out.println(findQuery2);
        rs = stmt.executeQuery(findQuery);
        while (rs.next()) {
          decNames.add(RationaleDBUtil.decode(rs.getString("name")));
        }
        Enumeration decs = decNames.elements();
        while (decs.hasMoreElements()) {
          PatternDecision subDec = new PatternDecision();
          subDec.fromDatabase((String) decs.nextElement());
          subDecisions.add(subDec);
        }

      } else {
        Vector<String> altNames = new Vector<String>();
        findQuery =
            "SELECT name from ALTERNATIVES where "
                + "ptype = '"
                + RationaleElementType.DECISION.toString()
                + "' and parent = "
                + new Integer(id).toString();
        //				***					System.out.println(findQuery2);
        rs = stmt.executeQuery(findQuery);
        while (rs.next()) {
          altNames.add(RationaleDBUtil.decode(rs.getString("name")));
        }
        Enumeration alts = altNames.elements();
        while (alts.hasMoreElements()) {
          Alternative alt = new Alternative();
          alt.fromDatabase((String) alts.nextElement());
          alternatives.add(alt);
        }
      }

      // need to do questions too
      Vector<String> questNames = new Vector<String>();
      findQuery =
          "SELECT name from QUESTIONS where "
              + "ptype = '"
              + RationaleElementType.DECISION.toString()
              + "' and parent = "
              + new Integer(id).toString();
      //			***				System.out.println(findQuery3);
      rs = stmt.executeQuery(findQuery);
      while (rs.next()) {
        questNames.add(RationaleDBUtil.decode(rs.getString("name")));
      }
      Enumeration quests = questNames.elements();
      questions.removeAllElements();
      while (quests.hasMoreElements()) {
        Question quest = new Question();
        quest.fromDatabase((String) quests.nextElement());
        questions.add(quest);
      }

      // no, not last - need history too
      findQuery =
          "SELECT * from HISTORY where ptype = 'Decision' and "
              + "parent = "
              + Integer.toString(id);
      //			***			  System.out.println(findQuery5);
      rs = stmt.executeQuery(findQuery);
      history.removeAllElements();
      while (rs.next()) {
        History nextH = new History();
        nextH.setStatus(rs.getString("status"));
        nextH.setReason(RationaleDBUtil.decode(rs.getString("reason")));
        nextH.dateStamp = rs.getTimestamp("date");
        //				nextH.dateStamp = rs.getDate("date");
        history.add(nextH);
      }

      // now, get our constraints
      findQuery =
          "SELECT * from ConDecRelationships WHERE " + "decision = " + new Integer(id).toString();

      rs = stmt.executeQuery(findQuery);
      constraints.removeAllElements();
      if (rs != null) {
        while (rs.next()) {
          int ontID = rs.getInt("constr");
          Constraint cont = new Constraint();
          cont.fromDatabase(ontID);
          this.addConstraint(cont);
        }
        rs.close();
      }

      // now, candidate patterns
      findQuery =
          "SELECT * from pattern_decision WHERE parentType= 'Decision' and decisionID=" + this.id;
      rs = stmt.executeQuery(findQuery);
      if (rs != null) {
        while (rs.next()) {
          int patternID = rs.getInt("patternID");
          Pattern p = new Pattern();
          p.fromDatabase(patternID);
          this.addCandidatePattern(p);
        }
      }

    } catch (SQLException ex) {
      // handle any errors
      RationaleDB.reportError(ex, "Error in PatternDecision.fromDatabase", findQuery);

    } finally {
      RationaleDB.releaseResources(stmt, rs);
    }
  }
示例#19
0
  /**
   * Save our decision to the database.
   *
   * @param parent - the parent of the decision
   * @param ptype - the parent's type
   * @return the unique ID
   */
  public int toDatabase(int parent, RationaleElementType ptype) {
    RationaleDB db = RationaleDB.getHandle();
    Connection conn = db.getConnection();
    String updateQuery = "";
    int ourid = 0;

    RationaleUpdateEvent l_updateEvent;

    // find out if this requirement is already in the database
    Statement stmt = null;
    ResultSet rs = null;

    String subsReq = "No";
    if (!alts) subsReq = "Yes";

    try {
      stmt = conn.createStatement();

      if (inDatabase(parent, ptype)) {
        // set up Designer update string
        String updateD;
        if (designer == null) updateD = "D.designer = null";
        else updateD = "D.designer = " + designer.getID();

        updateQuery =
            "UPDATE PATTERNDECISIONS D "
                + "SET D.parent = "
                + new Integer(parent).toString()
                + ", D.ptype = '"
                + ptype.toString()
                + "', D.phase = '"
                + devPhase.toString()
                + "', D.description = '"
                + RationaleDBUtil.escape(description)
                + "', D.type = '"
                + type.toString()
                + "', D.name = '"
                + RationaleDBUtil.escape(name)
                + "', D.status = '"
                + status.toString()
                + "', D.subdecreq = '"
                + subsReq
                + "', "
                + updateD
                + " WHERE "
                + "D.id = "
                + this.id
                + " ";
        stmt.execute(updateQuery);

        l_updateEvent = m_eventGenerator.MakeUpdated();
      } else {
        if (!fromXML) id = RationaleDB.findAvailableID("PATTERNDECISIONS");

        String parentSt;
        String parentTSt;

        // now, we have determined that the decision is new
        if ((this.parent < 0) || (ptype == null)) {
          parentSt = "NULL";
          parentTSt = "None";
        } else {
          parentSt = new Integer(this.parent).toString();
          parentTSt = ptype.toString();
        }
        String updateD;
        if (designer == null) updateD = "null";
        else updateD = new Integer(designer.getID()).toString();

        updateQuery =
            "INSERT INTO PATTERNDECISIONS "
                + "(id, name, description, type, status, phase, subdecreq, parent, ptype, designer) "
                + "VALUES ("
                + id
                + ", '"
                + RationaleDBUtil.escape(this.name)
                + "', '"
                + RationaleDBUtil.escape(this.description)
                + "', '"
                + this.type.toString()
                + "', '"
                + this.status.toString()
                + "', '"
                + this.devPhase.toString()
                + "', '"
                + subsReq
                + "', "
                + parentSt
                + ", '"
                + parentTSt
                + "', "
                + updateD
                + ")";

        stmt.execute(updateQuery);

        /*
        //Now, associate with pattern.
        //Get id first
        updateQuery = "SELECT id FROM patterndecisions where name='" +
        RationaleDBUtil.escape(this.name) + "'";
        rs = stmt.executeQuery(updateQuery);

        if (rs.next())
        {
        	ourid = rs.getInt("id");
        	rs.close();
        	//We have found out our ID and the insert is a success.
        	//get association set up.
        	updateQuery = "INSERT into pattern_decision values (" + parent +
        	"ourid" + "DECISION)";
        }

        //And now, we have patternID and patterndecisionID. We can insert into relationship entry
        updateQuery = "INSERT INTO pattern_decision values (" + parentPattern + ", " +
        ourid + ", " + "'Decision')";
        stmt.execute(updateQuery);
        */
        l_updateEvent = m_eventGenerator.MakeCreated();
      }
      // in either case, we want to update any sub-requirements in case
      // they are new!
      // now, we need to get our ID
      updateQuery =
          "SELECT id FROM PATTERNDECISIONS where name='" + RationaleDBUtil.escape(this.name) + "'";
      rs = stmt.executeQuery(updateQuery);

      if (rs.next()) {
        ourid = rs.getInt("id");
        rs.close();
      } else {
        ourid = -1;
      }
      this.id = ourid;

      Enumeration alts = alternatives.elements();
      while (alts.hasMoreElements()) {
        Alternative alt = (Alternative) alts.nextElement();
        //				System.out.println("Saving alternative from decision");
        alt.toDatabase(ourid, RationaleElementType.DECISION);
      }

      Enumeration decs = subDecisions.elements();
      while (decs.hasMoreElements()) {
        Decision dec = (Decision) decs.nextElement();
        dec.toDatabase(ourid, RationaleElementType.DECISION);
      }

      Enumeration quests = questions.elements();
      while (quests.hasMoreElements()) {
        Question quest = (Question) quests.nextElement();
        quest.toDatabase(ourid, RationaleElementType.DECISION);
      }

      // finally, the history

      Enumeration hist = history.elements();
      while (hist.hasMoreElements()) {
        History his = (History) hist.nextElement();
        his.toDatabase(ourid, RationaleElementType.DECISION);
      }

      // need to update our relationships with the constraints
      Enumeration conkids = this.constraints.elements();
      while (conkids.hasMoreElements()) {
        Constraint kid = (Constraint) conkids.nextElement();
        // if the parent ID is not zero, then update the parent-child relationship

        updateQuery =
            "SELECT * from ConDecRelationships WHERE "
                + "constr = "
                + new Integer(kid.getID()).toString()
                + " and decision = "
                + new Integer(ourid).toString();

        rs = stmt.executeQuery(updateQuery.toUpperCase());
        if (rs.next()) {
          rs.close();
        } else {
          String insertRel =
              "INSERT INTO ConDecRelationships (constr, decision) "
                  + "VALUES ("
                  + new Integer(kid.getID()).toString()
                  + ", "
                  + new Integer(ourid).toString()
                  + ")";
          System.out.println(insertRel.toUpperCase());
          stmt.execute(insertRel);
        }
        kid.toDatabase(ourid);
      } // checking parent

      m_eventGenerator.Broadcast(l_updateEvent);
    } catch (SQLException ex) {
      // handle any errors
      RationaleDB.reportError(ex, "Error in PatternDecision.toDatabase", updateQuery);

    } finally {
      RationaleDB.releaseResources(stmt, rs);
    }

    return ourid;
  }
示例#20
0
  /** Updates recent message in history. */
  private void updateRecentMessageToHistory(final ComparableEvtObj msg) {
    synchronized (historyID) {
      // and create it
      try {
        History history = getHistory();

        HistoryWriter writer = history.getWriter();

        writer.updateRecord(
            new HistoryWriter.HistoryRecordUpdater() {
              HistoryRecord hr;

              @Override
              public void setHistoryRecord(HistoryRecord historyRecord) {
                this.hr = historyRecord;
              }

              @Override
              public boolean isMatching() {
                boolean providerFound = false;
                boolean contactFound = false;
                for (int i = 0; i < hr.getPropertyNames().length; i++) {
                  String propName = hr.getPropertyNames()[i];

                  if (propName.equals(STRUCTURE_NAMES[0])) {
                    if (msg.getProtocolProviderService()
                        .getAccountID()
                        .getAccountUniqueID()
                        .equals(hr.getPropertyValues()[i])) {
                      providerFound = true;
                    }
                  } else if (propName.equals(STRUCTURE_NAMES[1])) {
                    if (msg.getContactAddress().equals(hr.getPropertyValues()[i])) {
                      contactFound = true;
                    }
                  }
                }

                return contactFound && providerFound;
              }

              @Override
              public Map<String, String> getUpdateChanges() {
                HashMap<String, String> map = new HashMap<String, String>();
                SimpleDateFormat sdf = new SimpleDateFormat(HistoryService.DATE_FORMAT);

                for (int i = 0; i < hr.getPropertyNames().length; i++) {
                  String propName = hr.getPropertyNames()[i];

                  if (propName.equals(STRUCTURE_NAMES[0])) {
                    map.put(
                        propName,
                        msg.getProtocolProviderService().getAccountID().getAccountUniqueID());
                  } else if (propName.equals(STRUCTURE_NAMES[1])) {
                    map.put(propName, msg.getContactAddress());
                  } else if (propName.equals(STRUCTURE_NAMES[2])) {
                    map.put(propName, sdf.format(msg.getTimestamp()));
                  } else if (propName.equals(STRUCTURE_NAMES[3]))
                    map.put(propName, RECENT_MSGS_VER);
                }

                return map;
              }
            });
      } catch (IOException ex) {
        logger.error("cannot create recent_messages history", ex);
        return;
      }
    }
  }
示例#21
0
 /**
  * Finishes a command.
  *
  * @param old old cursor position; store entry to history if position != -1
  */
 private void finish(final int old) {
   if (old != -1) hist.store(editor.text(), old, editor.pos());
   scrollCode.invokeLater(true);
   release(Action.CHECK);
 }
示例#22
0
 /** Formats the selected text. */
 public final void format() {
   final int caret = editor.pos();
   if (editor.format(rend.getSyntax())) hist.store(editor.text(), caret, editor.pos());
   scrollCode.invokeLater(true);
 }
示例#23
0
  static int loadCust(int whseKount, int distWhseKount, int custDistKount) {

    int k = 0;
    int t = 0;

    Customer customer = new Customer();
    History history = new History();
    PrintWriter outHist = null;

    try {

      now = new java.util.Date();

      if (outputFiles == true) {
        out = new PrintWriter(new FileOutputStream(fileLocation + "customer.csv"));
        System.out.println("\nWriting Customer file to: " + fileLocation + "customer.csv");
        outHist = new PrintWriter(new FileOutputStream(fileLocation + "cust-hist.csv"));
        System.out.println("\nWriting Customer History file to: " + fileLocation + "cust-hist.csv");
      }

      t = (whseKount * distWhseKount * custDistKount * 2);
      System.out.println("\nStart Cust-Hist Load for " + t + " Cust-Hists @ " + now + " ...");

      for (int w = 1; w <= whseKount; w++) {

        for (int d = 1; d <= distWhseKount; d++) {

          for (int c = 1; c <= custDistKount; c++) {

            sysdate = new java.sql.Timestamp(System.currentTimeMillis());

            customer.c_id = c;
            customer.c_d_id = d;
            customer.c_w_id = w;

            // discount is random between [0.0000 ... 0.5000]
            customer.c_discount = (float) (jTPCCUtil.randomNumber(1, 5000, gen) / 10000.0);

            if (jTPCCUtil.randomNumber(1, 100, gen) <= 10) {
              customer.c_credit = "BC"; // 10% Bad Credit
            } else {
              customer.c_credit = "GC"; // 90% Good Credit
            }
            customer.c_last = jTPCCUtil.getLastName(gen);
            customer.c_first = jTPCCUtil.randomStr(jTPCCUtil.randomNumber(8, 16, gen));
            customer.c_credit_lim = 50000;

            customer.c_balance = -10;
            customer.c_ytd_payment = 10;
            customer.c_payment_cnt = 1;
            customer.c_delivery_cnt = 0;

            customer.c_street_1 = jTPCCUtil.randomStr(jTPCCUtil.randomNumber(10, 20, gen));
            customer.c_street_2 = jTPCCUtil.randomStr(jTPCCUtil.randomNumber(10, 20, gen));
            customer.c_city = jTPCCUtil.randomStr(jTPCCUtil.randomNumber(10, 20, gen));
            customer.c_state = jTPCCUtil.randomStr(3).toUpperCase();
            customer.c_zip = "123456789";

            customer.c_phone = "(732)744-1700";

            customer.c_since = sysdate.getTime();
            customer.c_middle = "OE";
            customer.c_data = jTPCCUtil.randomStr(jTPCCUtil.randomNumber(300, 500, gen));

            history.h_c_id = c;
            history.h_c_d_id = d;
            history.h_c_w_id = w;
            history.h_d_id = d;
            history.h_w_id = w;
            history.h_date = sysdate.getTime();
            history.h_amount = 10;
            history.h_data = jTPCCUtil.randomStr(jTPCCUtil.randomNumber(10, 24, gen));

            k = k + 2;
            if (outputFiles == false) {
              custPrepStmt.setLong(1, customer.c_id);
              custPrepStmt.setLong(2, customer.c_d_id);
              custPrepStmt.setLong(3, customer.c_w_id);
              custPrepStmt.setDouble(4, customer.c_discount);
              custPrepStmt.setString(5, customer.c_credit);
              custPrepStmt.setString(6, customer.c_last);
              custPrepStmt.setString(7, customer.c_first);
              custPrepStmt.setDouble(8, customer.c_credit_lim);
              custPrepStmt.setDouble(9, customer.c_balance);
              custPrepStmt.setDouble(10, customer.c_ytd_payment);
              custPrepStmt.setDouble(11, customer.c_payment_cnt);
              custPrepStmt.setDouble(12, customer.c_delivery_cnt);
              custPrepStmt.setString(13, customer.c_street_1);
              custPrepStmt.setString(14, customer.c_street_2);
              custPrepStmt.setString(15, customer.c_city);
              custPrepStmt.setString(16, customer.c_state);
              custPrepStmt.setString(17, customer.c_zip);
              custPrepStmt.setString(18, customer.c_phone);

              Timestamp since = new Timestamp(customer.c_since);
              custPrepStmt.setTimestamp(19, since);
              custPrepStmt.setString(20, customer.c_middle);
              custPrepStmt.setString(21, customer.c_data);

              custPrepStmt.addBatch();

              histPrepStmt.setInt(1, history.h_c_id);
              histPrepStmt.setInt(2, history.h_c_d_id);
              histPrepStmt.setInt(3, history.h_c_w_id);

              histPrepStmt.setInt(4, history.h_d_id);
              histPrepStmt.setInt(5, history.h_w_id);
              Timestamp hdate = new Timestamp(history.h_date);
              histPrepStmt.setTimestamp(6, hdate);
              histPrepStmt.setDouble(7, history.h_amount);
              histPrepStmt.setString(8, history.h_data);

              histPrepStmt.addBatch();

              if ((k % configCommitCount) == 0) {
                long tmpTime = new java.util.Date().getTime();
                String etStr =
                    "  Elasped Time(ms): "
                        + ((tmpTime - lastTimeMS) / 1000.000)
                        + "                    ";
                System.out.println(etStr.substring(0, 30) + "  Writing record " + k + " of " + t);
                lastTimeMS = tmpTime;

                custPrepStmt.executeBatch();
                histPrepStmt.executeBatch();
                custPrepStmt.clearBatch();
                custPrepStmt.clearBatch();
                transCommit();
              }
            } else {
              String str = "";
              str = str + customer.c_id + ",";
              str = str + customer.c_d_id + ",";
              str = str + customer.c_w_id + ",";
              str = str + customer.c_discount + ",";
              str = str + customer.c_credit + ",";
              str = str + customer.c_last + ",";
              str = str + customer.c_first + ",";
              str = str + customer.c_credit_lim + ",";
              str = str + customer.c_balance + ",";
              str = str + customer.c_ytd_payment + ",";
              str = str + customer.c_payment_cnt + ",";
              str = str + customer.c_delivery_cnt + ",";
              str = str + customer.c_street_1 + ",";
              str = str + customer.c_street_2 + ",";
              str = str + customer.c_city + ",";
              str = str + customer.c_state + ",";
              str = str + customer.c_zip + ",";
              str = str + customer.c_phone;
              out.println(str);

              str = "";
              str = str + history.h_c_id + ",";
              str = str + history.h_c_d_id + ",";
              str = str + history.h_c_w_id + ",";
              str = str + history.h_d_id + ",";
              str = str + history.h_w_id + ",";
              Timestamp hdate = new Timestamp(history.h_date);
              str = str + hdate + ",";
              str = str + history.h_amount + ",";
              str = str + history.h_data;
              outHist.println(str);

              if ((k % configCommitCount) == 0) {
                long tmpTime = new java.util.Date().getTime();
                String etStr =
                    "  Elasped Time(ms): "
                        + ((tmpTime - lastTimeMS) / 1000.000)
                        + "                    ";
                System.out.println(etStr.substring(0, 30) + "  Writing record " + k + " of " + t);
                lastTimeMS = tmpTime;
              }
            }
          } // end for [c]
        } // end for [d]
      } // end for [w]

      long tmpTime = new java.util.Date().getTime();
      String etStr =
          "  Elasped Time(ms): " + ((tmpTime - lastTimeMS) / 1000.000) + "                    ";
      System.out.println(etStr.substring(0, 30) + "  Writing record " + k + " of " + t);
      lastTimeMS = tmpTime;
      custPrepStmt.executeBatch();
      histPrepStmt.executeBatch();
      transCommit();
      now = new java.util.Date();
      if (outputFiles == true) {
        outHist.close();
      }
      System.out.println("End Cust-Hist Data Load @  " + now);

    } catch (SQLException se) {
      System.out.println(se.getMessage());
      transRollback();
      if (outputFiles == true) {
        outHist.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
      transRollback();
      if (outputFiles == true) {
        outHist.close();
      }
    }

    return (k);
  } // end loadCust()
示例#24
0
 /**
  * Auto-completes a string at the specified position.
  *
  * @param string string
  * @param start start position
  */
 private void complete(final String string, final int start) {
   final int caret = editor.pos();
   editor.complete(string, start);
   hist.store(editor.text(), caret, editor.pos());
   scrollCode.invokeLater(true);
 }
示例#25
0
文件: History.java 项目: hurims/yobi
 private static void setUserPageUrl(History history, User user) {
   history.setWho(user.name);
   history.setUserPageUrl("/" + user.loginId);
   history.setUserAvatarUrl(user.avatarUrl());
 }
示例#26
0
 /**
  * Case conversion.
  *
  * @param cs case type
  */
 public final void toCase(final Case cs) {
   final int caret = editor.pos();
   if (editor.toCase(cs)) hist.store(editor.text(), caret, editor.pos());
   scrollCode.invokeLater(true);
 }
示例#27
0
  public Homework1() {
    Scanner scanner = new Scanner(System.in);
    FiniteDictionary myWords = new FiniteDictionary();

    // define dictionary
    myWords.populate(0, "statue");
    myWords.populate(1, "flamingo");
    myWords.populate(2, "meteor");
    myWords.populate(3, "children");
    myWords.populate(4, "whittle");
    myWords.populate(5, "thoughtful");
    myWords.populate(6, "embarrassed");
    myWords.populate(7, "knowingly");
    myWords.populate(8, "heroic");
    myWords.populate(9, "describe");
    myWords.populate(10, "ostrich");
    myWords.populate(11, "america");
    myWords.populate(12, "evening");
    myWords.populate(13, "loyalty");
    myWords.populate(14, "volume");
    myWords.populate(15, "leprechaun");
    myWords.populate(16, "lollipop");
    myWords.populate(17, "belittle");
    myWords.populate(18, "following");
    myWords.populate(19, "glowworm");
    myWords.populate(20, "hillbilly");
    myWords.populate(21, "neighborhood");
    myWords.populate(22, "requirement");
    myWords.populate(23, "aquarium");
    myWords.populate(24, "statement");
    myWords.populate(25, "juniper");
    myWords.populate(26, "iterate");
    myWords.populate(27, "umbrella");
    myWords.populate(28, "countless");
    myWords.populate(29, "harbor");

    // initialize game
    Hangman game1 = new Hangman(myWords);

    // print welcome
    System.out.println();
    System.out.println("******************************************");
    System.out.print("*     ");
    System.out.println("Welcome to the " + game1.getTitle() + "     *");
    System.out.println("*" + "         (c) Kenton Standard            *");
    System.out.println("******************************************");

    char control;
    String guessLetter = "";
    boolean alreadyGuessed;

    // loop goes until the user does not want to play
    do {
      GameScore hangScore = new HangmanScore();
      game1.setCurrentWord(); // resets to new guessing word
      System.out.println(".for.testing........(computer got: " + game1.getCurrentWord() + ")");
      System.out.println(); // spacer
      // loop goes until word is guessed
      do {
        System.out.print("Guess this word: " + game1.getBlankedOut().toString());
        System.out.println("                 Unused Letters: " + game1.getAlphabet().toString());
        System.out.print("[" + game1.getCount() + "] " + "Guess a letter: ");
        guessLetter = scanner.next();
        System.out.println(); // spacer
        if (guessLetter.substring(0, 1) == null) {
          guessLetter = "1"; // if pointer is null set value to 1, to prompt user to re type data
        } else {
          guessLetter = guessLetter.substring(0, 1); // formats string to first char only
        }
        if (guessLetter.charAt(0) < 65
            || guessLetter.charAt(0) > 122
            || (guessLetter.charAt(0) > 90 && guessLetter.charAt(0) < 97)) {
          do {
            System.out.print("Not a valid letter, please choose again: ");
            guessLetter = scanner.next();
            System.out.println();
          } while (guessLetter.charAt(0) < 65
              || guessLetter.charAt(0) > 122
              || (guessLetter.charAt(0) > 90 && guessLetter.charAt(0) < 97));
        }
        alreadyGuessed = game1.evaluateGuess(guessLetter);
        if (alreadyGuessed == true) {
          System.out.println("'" + guessLetter + "'" + "has already been guessed");
          System.out.println();
        }
      } while (!game1.getCurrentWord().equalsIgnoreCase(game1.getBlankedOut().toString()));

      System.out.println(
          game1.getCurrentWord() + ": you got it with " + (game1.getCount() - 1) + " guesses");
      if (game1.getCount() <= game1.getCurrentWord().length())
        hangScore.score(0); // Got the word correctly
      else hangScore.score((game1.getCount() - 1) - game1.getCurrentWord().length());
      System.out.println("Your score is " + hangScore.getTotalScore());
      Homework4.hangmanList.add(hangScore.getTotalScore()); // Puts total score into an array
      Homework4.hangmanCount++; // Increase count of how many times the player has played

      // Add current score into the game history arraylist
      GameHistory hangmanHistory = new GameHistory("Hangman", hangScore.getTotalScore());
      History hHistory = hangmanHistory.displayHistory();
      Homework4.gameHistory.add(hHistory.description());

      System.out.println(); // spacer
      System.out.print("Do you want to play another game? [y/n]: ");
      control = scanner.next().charAt(0); // gets first char typed
      System.out.println(); // spacer
      // checks for valid input
      while (control != 'y' && control != 'Y' && control != 'n' && control != 'N') {
        System.out.println(); // spacer
        System.out.println(); // spacer
        System.out.print("Invalid input, please enter a 'y' or a 'n': ");
        control = scanner.next().charAt(0);
      }
      if (control == 'y' || control == 'Y') {
        game1 = new Hangman(myWords);
      } else {
        break;
      }
    } while (control == 'y' || control == 'Y');
  }