Example #1
0
    @Override
    public void handle(HttpExchange arg0) throws IOException {
      try {
        String message =
            "<html><body><table border=\"1\"><tr><th>Email</th><th>Submitted at:</th><th>Progress:</th><th>Status:</th><th>Job id</th></tr>";
        for (int i = 0; i < jobs.size(); i++) {
          TnrsJob job = jobs.get(i);

          message +=
              "<tr> <td> "
                  + job.getRequest().getEmail()
                  + "</td><td>"
                  + job.getSubmissionDate()
                  + " </td><td> "
                  + job.progress()
                  + "% </td><td>  "
                  + job.status()
                  + "</td><td>"
                  + job.getRequest().getId()
                  + "</td></tr>\n";
        }
        message += "</table>";
        HandlerHelper.writeResponseRequest(arg0, 200, message, "text/html");

      } catch (Exception ex) {
        log.error(ExceptionUtils.getFullStackTrace(ex));
        throw new IOException(ex);
      }
    }
Example #2
0
    @Override
    public void handle(HttpExchange arg0) throws IOException {
      try {
        String jsons = IOUtils.toString(arg0.getRequestBody());

        JSONObject json = (JSONObject) JSONSerializer.toJSON(jsons);
        if (!json.containsKey("valid")) return;
        Email response = new SimpleEmail();
        response.setHostName(properties.getProperty("org.iplantc.tnrs.mail.host"));
        response.setSmtpPort(
            Integer.parseInt(properties.getProperty("org.iplantc.tnrs.mail.port")));
        response.setFrom("*****@*****.**");
        response.setSubject("TNRS support Ticket");
        response.setMsg(
            "TNRS support ticket from: "
                + json.getString("name")
                + " ("
                + json.getString("email")
                + "). "
                + "\n\n\n"
                + json.getString("contents"));
        response.addTo("*****@*****.**");
        response.send();
      } catch (Exception ex) {
        log.error(ExceptionUtils.getFullStackTrace(ex));
        throw new IOException(ex);
      }
    }
  @Test
  public void testCommandGetSingleDocument() {
    running(
        fakeApplication(),
        () -> {
          try {
            DbHelper.open("1234567890", TEST_USER, TEST_USER);
            ObjectNode cmd = MAPPER.createObjectNode();
            ObjectNode p = MAPPER.createObjectNode();
            p.put("collection", TEST_COLLECTION);
            p.put("id", sGenIds.get(0));
            cmd.put(ScriptCommand.RESOURCE, "documents");
            cmd.put(ScriptCommand.NAME, "get");
            cmd.put(ScriptCommand.PARAMS, p);

            JsonNode node = CommandRegistry.execute(cmd, null);

            assertNotNull(node);
            assertTrue(node.isObject());
            assertNotNull(node.get("generated"));
            assertNotNull(node.get("id"));
            assertEquals(node.get("id").asText(), sGenIds.get(0));
            assertEquals(node.get("@class").asText(), TEST_COLLECTION);
          } catch (Throwable t) {
            fail(ExceptionUtils.getFullStackTrace(t));
          } finally {
            DbHelper.close(DbHelper.getConnection());
          }
        });
  }
  @Test
  public void testCreateDocument() {
    running(
        fakeApplication(),
        () -> {
          try {
            DbHelper.open("1234567890", TEST_USER, TEST_USER);
            ObjectNode params = MAPPER.createObjectNode();
            ObjectNode doc = MAPPER.createObjectNode();
            doc.put("fresh", "fresh");
            params.put("collection", TEST_COLLECTION);
            params.put("data", doc);
            ObjectNode cmd = ScriptCommands.createCommand("documents", "post", params);

            JsonNode exec = CommandRegistry.execute(cmd, null);
            assertNotNull(exec);
            assertTrue(exec.isObject());
            assertNotNull(exec.get("id"));
            assertEquals(TEST_COLLECTION, exec.get("@class").asText());

          } catch (Throwable t) {
            fail(ExceptionUtils.getFullStackTrace(t));
          } finally {
            DbHelper.close(DbHelper.getConnection());
          }
        });
  }
  @Test
  public void testCommandGetFilteredCollection() {
    running(
        fakeApplication(),
        () -> {
          try {
            DbHelper.open("1234567890", TEST_USER, TEST_USER);
            ObjectNode cmd = MAPPER.createObjectNode();
            ObjectNode p = MAPPER.createObjectNode();
            ObjectNode q = MAPPER.createObjectNode();
            q.put("where", "idx < ?");
            ArrayNode params = MAPPER.createArrayNode();
            params.add("5");
            q.put("params", params);
            p.put("collection", TEST_COLLECTION);
            p.put("query", q);

            cmd.put(ScriptCommand.RESOURCE, "documents");
            cmd.put(ScriptCommand.NAME, "list");
            cmd.put(ScriptCommand.PARAMS, p);

            JsonNode node = CommandRegistry.execute(cmd, null);
            assertNotNull(node);
            assertTrue(node.isArray());
            assertEquals(5, node.size());
          } catch (Throwable t) {
            fail(ExceptionUtils.getFullStackTrace(t));
          } finally {
            DbHelper.close(DbHelper.getConnection());
          }
        });
  }
