Exemple #1
0
  public static Question GetQuestion(Entity entity) {
    Question q = new Question();
    q.key = KeyFactory.keyToString(entity.getKey());
    q.questionText = (String) entity.getProperty("Text");
    q.rating = (Long) entity.getProperty("Rating");
    q.datePosted = (Date) entity.getProperty("DatePosted");

    return q;
  }
  @WebMethod(operationName = "insertQuestion")
  @WebResult(name = "Question")
  public int insertQuestion(
      @WebParam(name = "Question") Question q, @WebParam(name = "token") String token) {
    int insertsuccessful = 1, tokenUserId = 0; // nanti diganti fungsi validasi

    if (insertsuccessful == 1) {
      try {
        String sql;
        Statement statement = conn.createStatement();

        sql = "SELECT user_id FROM tokenlist WHERE token = ? LIMIT 1";

        PreparedStatement dbStatement = conn.prepareStatement(sql);
        dbStatement.setString(1, token);

        ResultSet result = dbStatement.executeQuery();

        tokenUserId = 0;
        if (result.next()) {
          tokenUserId = result.getInt("user_id");
        } else {
          tokenUserId = 0;
        }
        statement.close();
      } catch (SQLException ex) {
        Logger.getLogger(QuestionWS.class.getName()).log(Level.SEVERE, null, ex);
      }
      try {
        Statement statement = conn.createStatement();
        String sql;
        sql = "INSERT INTO Question (user_id, topic, content, vote, date) VALUES (?,?,?,0,now())";

        PreparedStatement dbStatement = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        dbStatement.setInt(1, tokenUserId);
        dbStatement.setString(2, q.getQuestionTopic());
        dbStatement.setString(3, q.getQuestionContent());

        dbStatement.executeUpdate();
        statement.close();

      } catch (SQLException ex) {
        Logger.getLogger(QuestionWS.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
    return insertsuccessful;
  }
  public void handleProgram(ASTProgram node) {
    program = node;
    // System.out.println("visiting program");
    Global.setCurrentSymbolTable(Global.getSymbolTable());
    update(1, UPDATE_REASON_BEGIN);
    startQuestion = questionFactory.getStartQuestion();
    // Drawing Stuff
    connector.addScope(Global.getSymbolTable(), "Global", null);
    connector.startPar(); // STARTPAR
    connector.showScope("Global");
    connector.endPar(); // ENDPAR
    // connector.endSnap();

    node.jjtGetChild(0).jjtAccept(this, null);
    update(LINE_NUMBER_END, UPDATE_REASON_END);

    int value = 0;

    try {
      value = Global.getSymbolTable().get(startQuestion.getVariable());
      System.out.println(startQuestion.getVariable() + " is " + value);
    } catch (Exception e) {
      System.out.println(e);
    }
    if (startQuestion instanceof FIBQuestion) {

      ((FIBQuestion) startQuestion).addAnswer(value + "");
    } else if (startQuestion instanceof TFQuestion) {
      Random r = new Random();
      int prob = r.nextInt(10);
      int qa = value;
      if (prob >= 3 && value != startQuestion.getValue()) {
        qa = startQuestion.getValue();
        ((TFQuestion) startQuestion).setAnswer(false);
      } else {
        ((TFQuestion) startQuestion).setAnswer(true);
      }
      startQuestion.setText(startQuestion.getText() + qa + ".");
    }

    // TODO Write the last snap nicely

    connector.startSnap(node.getPseudocode().length);
    connector.startPar(); // STARTPAR
    // we can't hide foo in by macro cuz it doesn't exist
    if (!byMacroFlag) connector.hideScope("foo");
    connector.endPar(); // ENDPAR
    connector.endSnap();
  }
Exemple #4
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);
    }
  }
