Esempio n. 1
0
 @Test
 public void shouldReturnSurveyReadyToSend() throws Exception {
   Survey mySurvey = mock(Survey.class);
   when(mySurvey.readyToSend()).thenReturn(true);
   response.setSurvey(mySurvey);
   assertEquals(response.readyToSend(), true);
 }
Esempio n. 2
0
  /**
   * Load or Reload a survey from file, return survey ID or null if unsuccessful
   *
   * @param filename File from which the survey has to be loaded. *
   * @return String The survey Id that has been loaded.
   */
  public String loadSurvey(String filename) {
    String sid = null;
    Survey s;
    try {
      // String file_loc = SurveyorApplication.xmlLoc
      // + System.getProperty("file.separator") + dirName
      // + System.getProperty("file.separator") + filename;
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setCoalescing(true);
      factory.setExpandEntityReferences(false);
      factory.setIgnoringComments(true);
      factory.setIgnoringElementContentWhitespace(true);

      /*
       * Document xml_doc = factory.newDocumentBuilder().parse(
       * CommonUtils.loadResource(file_loc));
       */

      LOGGER.info("Fetching survey file " + filename + " from database for " + this.studyName);
      InputStream surveyFileInputStream = this.db.getXmlFileFromDatabase(filename);

      if (surveyFileInputStream == null) {
        throw new FileNotFoundException();
      }

      Document xmlDoc = factory.newDocumentBuilder().parse(surveyFileInputStream);

      s = new Survey(xmlDoc, this);
      if (s != null) {
        sid = s.getId();
        this.surveys.put(sid, s);
      }

    } catch (DOMException e) {
      LOGGER.error(
          "WISE - SURVEY parse error: " + e.toString() + "\n" + this.id + "\n" + this.toString(),
          null);

    } catch (FileNotFoundException e) {
      LOGGER.error(
          "Study Space " + this.dirName + " failed to parse survey " + filename + ". Error: " + e,
          e);
    } catch (SAXException e) {
      LOGGER.error(
          "Study Space " + this.dirName + " failed to parse survey " + filename + ". Error: " + e,
          e);
    } catch (ParserConfigurationException e) {
      LOGGER.error(
          "Study Space " + this.dirName + " failed to parse survey " + filename + ". Error: " + e,
          e);
    } catch (IOException e) {
      LOGGER.error(
          "Study Space " + this.dirName + " failed to parse survey " + filename + ". Error: " + e,
          e);
    }
    return sid;
  }
 private void extractLabels(CodeList codeList, Cursor crs, PersistedCodeListItem item) {
   Survey survey = codeList.getSurvey();
   item.removeAllLabels();
   List<String> languages = survey.getLanguages();
   String[] labelColumnNames = {
     OFC_CODE_LIST.LABEL1.getName(), OFC_CODE_LIST.LABEL2.getName(), OFC_CODE_LIST.LABEL3.getName()
   };
   for (int i = 0; i < languages.size(); i++) {
     String lang = languages.get(i);
     String label = crs.getString(crs.getColumnIndex(labelColumnNames[i]));
     item.setLabel(lang, label);
     if (i >= 3) break;
   }
 }
 private void extractDescriptions(CodeList codeList, Cursor crs, PersistedCodeListItem item) {
   Survey survey = codeList.getSurvey();
   item.removeAllDescriptions();
   List<String> languages = survey.getLanguages();
   String[] descrColumnNames = {
     OFC_CODE_LIST.DESCRIPTION1.getName(),
     OFC_CODE_LIST.DESCRIPTION2.getName(),
     OFC_CODE_LIST.DESCRIPTION3.getName()
   };
   for (int i = 0; i < languages.size(); i++) {
     String lang = languages.get(i);
     String label = crs.getString(crs.getColumnIndex(descrColumnNames[i]));
     item.setDescription(lang, label);
     if (i >= 3) break;
   }
 }