Example #6
0
  @With({UserCredentialWrapFilter.class, ConnectToDBFilter.class})
  @BodyParser.Of(BodyParser.Json.class)
  public static Result changePassword() {
    if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method Start");
    Http.RequestBody body = request().body();

    JsonNode bodyJson = body.asJson();
    if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("changePassword bodyJson: " + bodyJson);
    if (bodyJson == null)
      return badRequest(
          "The body payload cannot be empty. Hint: put in the request header Content-Type: application/json");

    // check and validate input
    if (!bodyJson.has("old")) return badRequest("The 'old' field is missing");
    if (!bodyJson.has("new")) return badRequest("The 'new' field is missing");

    String currentPassword = DbHelper.getCurrentHTTPPassword();
    String oldPassword = (String) bodyJson.findValuesAsText("old").get(0);
    String newPassword = (String) bodyJson.findValuesAsText("new").get(0);

    if (!oldPassword.equals(currentPassword)) {
      return badRequest("The old password does not match with the current one");
    }

    try {
      UserService.changePasswordCurrentUser(newPassword);
    } catch (OpenTransactionException e) {
      BaasBoxLogger.error(ExceptionUtils.getFullStackTrace(e));
      throw new RuntimeException(e);
    }
    if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method End");
    return ok();
  }
  @BeforeClass
  public static void initTestser() {
    running(
        fakeApplication(),
        () -> {
          try {
            DbHelper.open("1234567890", "admin", "admin");
            ODocument user =
                UserService.signUp(TEST_USER, TEST_USER, new Date(), null, null, null, null, false);
            assertNotNull(user);
            ODocument alt =
                UserService.signUp(
                    TEST_ALT_USER, TEST_ALT_USER, new Date(), null, null, null, null, false);
            assertNotNull(alt);

            CollectionService.create(TEST_COLLECTION);
            DbHelper.close(DbHelper.getConnection());
            DbHelper.open("1234567890", TEST_USER, TEST_USER);
            sGenIds = createRandomDocuments(10);
            DbHelper.close(DbHelper.getConnection());
          } catch (Throwable e) {
            fail(ExceptionUtils.getFullStackTrace(e));
          } finally {
            DbHelper.close(DbHelper.getConnection());
          }
        });
  }
Example #8
0
    @Override
    public void run() {
      try {
        StopWatch stp2 = new StopWatch();
        stp2.start();
        JSONObject json = new JSONObject();
        job.setStatus("running");
        if (job.progress() == 100.0) {

          finalizeJob(job);
          return;
        }
        Vector<String> ids = new Vector<String>();
        Vector<String> original_names = new Vector<String>();

        String data = job.getNextDataBatch();

        if (data == null || data.equals("")) return;

        String[] lines = data.split("\n");

        if (job.containsId()) {
          for (int i = 0; i < lines.length; i++) {
            if (lines[i].trim().equals("")) continue;
            ids.add(NameUtil.getNameId(lines[i]));
          }
        }

        for (int i = 0; i < lines.length; i++) {
          original_names.add(NameUtil.processName(lines[i], job.containsId()));
        }

        String names = NameUtil.CleanNames(lines, job);

        if (names.equals("")) return;

        if (job.getType() == TnrsJob.NAME_MATCH_JOB) {

          TaxamatchInterface taxa_match = new TaxamatchInterface(tnrsBaseUrl);
          String result = taxa_match.queryTaxamatch(names, job);
          json = (JSONObject) JSONSerializer.toJSON(result);

        } else if (job.getType() == TnrsJob.PARSING_JOB) {

          json = gni_interface.parseNames(names);
        }
        if (job.outstandingNames() == 0) {
          JobHelper.persistJobInfo(baseFolder, job);
        }
        saveResults(job, json, ids, original_names, "");

        job.setStatus("idle");
        stp2.stop();
        log.info("overall :" + stp2.toString());
      } catch (Exception ex) {
        log.error(ExceptionUtils.getFullStackTrace(ex));
        job.setStatus("failed");
        ex.printStackTrace();
      }
    }