Exemple #5
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;
  }
  public void handleAssignment(ASTAssignment node) {
    connector.startPar(); // STARTPAR
    Random r = new Random();
    int q = r.nextInt(100);

    boolean gotAQuestion = q < QUESTION_FREQUENCY; // q < QUESTION_FREQUENCY;//HACK FOR NOW FIXME
    String name = node.getName();
    if (((ASTVar) node.jjtGetChild(0)).isArg()) {
      name += "_";
    }
    Integer value = (Integer) node.jjtGetChild(1).jjtAccept(this, null);
    int index = 0;

    Variable v = Global.getCurrentSymbolTable().getVariable(name);
    if (v instanceof ByNameVariable) {
      if (gotAQuestion) {
        if (v.getIsArray()) {
          gotAQuestion = false;
        } else {
          assignmentQuestion = questionFactory.getByNameQuestion(node.getLineNumber(), name);
        }
      }
      v.setValue(value);
      index = ((ByNameVariable) v).getIndex();
    } else if (v.getIsArray()) {
      index = (Integer) node.jjtGetChild(0).jjtGetChild(0).jjtAccept(this, null);

      try {
        v.setValue(value, index);
      } catch (VizIndexOutOfBoundsException e) {

        System.out.println(e);
      }
      if (gotAQuestion) {
        assignmentQuestion =
            questionFactory.getAssignmentQuestion(node.getLineNumber(), name, index);
      }
    } else {
      if (gotAQuestion) {
        assignmentQuestion = questionFactory.getAssignmentQuestion(node.getLineNumber(), name);
      }
      try {
        v.setValue(value);
      } catch (Exception e) {
        System.out.println(e);
      }
    }
    System.out.println(assignmentQuestion);
    if (gotAQuestion) {
      int i = -257;
      if (assignmentQuestion.getIndex() != -1) {
        if (assignmentQuestion.aboutArg) {
          try {
            i =
                Global.getFunction("main")
                    .getSymbolTable()
                    .get(assignmentQuestion.getVariable(), assignmentQuestion.getIndex());
          } catch (Exception e) {
            System.out.println(e);
          }
        } else {
          try {
            i = Global.getCurrentSymbolTable().get(name, assignmentQuestion.getIndex());
          } catch (Exception e) {
            System.out.println(e);
          }
        }
      } else {
        if (assignmentQuestion.aboutArg || v instanceof ByNameVariable) {
          System.out.println("Getting " + name);
          try {
            i = Global.getFunction("main").getSymbolTable().get(assignmentQuestion.getVariable());
          } catch (Exception e) {
            System.out.println(e);
          }
        }
        {
          try {
            i = Global.getCurrentSymbolTable().get(name);
          } catch (Exception e) {
            System.out.println(e);
          }
        }
      }
      if (gotAQuestion) {
        setAssignmentQuestionAnswer(i);
        connector.addQuestion(assignmentQuestion);
      }
    }

    if (v instanceof ByNameVariable) {

      connector.greyScope("foo");
      System.out.println("Greying scope");
      connector.highlightScopeByName("main");

      if (v.getIsArray()) {
        connector.highlightVarByName(((ByNameVariable) v).getVariable(), index);
        connector.modifyVarByName(((ByNameVariable) v).getVariable(), index, value);
      } else {
        connector.highlightVarByName(((ByNameVariable) v).getVariable());
        connector.modifyVarByName(((ByNameVariable) v).getVariable(), value);
      }
    } else {
      if (v.getIsArray()) {
        connector.modifyVarByName(v, index, value);
      } else {
        connector.modifyVarByName(v, value);
      }
    }
    connector.endPar(); // ENDPAR
    update(node.getLineNumber(), UPDATE_REASON_ASSIGNMENT);
  }
  public Integer handleCall(ASTCall node) {
    boolean gotAQuestion = true; // FIXME HACK
    // Get the correct function head node
    ASTFunction fun = Global.getFunction(node.getName());
    System.out.println("Calling: " + fun.getName());
    // Get the parameters and put the correct values in the symbolTable
    SymbolTable st = fun.getSymbolTable();
    String name = fun.getName();
    ArrayList<String> parameters = fun.getParameters();
    JustCalling = true;
    ArrayList<Integer> args = (ArrayList<Integer>) node.jjtGetChild(0).jjtAccept(this, null);
    JustCalling = false;
    ArrayList<ASTVar> argNames = ((ASTArgs) node.jjtGetChild(0)).getArgs();
    for (int i = 0; i < args.size(); i++) {
      ByNameVariable v = (ByNameVariable) st.getVariable(parameters.get(i));
      v.setRef(argNames.get(i));

      ByNameVariable argVar = (ByNameVariable) st.getVariable(argNames.get(i).getName() + "_");
    }
    HashMap<String, String> pa = new HashMap<String, String>(); // Maps args to params
    for (int i = 0; i < parameters.size(); i++) {
      pa.put(parameters.get(i), argNames.get(i).getName());
    }
    Global.setCurrentParamToArg(pa);

    // QUESTION!!!
    callQuestion = questionFactory.getCallQuestion(name, pa);
    if (callQuestion == null) {
      System.out.println("No question");
      gotAQuestion = false;
    }
    // Drawing Stuff
    connector.addScope(new SymbolTable(null), fun.getName(), "Global", true);
    connector.startPar(); // STARTPAR
    connector.showScope(node.getName());
    if (gotAQuestion) {
      System.out.println("Adding the call question");
      connector.addQuestion(callQuestion);
    }
    connector.endPar(); // ENDPAR

    connector.endSnap();
    fun.jjtAccept(this, null); // and we gogogo

    if (gotAQuestion) {

      int answer = 0;
      try {
        answer = Global.getFunction("main").getSymbolTable().get(callQuestion.getVariable());
      } catch (Exception e) {
        System.out.println(e);
      }
      System.out.println(callQuestion.getVariable() + " is " + answer);

      if (callQuestion instanceof FIBQuestion) {
        ((FIBQuestion) callQuestion).addAnswer(answer + "");
      } else if (callQuestion instanceof TFQuestion) {
        int qa = answer;
        // Getting the value of the var at the end of the function
        String paramName = Global.getCurrentParamToArg().get(callQuestion.getVariable());
        int prevVal = 0;
        try {
          Global.getFunction("foo").getSymbolTable().get(paramName);
        } catch (Exception e) {
          System.out.println(e);
        }

        Random r = new Random();
        int choose = r.nextInt(3);
        switch (choose) {
          case 0:
            qa = callQuestion.getValue();
            System.out.println(qa + "getValue");
            ((TFQuestion) callQuestion).setAnswer(false);
            if (qa == answer) // Value is the same anyway
            {
              ((TFQuestion) callQuestion).setAnswer(true);
            }
            break;
          case 1:
          case 2:
            System.out.println(qa + "value");
            ((TFQuestion) callQuestion).setAnswer(true);
            break;
        }

        callQuestion.setText(callQuestion.getText() + qa);
      } else {
      }
    }
    connector.startSnap(Global.getFunction("main").getLineNumber());

    System.out.println("leaving call");
    return 0;
  }