Esempio n. 5
0
  private void registerDependencies() {
    Schema schema = survey.getSchema();

    // register dependencies for each root entity
    List<EntityDefinition> rootEntityDefns = schema.getRootEntityDefinitions();
    for (EntityDefinition rootDefn : rootEntityDefns) {
      registerDependencies(rootDefn);
      registerMultipleKeyDependencies(rootDefn);
    }
  }
  private void saveSurvey(String name, Survey survey) {
    task.setName(name);
    survey.setTitle(name);
    survey.setQuestions(dynamicList.getList());

    ObjectMapper mapper = new ObjectMapper();
    String json = null;
    try {
      json = mapper.writeValueAsString(survey);
    } catch (JsonGenerationException e) {
      e.printStackTrace();
    } catch (JsonMappingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    task.putExtra("survey", json);

    // Save new task
    editor.saveNewTask(task);
  }
  public void onSubmitClick(View view) {
    String question = questionInput.getText().toString();
    boolean cancel = false;
    View focusView = null;

    if (question == "") {
      questionInput.setError("Required field");
      focusView = questionInput;
      cancel = true;
    }

    if (answerList.isEmpty()) {
      answerInput.setError("Answers needed");
      focusView = answerInput;
      cancel = true;
    }

    if (radioGroup.getCheckedRadioButtonId() == -1) {
      singleChoice.setError("Required input");
      focusView = radioGroup;
      cancel = true;
    }

    if (cancel) {
      focusView.requestFocus();
    } else {
      String[] answerListStrings =
          Arrays.copyOf(answerList.toArray(), answerList.size(), String[].class);
      survey.addQuestion(question, answerListStrings, multipleChoice.isChecked());
      currentQuestion++;
      Intent intent;
      Log.d(
          "current, number",
          String.valueOf(currentQuestion) + " " + String.valueOf(numberOfQuestions));
      if (currentQuestion >= numberOfQuestions) {
        Toast.makeText(this, "Question submitted", Toast.LENGTH_SHORT).show();
        intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
      } else {
        Toast.makeText(this, "Question submitted", Toast.LENGTH_SHORT).show();
        intent = new Intent(this, NewSurveyQuestionsActivity.class);
        intent.putExtra("numberOfQuestions", numberOfQuestions);
        intent.putExtra("currentQuestion", currentQuestion);
        intent.putExtra("survey", survey);
        startActivity(intent);
      }
    }
  }
Esempio n. 8
0
  /**
   * *************************************************** Helper methods
   * ***************************************************
   */
  private Node createNode() throws InterruptedException {
    Comboitem item = typeBox.getSelectedItem();
    if (item == null) {
      Messagebox.show("Node type is required.");
      return null;
    }

    String nodeType = GeneralUtil.getNodeDescriptionByLabel(ntds, item.getLabel()).get("type");
    String firstName = firstNameBox.getValue().trim();
    String lastName = lastNameBox.getValue().trim();
    String midName = midNameBox.getValue().trim();
    String label = labelBox.getValue().trim();
    String username;
    if (nodeType.equals(Constants.NODE_TYPE_USER)) {
      if (firstName.isEmpty()) {
        Messagebox.show("First Name is required.");
        return null;
      } else if (firstName.length() > 80) {
        Messagebox.show("First Name cannot be longer than 80.");
        return null;
      } else if (GeneralUtil.containSpecialCharacter(firstName)) {
        Messagebox.show("First Name cannot contain special characters.");
        return null;
      }

      if (lastName.isEmpty()) {
        Messagebox.show("Last Name is required.");
        return null;
      } else if (lastName.length() > 80) {
        Messagebox.show("Last Name cannot be longer than 80.");
        return null;
      } else if (GeneralUtil.containSpecialCharacter(lastName)) {
        Messagebox.show("Last Name cannot contain special characters.");
        return null;
      }

      username = firstName.replace(" ", "_") + "__" + lastName.replace(" ", "_");
    } else {
      if (label.isEmpty()) {
        Messagebox.show("Label is required.");
        return null;
      } else if (label.length() > 255) {
        Messagebox.show("Label cannot be longer than 255.");
        return null;
      }
      username = GeneralUtil.replaceSpecialCharacter(label, "_").replace(" ", "_");
    }

    if (nodeDao.findByUsername(username) != null) {
      Messagebox.show("Username: "******" has already been used.");
      return null;
    }

    Survey survey = surveyDao.findById(1L);
    Node node = new Node();
    node.setType(nodeType);
    node.setUsername(username);
    node.setLabel(label);
    if (nodeType.equals(Constants.NODE_TYPE_USER)) {
      node.setFirstName(firstName);
      node.setLastName(lastName);
      node.setMidName(midName);
    }

    String defaultPassword = survey.getAttribute(Constants.SURVEY_DEFAULT_PASSWORD);
    if (defaultPassword == null) {
      defaultPassword = "******";
    }
    if (defaultPassword.equals("rAnDoM")) {
      RandomString rs = new RandomString(8);
      defaultPassword = rs.nextString();
    }
    node.setPassword(defaultPassword);

    node.setAttribute(
        Constants.NODE_LOGIN_MODE, survey.getAttribute(Constants.SURVEY_DEFAULT_LOGIN_MODE));

    // role
    node.getRoles().add(roleDao.findByName(Constants.ROLE_USER));

    // groups
    Set<Group> groups = new HashSet<Group>();
    AbstractQuestionRelation p = (AbstractQuestionRelation) getParent();
    groups.addAll(p.getQuestion().getAvailableGroups());
    groups.add(groupDao.findByName(Constants.GROUP_ALL));

    if (nodeType.equals(Constants.NODE_TYPE_USER)) {
      groups.add(groupDao.findByName(Constants.GROUP_USER));
    } else {
      String groupName = Constants.GROUP_NODE_TYPE_PREFIX + nodeType;
      Group group = groupDao.findByName(groupName);
      if (group == null) {
        group = new Group();
        group.setName(groupName);
        groupDao.save(group);
        logger.info("created new group: " + group.getName());
      }
      groups.add(group);
    }

    node.setGroups(groups);

    // save
    nodeDao.save(node);
    logger.debug("Node created: " + username);

    return node;
  }
Esempio n. 9
0
  // Submit a survey to the server
  // Parameter:  theSessionID(String), theStartTime(String), theEndTime(String),
  // theQuestionList(String)
  // Return:  JSONObject for response object
  public JSONObject submitSurvey(final Survey theSurvey, final String theSessionID) {
    final String api = "api/submitsurvey";
    boolean levelOneCompleted = false;
    JSONObject finalresponse = new JSONObject();

    int qcount = 0; // quesiton count
    int opcount = 0; // option count;
    String surveyid = "";

    // Level 0
    // WeeklySymptomSurvey
    JSONObject level0 = new JSONObject();
    level0.put("entrylevel", 0);
    level0.put("starttime", theSurvey.getHeading().getStartDate());
    level0.put("endtime", theSurvey.getHeading().getEndDate());
    level0.put("sessionid", theSessionID);

    JSONObject stage1 = new JSONObject(callAPI(level0, api));
    if (stage1.getBoolean("status")) {
      levelOneCompleted = true;
      surveyid = stage1.getString("surveyid");
    }

    // Level 1 & 2
    // SurveyQuestionBridge
    if (levelOneCompleted) {
      List<Question> questions = theSurvey.getQuestions();
      for (int i = 0; i < questions.size(); i++) {
        Question myQuestion = questions.get(i);
        JSONObject myType = new JSONObject();
        myType.put("entrylevel", 1);
        myType.put("sessionid", theSessionID);
        myType.put("surveyid", surveyid);
        myType.put("questiontype", myQuestion.getType());

        JSONObject response = new JSONObject(callAPI(myType, api));
        if (response.getBoolean("status")) {
          qcount++;
          final String questionid = response.getString("questionid");

          // level 2
          JSONObject finalLevel = new JSONObject();
          finalLevel.put("sessionid", theSessionID);
          finalLevel.put("questionid", questionid);
          finalLevel.put("entrylevel", 2);

          JSONArray jsonoption = new JSONArray();
          List<Option> options = myQuestion.getOptions();
          for (int j = 0; j < options.size(); j++) {
            Option op = options.get(j);
            JSONObject json_op = new JSONObject();
            json_op.put("id", op.getID());
            json_op.put("status", op.getStatus());
            json_op.put("type", op.getType());
            jsonoption.put(j, json_op);
          }
          finalLevel.put("options", jsonoption);

          JSONObject optionResponse = new JSONObject(callAPI(finalLevel, api));
          if (optionResponse.getBoolean("status")) {
            opcount++;
          }
        }
      }
      int totaloptions = 0;
      for (Question q : questions) {
        totaloptions += q.getOptions().size();
      }
      if (qcount == questions.size() && opcount == totaloptions) {
        finalresponse.put("status", true);
        finalresponse.put("message", "Successfully submitted survey");
      } else {
        finalresponse.put("status", false);
        finalresponse.put("message", "Failed to submit survey");
      }
      return finalresponse;
    }

    return null;
  }
Esempio n. 10
0
 public final Schema getSchema() {
   return survey == null ? null : survey.getSchema();
 }
  protected void addComponents(final EditorTask task) {
    this.task = task;

    JsonSurvey jsonSurvey = new JsonSurvey(new ObjectMapper());
    final Survey survey = jsonSurvey.toSurvey(task.getExtra("survey"));

    GroupLayout layout = new GroupLayout(this);
    setLayout(layout);
    layout.setAutoCreateGaps(true);
    layout.setAutoCreateContainerGaps(true);
    GroupLayout.Group hGroup = layout.createParallelGroup(Alignment.CENTER);
    GroupLayout.Group vGroup = layout.createSequentialGroup();

    // First 2 fields are always the same: type and name
    GroupLayout.Group hLeftGroup = layout.createParallelGroup();
    GroupLayout.Group hRightGroup = layout.createParallelGroup();

    JLabel typeLabel = new JLabel(mxResources.get("taskType") + ":");
    JLabel typeValue = new JLabel(task.getType());

    vGroup.addGroup(layout.createParallelGroup().addComponent(typeLabel).addComponent(typeValue));
    hLeftGroup.addComponent(typeLabel);
    hRightGroup.addComponent(typeValue);

    JLabel nameLabel = new JLabel(mxResources.get("taskName") + ":");
    final JTextField nameTextField = new JTextField(10);
    nameTextField.setText(task.getName());

    vGroup.addGroup(
        layout.createParallelGroup().addComponent(nameLabel).addComponent(nameTextField));
    hLeftGroup.addComponent(nameLabel);
    hRightGroup.addComponent(nameTextField);

    hGroup.addGroup(layout.createSequentialGroup().addGroup(hLeftGroup).addGroup(hRightGroup));

    // Survey specific data
    ImageIcon icon =
        new ImageIcon(GraphEditor.class.getResource("/edu/incense/designer/images/add-icon.png"));
    JButton addButton = new JButton("Add a question", icon);
    addButton.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent event) {
            addItem();
          }
        });
    hGroup.addGroup(layout.createParallelGroup(Alignment.LEADING).addComponent(addButton));
    vGroup.addComponent(addButton);

    questionEditor = new QuestionEditor(windowContainer);
    dynamicList = new DynamicList<Question>(questionEditor, windowContainer);
    for (Question q : survey.getQuestions()) {

      dynamicList.add(q.clone());
    }
    JScrollPane scrollPane = new JScrollPane(dynamicList);
    Dimension d = dynamicList.getPreferredSize(8);
    d.setSize(d.getWidth() + 50, d.getHeight() + 5);
    scrollPane.setMaximumSize(d);
    scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

    hGroup.addComponent(scrollPane);
    vGroup.addComponent(scrollPane);

    JButton okButton = new JButton("Ok");
    okButton.addActionListener(
        new ActionListener() {

          public void actionPerformed(ActionEvent e) {
            saveSurvey(nameTextField.getText(), survey);
            windowContainer.dispose();
          }
        });

    JButton cancelButton = new JButton("Cancel");
    cancelButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            windowContainer.dispose();
          }
        });
    JPanel buttonsPanel = new JPanel();
    buttonsPanel.add(okButton);
    buttonsPanel.add(cancelButton);
    hGroup.addComponent(buttonsPanel);
    vGroup.addComponent(buttonsPanel);

    layout.setVerticalGroup(vGroup);
    layout.setHorizontalGroup(hGroup);
  }
 private ModelVersion extractModelVersion(SurveyObject surveyObject, Integer versionId) {
   Survey survey = surveyObject.getSurvey();
   return ((versionId == null) || (versionId == 0)) ? null : survey.getVersionById(versionId);
 }
  public void testSurveyStateSaving() {
    final String surveyJsonString =
        "{\"collections\":[{\"id\":151,\"selector\":\"\\\"@mixpanel\\\" in properties[\\\"$email\\\"]\"}],"
            + "\"id\":299,"
            + "\"questions\":["
            + "{\"prompt\":\"PROMPT1\",\"extra_data\":{\"$choices\":[\"Answer1,1\",\"Answer1,2\",\"Answer1,3\"]},\"type\":\"multiple_choice\",\"id\":287},"
            + "{\"prompt\":\"PROMPT2\",\"extra_data\":{},\"type\":\"text\",\"id\":289}]}";

    Bitmap.Config conf = Bitmap.Config.ARGB_8888;
    Bitmap testBitmap = Bitmap.createBitmap(100, 100, conf);

    UpdateDisplayState originalUpdateDisplayState;
    try {
      final JSONObject surveyJson = new JSONObject(surveyJsonString);
      final Survey s = new Survey(surveyJson);
      final UpdateDisplayState.DisplayState.SurveyState surveyState =
          new UpdateDisplayState.DisplayState.SurveyState(s);
      surveyState.setHighlightColor(Color.WHITE);
      surveyState.setBackground(testBitmap);
      originalUpdateDisplayState = new UpdateDisplayState(surveyState, "DistinctId", "Token");
    } catch (JSONException e) {
      throw new RuntimeException("Survey string in test doesn't parse");
    } catch (BadDecideObjectException e) {
      throw new RuntimeException("Test survey string couldn't be made into a survey");
    }

    final Bundle inBundle = new Bundle();
    inBundle.putParcelable("TEST SURVEY PARCEL", originalUpdateDisplayState);
    final Parcel outerParcel = Parcel.obtain();
    inBundle.writeToParcel(outerParcel, 0);
    outerParcel.setDataPosition(0);
    final Bundle outBundle = outerParcel.readBundle();
    outBundle.setClassLoader(UpdateDisplayState.class.getClassLoader());
    final UpdateDisplayState inUpdateDisplayState = outBundle.getParcelable("TEST SURVEY PARCEL");

    final UpdateDisplayState.DisplayState.SurveyState surveyState =
        (UpdateDisplayState.DisplayState.SurveyState) inUpdateDisplayState.getDisplayState();
    final Survey inSurvey = surveyState.getSurvey();
    final String inDistinctId = inUpdateDisplayState.getDistinctId();
    final String inToken = inUpdateDisplayState.getToken();

    assertEquals("DistinctId", inDistinctId);
    assertEquals("Token", inToken);
    assertEquals(inSurvey.getId(), 299);

    List<Survey.Question> inQuestions = inSurvey.getQuestions();
    assertEquals(2, inQuestions.size());

    final Survey.Question q1 = inQuestions.get(0);
    assertEquals(q1.getId(), 287);
    assertEquals(q1.getPrompt(), "PROMPT1");
    assertEquals(q1.getType(), Survey.QuestionType.MULTIPLE_CHOICE);

    final List<String> q1Choices = q1.getChoices();
    assertEquals(q1Choices.size(), 3);
    assertEquals(q1Choices.get(0), "Answer1,1");
    assertEquals(q1Choices.get(1), "Answer1,2");
    assertEquals(q1Choices.get(2), "Answer1,3");

    final Survey.Question q2 = inQuestions.get(1);
    assertEquals(q2.getId(), 289);
    assertEquals(q2.getPrompt(), "PROMPT2");
    assertEquals(q2.getType(), Survey.QuestionType.TEXT);

    assertNotNull(surveyState.getBackground());
    assertNotNull(surveyState.getAnswers());
  }