Example #9
0
    @Override
    public void handle(HttpExchange arg0) throws IOException {

      try {
        JSONObject request =
            (JSONObject) JSONSerializer.toJSON(IOUtils.toString(arg0.getRequestBody()));
        String email = request.getString("email");
        String key = request.getString("key");

        for (int i = 0; i < jobs.size(); i++) {
          TnrsJob job = jobs.get(i);
          if (job.getRequest().getId().equals(key) && job.getRequest().getEmail().equals(email)) {
            JSONObject json = (JSONObject) JSONSerializer.toJSON(job.toJsonString());
            json.put("status", "incomplete");
            json.put("progress", job.progress());

            HandlerHelper.writeResponseRequest(arg0, 200, json.toString(), "application/json");
            return;
          }
        }
        if (JobHelper.jobFileExists(baseFolder, email, key)) {
          TnrsJob job = JobHelper.readJobInfo(baseFolder, email, key);

          HandlerHelper.writeResponseRequest(arg0, 200, job.toJsonString(), "application/json");
        } else {
          HandlerHelper.writeResponseRequest(
              arg0, 500, "No such job exists o it might have expired", "text/plain");
        }

      } catch (Exception ex) {
        log.error(ExceptionUtils.getFullStackTrace(ex));
        throw new IOException(ex);
      }
    }
  /**
   * insert rollback
   *
   * @author zhuoxue
   * @since 5.0.1
   */
  @Test
  public void insertRollbackTest() throws Exception {
    // TODO:ob bug,读取不到事务内的最新数据
    if (normaltblTableName.startsWith("ob")) {
      return;
    }

    String sql = "insert into " + normaltblTableName + " values(?,?,?,?,?,?,?)";
    List<Object> param = new ArrayList<Object>();
    param.add(RANDOM_ID);
    param.add(RANDOM_INT);
    param.add(gmt);
    param.add(gmt);
    param.add(gmt);
    param.add(name);
    param.add(fl);

    tddlConnection.setAutoCommit(false);

    mysqlConnection.setAutoCommit(false);
    mysqlPreparedStatement = null;
    try {
      int mysqlAffectRow = mysqlUpdateDataTranscation(sql, param);
      int andorAffectRow = tddlUpdateDataTranscation(sql, param);
      Assert.assertEquals(mysqlAffectRow, andorAffectRow);

      // 在事物内内查到数据
      sql = "select * from " + normaltblTableName + " where pk=" + RANDOM_ID;
      String[] columnParam = {"PK", "ID", "GMT_CREATE", "NAME", "FLOATCOL"};
      selectOrderAssertTranscation(sql, columnParam, null);

      mysqlConnection.rollback();
      tddlConnection.rollback();

      // 在事物回滚查询不到数据
      selectOrderAssertTranscation(sql, columnParam, null);
    } catch (Exception ex) {
      try {
        mysqlConnection.rollback();
        tddlConnection.rollback();
      } catch (Exception ee) {

      }

      throw ex;
    }
    // 多次回滚和提交保证不出现异常
    try {
      tddlConnection.commit();
      tddlConnection.commit();
      tddlConnection.rollback();
      tddlConnection.rollback();
    } catch (Exception e) {
      Assert.fail(ExceptionUtils.getFullStackTrace(e));
    }
  }
Example #11
0
  @Test
  public void testFunctionalMMSService() {
    try {

      MetadataModelService mmsService = getOsgiService(MetadataModelService.class, 30000L);
      assertNotNull(mmsService);

      // make sure we can generate domain models and annotate metadata
      UMLProjectIdentifer project = new UMLProjectIdentifer();
      project.setIdentifier("caCORE 3.2");
      project.setVersion("3.2");

      System.out.println(
          "Creating domain model for project: "
              + project.getIdentifier()
              + " (version:"
              + project.getVersion()
              + ")");

      // TEST THE MMS OSGI SERVICE
      DomainModel model = null;
      try {
        model =
            mmsService.generateDomainModelForPackages(
                project, new String[] {"gov.nih.nci.cabio.domain"});
        System.out.println(model.getProjectLongName());
        for (Iterator iterator = model.getExposedUMLClassCollection().getUMLClass().iterator();
            iterator.hasNext(); ) {
          UMLClass type = (UMLClass) iterator.next();
          System.out.println("\t" + type.getClassName());
        }
      } catch (InvalidUMLProjectIndentifier e) {
        e.printStackTrace();
        fail(ExceptionUtils.getFullStackTrace(e));
      }

      assertNotNull(model);

    } catch (Exception e) {
      e.printStackTrace();
      fail(ExceptionUtils.getFullStackTrace(e));
    }
  }
Example #12
0
    @Override
    public void handle(HttpExchange arg0) throws IOException {
      try {
        JSONObject json =
            (JSONObject) JSONSerializer.toJSON(IOUtils.toString(arg0.getRequestBody()));

        JSONObject result = new JSONObject();

        String email = json.getString("email");
        String key = json.getString("key");

        for (int i = 0; i < jobs.size(); i++) {

          TnrsJob job = jobs.get(i);

          if (job.getRequest().getEmail().equals(email) && job.getRequest().getId().equals(key)) {
            if (job.status().equals("failed") || job.status().equals("error")) {
              result.put("type", "failed");
            } else {
              result.put("type", "incomplete");
              double progress = job.progress();
              if (job.progress() == 100.0) {
                progress = 99.0;
              }
              result.put("progress", progress);
            }
            HandlerHelper.writeResponseRequest(arg0, 200, result.toString(), "application/json");

            return;
          }
        }

        String filename = baseFolder + email.replace("@", "-").replace(".", "-") + "/result" + key;

        File results = new File(filename);

        if (!results.exists()) {
          result.put("type", "non-existent");
        } else {
          result.put("type", "complete");
          TnrsJob job = JobHelper.readJobInfo(baseFolder, email, key);

          result.put("job_type", job.getTypeString());
        }

        HandlerHelper.writeResponseRequest(arg0, 200, result.toString(), "application/json");

        return;
      } catch (Exception ex) {
        log.error(ExceptionUtils.getFullStackTrace(ex));
        throw new IOException(ex);
      }
    }
Example #13
0
 /**
  * * Returns the people those the given user is following
  *
  * @param username
  * @return
  */
 @With({UserCredentialWrapFilter.class, ConnectToDBFilter.class, ExtractQueryParameters.class})
 public static Result following(String username) {
   if (StringUtils.isEmpty(username)) username = DbHelper.currentUsername();
   try {
     Context ctx = Http.Context.current.get();
     QueryParams criteria = (QueryParams) ctx.args.get(IQueryParametersKeys.QUERY_PARAMETERS);
     List<ODocument> following = FriendShipService.getFollowing(username, criteria);
     return ok(prepareResponseToJson(following));
   } catch (SqlInjectionException e) {
     return internalServerError(ExceptionUtils.getFullStackTrace(e));
   }
 }
Example #14
0
 @With({UserCredentialWrapFilter.class, ConnectToDBFilter.class})
 public static Result disable() {
   try {
     UserService.disableCurrentUser();
   } catch (UserNotFoundException e) {
     return badRequest(ExceptionUtils.getMessage(e));
   } catch (OpenTransactionException e) {
     BaasBoxLogger.error(ExceptionUtils.getFullStackTrace(e));
     throw new RuntimeException(e);
   }
   return ok();
 }
Example #15
0
  @With({
    AdminCredentialWrapFilter.class,
    ConnectToDBFilter.class,
  })
  @BodyParser.Of(BodyParser.Json.class)
  public static Result signUp() {
    Logger.trace("Method Start");
    Http.RequestBody body = request().body();

    JsonNode bodyJson = body.asJson();
    Logger.trace("signUp bodyJson: " + bodyJson);
    if (bodyJson == null)
      return badRequest(
          "The body payload cannot be empty. Hint: put in the request header Content-Type: application/json");
    // check and validate input
    if (!bodyJson.has("username")) return badRequest("The 'username' field is missing");
    if (!bodyJson.has("password")) return badRequest("The 'password' field is missing");

    // extract mandatory fields
    JsonNode nonAppUserAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_ANONYMOUS_USER);
    JsonNode privateAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER);
    JsonNode friendsAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_FRIENDS_USER);
    JsonNode appUsersAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_REGISTERED_USER);
    String username = (String) bodyJson.findValuesAsText("username").get(0);
    String password = (String) bodyJson.findValuesAsText("password").get(0);

    if (privateAttributes != null && privateAttributes.has("email")) {
      // check if email address is valid
      if (!Util.validateEmail((String) privateAttributes.findValuesAsText("email").get(0)))
        return badRequest("The email address must be valid.");
    }

    // try to signup new user
    try {
      UserService.signUp(
          username,
          password,
          nonAppUserAttributes,
          privateAttributes,
          friendsAttributes,
          appUsersAttributes);
    } catch (UserAlreadyExistsException e) {
      Logger.debug("signUp", e);
      return badRequest(username + " already exists");
    } catch (Throwable e) {
      Logger.warn("signUp", e);
      if (Play.isDev()) return internalServerError(ExceptionUtils.getFullStackTrace(e));
      else return internalServerError(e.getMessage());
    }
    Logger.trace("Method End");
    return created();
  }
Example #16
0
 /** @param parent parent to set */
 public void setParentNode(INodePO parent) {
   if (LOG.isErrorEnabled() && parent == null) {
     try {
       throw new IllegalArgumentException(
           "The parent of the INodePO (GUID "
               + getGuid() //$NON-NLS-1$
               + ") is not intended to be set to null."); //$NON-NLS-1$
     } catch (IllegalArgumentException e) {
       LOG.info(ExceptionUtils.getFullStackTrace(e), e);
     }
   }
   m_parentNode = parent;
 }
Example #17
0
  private String getErrorText() {

    Throwable t = (Throwable) getResult();

    StringBuilder out = new StringBuilder();
    out.append("An error occured: " + t.getMessage() + "\n\n");

    if (MamConfigManager.get().getConfig().isDebug()) {
      out.append(ExceptionUtils.getFullStackTrace(t));
    }

    return out.toString();
  }
Example #18
0
    @Override
    public void handle(HttpExchange arg0) throws IOException {

      try {

        JSONObject json =
            (JSONObject) JSONSerializer.toJSON(IOUtils.toString(arg0.getRequestBody()));

        String contents = json.getString("names");

        byte[] fileContents = contents.getBytes("UTF-8");

        ByteArrayOutputStream byteArray = new ByteArrayOutputStream();

        GZIPOutputStream gzipStr = new GZIPOutputStream(byteArray);

        gzipStr.write(fileContents);
        gzipStr.close();

        ByteArrayOutputStream byteArray2 = new ByteArrayOutputStream();

        Base64OutputStream base64 = new Base64OutputStream(byteArray2);

        base64.write(byteArray.toByteArray());
        base64.close();

        String value = new String(byteArray2.toByteArray());

        json.remove("names");
        json.put("upload", value);

        HttpClient client = new HttpClient();

        PostMethod post =
            new PostMethod(
                "http://"
                    + properties.getProperty("org.iplantc.tnrs.servicesHost")
                    + "/tnrs-svc/upload");

        post.setRequestEntity(new StringRequestEntity(json.toString(), "text/plain", "UTF-8"));

        client.executeMethod(post);

        HandlerHelper.writeResponseRequest(arg0, 200, "", "text/plain");

      } catch (Exception ex) {
        log.error(ExceptionUtils.getFullStackTrace(ex));
        ex.printStackTrace();
        throw new IOException(ex);
      }
    }
Example #19
0
 public static Terms getTermVector(
     int docId, String fieldname, SolrIndexSearcher solrIndexSearcher) throws JATEException {
   try {
     Terms vector = solrIndexSearcher.getLeafReader().getTermVector(docId, fieldname);
     if (vector == null) throw new JATEException("Cannot find expected field: " + fieldname);
     return vector;
   } catch (IOException ioe) {
     StringBuilder sb =
         new StringBuilder(
             String.format("Cannot find expected field: %s. Error stacktrack:\n", fieldname));
     sb.append(org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(ioe));
     throw new JATEException(sb.toString());
   }
 }
Example #20
0
    @Override
    public void handle(HttpExchange arg0) throws IOException {

      try {
        JSONObject command =
            (JSONObject) JSONSerializer.toJSON(IOUtils.toString(arg0.getRequestBody()));

        String job_id = command.getString("job_id");

        TnrsJob job = null;

        for (TnrsJob jobc : jobs) {
          if (jobc.getRequest().getId().equals(job_id)) {
            job = jobc;
            break;
          }
        }

        if (job == null) {
          HandlerHelper.writeResponseRequest(arg0, 500, "Invalid job identifier", "text/plain");
        }

        if (command.getString("command").equals("stop")) {

          synchronized (job) {
            job.disable();
          }

        } else if (command.getString("command").equals("pause")) {

          synchronized (job) {
            job.pause();
          }

        } else if (command.getString("command").equals("resume")) {

          synchronized (job) {
            job.resume();
          }

        } else {
          HandlerHelper.writeResponseRequest(arg0, 500, "Wrong command", "text/plain");
          return;
        }

        HandlerHelper.writeResponseRequest(arg0, 200, "", "text/plain");
      } catch (Exception ex) {
        log.error(ExceptionUtils.getFullStackTrace(ex));
      }
    }
Example #21
0
  /**
   * This main loop iterates over the submitted jobs and creates the corresponding threads that will
   * carry the execution of each job segment.
   */
  @Override
  public void run() {
    try {
      int jobno = 0;

      while (true) {

        sleep(20);
        synchronized (jobs) {
          if (jobs.size() == 0) {

            continue;
          }
        }

        TnrsJob job = jobs.get(jobno % jobs.size());
        if (job.status().equalsIgnoreCase("idle")) {
          ExecutionThread thread = new ExecutionThread(job);
          threads.add(thread);
          thread.start();
        } else if (job.status().equalsIgnoreCase("stopped")) {
          jobs.remove(job);
          JobHelper.cleanJobData(baseFolder, job);
          jobno = 0;
          continue;
        } else if (job.status().equals("failed")) {
          sendFailedJobEmail(job);
          job.setStatus("error");
        }
        jobno++;

        if (jobs.size() == 200) {

          for (int i = 0; i < threads.size(); i++) {
            threads.elementAt(i).join();
          }
          jobno = 0;
          threads.clear();
        }

        sleep(10);
      }

    } catch (Exception e) {
      log.error(ExceptionUtils.getFullStackTrace(e));
      e.printStackTrace();
    }
  }
  @RequestMapping(value = "export-list", method = RequestMethod.GET)
  public String exportTaskList() {

    Collection<Task> tasks = this.taskService.getAllTasks();

    try {

      String filePath = this.localSettingsProperties.getProperty(Constants.TASKS_FILE);

      FileUtils.writeLines(new File(filePath), tasks);
    } catch (IOException ex) {
      LOGGER.error(ExceptionUtils.getFullStackTrace(ex));
    }

    return "redirect:/";
  }
Example #23
0
 public HTableInterface getTable(String tablename) {
   try {
     if (connection == null) {
       connection = HConnectionManager.createConnection(config);
     }
     return connection.getTable(tablename);
   } catch (IOException e) {
     LOG.error(ExceptionUtils.getFullStackTrace(e));
     LOG.error("exception accurs when getting table from hconnection, will be retried");
     try {
       connection = HConnectionManager.createConnection(config);
       return connection.getTable(tablename);
     } catch (Throwable throwable) {
       throw new RuntimeException(throwable);
     }
   }
 }
  @Test
  public void testCommandAlterDocument() {
    running(
        fakeApplication(),
        () -> {
          try {
            DbHelper.open("1234567890", TEST_USER, TEST_USER);
            ObjectNode cmd = MAPPER.createObjectNode();
            ObjectNode p = MAPPER.createObjectNode();
            p.put("id", sGenIds.get(0));
            p.put("collection", TEST_COLLECTION);

            cmd.put(ScriptCommand.RESOURCE, "documents");
            cmd.put(ScriptCommand.NAME, "get");

            cmd.put(ScriptCommand.PARAMS, p);

            JsonNode node = CommandRegistry.execute(cmd, null);
            assertNotNull(node);
            assertTrue(node.isObject());
            ObjectNode doc = node.deepCopy();
            doc.put("extra", "extra");

            ObjectNode upd = MAPPER.createObjectNode();
            upd.put(ScriptCommand.RESOURCE, "documents");
            upd.put(ScriptCommand.NAME, "put");

            ObjectNode params = MAPPER.createObjectNode();
            params.put("collection", TEST_COLLECTION);
            params.put("id", doc.get("id").asText());
            params.put("data", doc);
            upd.put(ScriptCommand.PARAMS, params);
            JsonNode res = CommandRegistry.execute(upd, null);
            assertNotNull(res);
            assertTrue(res.isObject());
            assertNotNull(res.get("extra"));
            assertEquals(res.get("id"), doc.get("id"));
            assertEquals("extra", res.get("extra").asText());
          } catch (Throwable t) {
            fail(ExceptionUtils.getFullStackTrace(t));
          } finally {
            DbHelper.close(DbHelper.getConnection());
          }
        });
  }
Example #25
0
 /**
  * Used for initial get of first page Log.setTcStartTime(); is called. use get(url) to get pages
  * without overwriting the start time.
  *
  * @param url
  */
 public boolean openUrl(String url) {
   se.log().logSeStep("Open URL: " + url);
   try {
     se.driver().get(url);
     deleteCookies();
     se.log().setTcStartTime();
     se.driver().get(url);
   } catch (Exception e) {
     se.log()
         .logTcError(
             String.format(
                 "Unhandled Exception in openUrl %s: %s: %s: %s",
                 url, e, e.getMessage(), ExceptionUtils.getFullStackTrace(e)),
             takeScreenShot());
     return false;
   }
   return se.driver().getTitle() != null;
 }
  @RequestMapping(value = "do-push", method = RequestMethod.GET)
  public String pushOnNotificationEngine() {

    JSONObject toBeSent = new JSONObject();

    toBeSent.put(Constants.TOPIC, "todoApp");

    JSONObject context = new JSONObject();
    context.put(Constants.SUBJECT, "Notification from TodoApp");
    context.put(Constants.CONTENT, "This notification has been sent directly from the TodoApp");

    toBeSent.put(Constants.CONTEXT, context);

    String stringToPost = toBeSent.toString();

    final StringBuilder sb =
        new StringBuilder(this.localSettingsProperties.getProperty(Constants.SERVER_URL));
    sb.append(Constants.RAW_NOTIFICATION);

    String url = sb.toString();

    HttpClient client = new DefaultHttpClient();

    HttpPost post = new HttpPost(url);

    try {
      StringEntity params = new StringEntity(stringToPost);

      post.setEntity(params);

      post.addHeader("Content-Type", "application/json");

      HttpResponse response = client.execute(post);

      LOGGER.info("Notification sent : " + stringToPost);
    } catch (Exception ex) {

      LOGGER.error(ExceptionUtils.getFullStackTrace(ex));

      LOGGER.info("Notification not sent : " + stringToPost);
    }

    return "redirect:/";
  }
Example #27
0
  @Test
  public void testFunctionalMMS() {
    try {

      MMS mmsImpl = getOsgiService(MMS.class, 30000L);
      assertNotNull(mmsImpl);

      // make sure we can generate domain models and annotate metadata
      UMLProjectIdentifer project = new UMLProjectIdentifer();
      project.setIdentifier("caCORE 3.2");
      project.setVersion("3.2");

      System.out.println(
          "Creating domain model for project: "
              + project.getIdentifier()
              + " (version:"
              + project.getVersion()
              + ")");

      // TEST THE MMS CADSR IMPL
      DomainModel domainModel = null;
      try {
        domainModel =
            mmsImpl.generateDomainModelForPackages(
                project, (List<String>) Arrays.asList(new String[] {"gov.nih.nci.cabio.domain"}));
        System.out.println("FOUND A DOMAIN MODEL" + domainModel.getProjectLongName());
        for (Iterator iterator =
                domainModel.getExposedUMLClassCollection().getUMLClass().iterator();
            iterator.hasNext(); ) {
          UMLClass type = (UMLClass) iterator.next();
          System.out.println("\t" + type.getClassName());
        }
      } catch (InvalidUMLProjectIndentifier e) {
        e.printStackTrace();
      }

      assertNotNull(domainModel);
    } catch (Exception e) {
      e.printStackTrace();
      fail(ExceptionUtils.getFullStackTrace(e));
    }
  }
  protected boolean handleReceivingRateLimitStatus(RateLimitStatus rateLimitStatus) {
    try {
      int secondsUntilReset = rateLimitStatus.getSecondsUntilReset();
      int remainingHits = rateLimitStatus.getRemainingHits();

      if (remainingHits == 0) {
        logger.debug("rate status limit service returned 0 for the remaining hits value");

        return false;
      }

      if (secondsUntilReset == 0) {
        logger.debug(
            "rate status limit service returned 0 for the seconds until reset period value");

        return false;
      }

      int secondsUntilWeCanPullAgain = secondsUntilReset / remainingHits;
      long msUntilWeCanPullAgain = secondsUntilWeCanPullAgain * 1000;

      logger.debug(
          "need to Thread.sleep() "
              + secondsUntilWeCanPullAgain
              + " seconds until the next timeline pull. Have "
              + remainingHits
              + " remaining pull this rate period. The period ends in "
              + secondsUntilReset);

      Thread.sleep(msUntilWeCanPullAgain);
    } catch (Throwable throwable) {
      logger.debug(
          "encountered an error when"
              + " trying to refresh the timeline: "
              + ExceptionUtils.getFullStackTrace(throwable));
    }

    return true;
  }
Example #29
0
  @With({AdminCredentialWrapFilter.class, ConnectToDBFilter.class})
  public static Result resetPasswordStep1(String username) {
    if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method Start");

    // check and validate input
    if (username == null)
      return badRequest(
          "The 'username' field is missing in the URL, please check the documentation");

    if (!UserService.exists(username)) return badRequest("Username " + username + " not found!");

    QueryParams criteria =
        QueryParams.getInstance().where("user.name=?").params(new String[] {username});
    ODocument user;

    try {
      List<ODocument> users = UserService.getUsers(criteria);
      user = UserService.getUsers(criteria).get(0);

      ODocument attrObj = user.field(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER);
      if (attrObj == null || attrObj.field("email") == null)
        return badRequest(
            "Cannot reset password, the \"email\" attribute is not defined into the user's private profile");

      // if (UserService.checkResetPwdAlreadyRequested(username)) return badRequest("You have
      // already requested a reset of your password.");

      String appCode = (String) Http.Context.current.get().args.get("appcode");
      UserService.sendResetPwdMail(appCode, user);
    } catch (PasswordRecoveryException e) {
      BaasBoxLogger.warn("resetPasswordStep1", e);
      return badRequest(ExceptionUtils.getMessage(e));
    } catch (Exception e) {
      BaasBoxLogger.warn("resetPasswordStep1", e);
      return internalServerError(ExceptionUtils.getFullStackTrace(e));
    }
    if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method End");
    return ok();
  }
Example #30
0
  @With({UserCredentialWrapFilter.class, ConnectToDBFilter.class})
  @BodyParser.Of(BodyParser.Json.class)
  public static Result updateProfile() {
    Logger.trace("Method Start");
    Http.RequestBody body = request().body();

    JsonNode bodyJson = body.asJson();
    Logger.trace("updateProfile bodyJson: " + bodyJson);
    if (bodyJson == null)
      return badRequest(
          "The body payload cannot be empty. Hint: put in the request header Content-Type: application/json");

    // extract the profile	 fields
    JsonNode nonAppUserAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_ANONYMOUS_USER);
    JsonNode privateAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER);
    JsonNode friendsAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_FRIENDS_USER);
    JsonNode appUsersAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_REGISTERED_USER);

    if (privateAttributes.has("email")) {
      // check if email address is valid
      if (!Util.validateEmail((String) privateAttributes.findValuesAsText("email").get(0)))
        return badRequest("The email address must be valid.");
    }

    ODocument profile;
    try {
      profile =
          UserService.updateCurrentProfile(
              nonAppUserAttributes, privateAttributes, friendsAttributes, appUsersAttributes);
    } catch (Throwable e) {
      Logger.warn("updateProfile", e);
      if (Play.isDev()) return internalServerError(ExceptionUtils.getFullStackTrace(e));
      else return internalServerError(e.getMessage());
    }
    Logger.trace("Method End");

    return ok(prepareResponseToJson(profile));
  } // updateProfile