示例#1
0
  /**
   * Helper method for running yaml workflows using an instance of WorkflowRunner.
   *
   * @param yamlFile The workflow yaml file
   * @param workflow Workflow definition object
   * @param settings A map of the settings provided as input to the runner
   * @return json containing the id of this run
   */
  private static ObjectNode runYamlWorkflow(
      String yamlFile, Workflow workflow, Map<String, Object> settings) {
    InputStream yamlStream = null;
    try {
      yamlStream = loadYamlStream(yamlFile);
    } catch (Exception e) {
      throw new RuntimeException("Could not load workflow from yaml file.", e);
    }

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    ByteArrayOutputStream errStream = new ByteArrayOutputStream();

    // This instance of runnable will be executed at the end of a workflow run
    AsyncWorkflowRunnable runnable = new AsyncWorkflowRunnable();

    try {

      // Get jython home and path variables from application.conf and set them in workflow runner
      // global config
      String jythonPath = ConfigFactory.defaultApplication().getString("jython.packages");
      String jythonHome = ConfigFactory.defaultApplication().getString("jython.home");

      Map<String, Object> config = new HashMap<String, Object>();
      config.put("jython_home", jythonHome);
      config.put("jython_path", jythonPath);

      // Initialize and run the yaml workflow
      WorkflowRunner runner =
          new YamlStreamWorkflowRunner().yamlStream(yamlStream).configure(config);

      runnable.init(workflow, runner, errStream, outStream);

      runner
          .apply(settings)
          .outputStream(new PrintStream(outStream))
          .errorStream(new PrintStream(errStream))
          .runAsync(runnable);
    } catch (Exception e) {
      e.printStackTrace();

      // Log exceptions as part of the workflow error log
      StringWriter writer = new StringWriter();
      e.printStackTrace(new PrintWriter(writer));

      String errorText = writer.toString();
      String outputText = new String(outStream.toByteArray());

      runnable.error(errorText, outputText);
    }

    // The response json contains the workflow run id for later reference
    ObjectNode response = Json.newObject();

    WorkflowRun run = runnable.getWorkflowRun();
    response.put("runId", run.id);

    return response;
  }
示例#2
0
  public static Result createNewUser() {
    Form<User> nu = userForm.bindFromRequest();

    ObjectNode jsonData = Json.newObject();
    String userName = null;

    try {
      userName =
          nu.field("firstName").value()
              + " "
              + (nu.field("middleInitial")).value()
              + " "
              + (nu.field("lastName")).value();
      jsonData.put("userName", userName);
      jsonData.put("firstName", nu.get().getFirstName());
      jsonData.put("middleInitial", nu.get().getMiddleInitial());
      jsonData.put("lastName", nu.get().getLastName());
      jsonData.put("password", nu.get().getPassword());
      jsonData.put("affiliation", nu.get().getAffiliation());
      jsonData.put("title", nu.get().getTitle());
      jsonData.put("email", nu.get().getEmail());
      jsonData.put("mailingAddress", nu.get().getMailingAddress());
      jsonData.put("phoneNumber", nu.get().getPhoneNumber());
      jsonData.put("faxNumber", nu.get().getFaxNumber());
      jsonData.put("researchFields", nu.get().getResearchFields());
      jsonData.put("highestDegree", nu.get().getHighestDegree());

      JsonNode response =
          RESTfulCalls.postAPI(
              Constants.URL_HOST + Constants.CMU_BACKEND_PORT + Constants.ADD_USER, jsonData);

      // flash the response message
      Application.flashMsg(response);
      return redirect(routes.Application.createSuccess());

    } catch (IllegalStateException e) {
      e.printStackTrace();
      Application.flashMsg(RESTfulCalls.createResponse(ResponseType.CONVERSIONERROR));
    } catch (Exception e) {
      e.printStackTrace();
      Application.flashMsg(RESTfulCalls.createResponse(ResponseType.UNKNOWN));
    }
    return ok(signup.render(nu));
  }
示例#3
0
  public F.Promise<Result> call(Http.Context ctx) throws Throwable {
    try {
      return delegate.call(ctx);
    } catch (Exception e) {
      e.printStackTrace();
      StringBuilder sb = new StringBuilder();

      sb.append("Error for request at " + ctx.request().uri() + "\n");
      sb.append("Headers: \n");
      Map<String, String[]> headers = ctx.request().headers();
      for (String key : headers.keySet()) {
        sb.append("  " + key + " --> ");
        for (String val : headers.get(key)) {
          sb.append(val + "|||");
        }
        sb.append("\n");
      }

      sb.append("Cookies: \n");
      for (Http.Cookie cookie : ctx.request().cookies()) {
        sb.append("  " + cookie.name() + " --> " + cookie.value() + "\n");
      }

      Http.RequestBody body = ctx.request().body();
      Map<String, String[]> body_vals = body.asFormUrlEncoded();
      if (body_vals != null) {
        sb.append("Body (as form URL encoded): \n");
        for (String key : body_vals.keySet()) {
          sb.append("  " + key + " --> ");
          for (String val : body_vals.get(key)) {
            sb.append(val + "|||");
          }
          sb.append("\n");
        }
      }

      Logger.error(sb.toString());
      throw e;
    }
  }
示例#4
0
  public static Result isEmailExisted() {
    JsonNode json = request().body().asJson();
    String email = json.path("email").asText();

    ObjectNode jsonData = Json.newObject();
    JsonNode response = null;
    try {
      jsonData.put("email", email);
      response =
          RESTfulCalls.postAPI(
              Constants.URL_HOST + Constants.CMU_BACKEND_PORT + Constants.IS_EMAIL_EXISTED,
              jsonData);
      Application.flashMsg(response);
    } catch (IllegalStateException e) {
      e.printStackTrace();
      Application.flashMsg(RESTfulCalls.createResponse(ResponseType.CONVERSIONERROR));
    } catch (Exception e) {
      e.printStackTrace();
      Application.flashMsg(RESTfulCalls.createResponse(ResponseType.UNKNOWN));
    }
    return ok(response);
  }
  public static void upload(String imei, File data) {

    try {

      File pbFile =
          new File(
              Play.configuration.getProperty("application.uploadDataDirectory"),
              imei + "_" + new Date().getTime() + ".pb");
      Logger.info(pbFile.toString());
      data.renameTo(pbFile);

      byte[] dataFrame = new byte[(int) pbFile.length()];
      ;
      DataInputStream dataInputStream =
          new DataInputStream(new BufferedInputStream(new FileInputStream(pbFile)));

      dataInputStream.read(dataFrame);
      Upload upload = Upload.parseFrom(dataFrame);

      Phone phone = Phone.find("imei = ?", imei).first();
      if (phone == null) badRequest();

      for (Upload.Route r : upload.getRouteList()) {

        if (r.getPointList().size() <= 1) continue;

        Agency a = Agency.find("gtfsAgencyId = ?", "DEFAULT").first();
        Route route = new Route("", r.getRouteName(), RouteType.BUS, r.getRouteDescription(), a);
        route.phone = phone;
        route.routeNotes = r.getRouteNotes();
        route.vehicleCapacity = r.getVehicleCapacity();
        route.vehicleType = r.getVehicleType();
        route.captureTime = new Date(r.getStartTime());
        route.save();

        List<String> points = new ArrayList<String>();

        Integer pointSequence = 1;
        for (Upload.Route.Point p : r.getPointList()) {
          points.add(new Double(p.getLon()).toString() + " " + new Double(p.getLat()).toString());
          RoutePoint.addRoutePoint(p, route.id, pointSequence);
          pointSequence++;
        }

        String linestring = "LINESTRING(" + StringUtils.join(points, ", ") + ")";

        BigInteger tripShapeId = TripShape.nativeInsert(TripShape.em(), "", linestring, 0.0);

        TripPattern tp = new TripPattern();
        tp.route = route;
        tp.headsign = r.getRouteName();
        tp.shape = TripShape.findById(tripShapeId.longValue());
        tp.save();

        Integer sequenceId = 0;

        for (Upload.Route.Stop s : r.getStopList()) {
          BigInteger stopId = Stop.nativeInsert(Stop.em(), s);

          TripPatternStop tps = new TripPatternStop();
          tps.stop = Stop.findById(stopId.longValue());
          tps.stopSequence = sequenceId;
          tps.defaultTravelTime = s.getArrivalTimeoffset();
          tps.defaultDwellTime = s.getDepartureTimeoffset() - s.getArrivalTimeoffset();
          tps.pattern = tp;
          tps.board = s.getBoard();
          tps.alight = s.getAlight();
          tps.save();

          sequenceId++;
        }

        // ProcessGisExport gisExport = new ProcessGisExport(tp.id);
        // gisExport.doJob();
      }

      Logger.info("Routes uploaded: " + upload.getRouteList().size());

      dataInputStream.close();

      ok();
    } catch (Exception e) {
      e.printStackTrace();
      badRequest();
    }
  }
示例#6
0
  public static Result postGenerate(String handler_json) {

    String oper = "";

    RequestBody body = request().body();
    if (body == null) {
      return ok(completeAnnotation.render("Error processing form: form appears to be empty."));
    }

    String textBody = body.asText();
    Properties p = new Properties();
    try {
      p.load(new StringReader(textBody));
    } catch (Exception e) {
      e.printStackTrace();
      return ok(completeAnnotation.render("Error processing form: form appears to be empty."));
    }

    System.out.println("Selection: " + p.getProperty("submitButton"));
    if (p.getProperty("submitButton") != null) oper = p.getProperty("submitButton");

    if (oper.equals(OPER_FINISH)) {
      return ok(completeAnnotation.render("Annotation operation finished."));
    }

    NameSpaces ns = NameSpaces.getInstance();
    String preamble = FRAG_START_PREAMBLE;
    preamble += ns.printNameSpaceList();
    preamble += "\n";

    /*
     * Insert KB
     */

    preamble += FRAG_KB_PART1;
    preamble += Play.application().configuration().getString("hadatac.console.kb");
    preamble += FRAG_KB_PART2;

    try {
      handler_json = URLDecoder.decode(handler_json, "UTF-8");
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.println(handler_json);

    ObjectMapper mapper = new ObjectMapper();
    CSVAnnotationHandler handler = null;
    try {
      handler = mapper.readValue(handler_json, CSVAnnotationHandler.class);

      /*
       * Insert Data Set
       */

      preamble += "<" + DataFactory.getNextURI(DataFactory.DATASET_ABBREV) + ">";
      preamble += FRAG_DATASET;
      preamble += handler.getDataCollectionUri() + ">; ";

      int i = 0;
      int timeStampIndex = -1;
      ArrayList<Integer> mt = new ArrayList<Integer>();
      for (String str : handler.getFields()) {
        // System.out.println(str);
        // System.out.println("get " + i + "-characteristic: [" + p.getProperty(i +
        // "-characteristic") + "]");
        // System.out.println("get " + i + "-unit:           [" + p.getProperty(i + "-unit") + "]");
        if ((p.getProperty(i + "-characteristic") != null)
            && (!p.getProperty(i + "-characteristic").equals(""))
            && (p.getProperty(i + "-unit") != null)
            && (!p.getProperty(i + "-unit").equals(""))) {
          if (p.getProperty(i + "-unit").equals(FRAG_IN_DATE_TIME)) {
            timeStampIndex = i;
          } else {
            mt.add(i);
          }
        }
        i++;
      }

      preamble += FRAG_HAS_MEASUREMENT_TYPE;
      int aux = 0;
      for (Integer mt_count : mt) {
        preamble += FRAG_MT + aux++ + "> ";
      }
      preamble += ".\n\n";

      /*
       * Insert measurement types
       */

      aux = 0;
      for (Integer mt_count : mt) {
        preamble += FRAG_MT + aux;
        preamble += FRAG_MEASUREMENT_TYPE_PART1;
        if (timeStampIndex != -1) {
          preamble += FRAG_IN_DATE_TIME;
          preamble += FRAG_IN_DATE_TIME_SUFFIX;
        }
        preamble += FRAG_MEASUREMENT_TYPE_PART2;
        preamble += mt_count;
        preamble += FRAG_MEASUREMENT_TYPE_PART3;
        preamble += "<" + p.getProperty(mt_count + "-characteristic") + ">";
        preamble += FRAG_MEASUREMENT_TYPE_PART4;
        preamble += "<" + p.getProperty(mt_count + "-unit") + ">";
        preamble += " .\n";
      }

      if (timeStampIndex != -1) {
        preamble += "\n";
        preamble += FRAG_IN_DATE_TIME_STATEMENT + " " + timeStampIndex + "  . \n";
      }

      if (textBody == null) {
        badRequest("Expecting text/plain request body");
      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return ok(completeAnnotation.render("Error processing form. Please restart form."));
    }

    preamble += FRAG_END_PREAMBLE;

    if (oper.equals(OPER_PREAMBLE)) {
      return ok(preamble).as("text/turtle");
    }

    if (oper.equals(OPER_CCSV)) {
      File newFile = new File(handler.getDatasetName());
      try {
        preamble += FileUtils.readFileToString(newFile, "UTF-8");
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return ok(completeAnnotation.render("Error reading cached CSV file. Please restart form."));
      }
      return ok(preamble).as("text/turtle");
    }

    if (oper.equals(OPER_UPLOAD)) {}

    return ok(completeAnnotation.render("Error processing form: unspecified download operation."));
  }
示例#7
0
  public static void inviteNewMember(
      @Required String nom,
      @Required String prenom,
      @Required String mail,
      @Required String langue) {

    try {
      String login = normalize(prenom) + '.' + normalize(nom);
      String url = "";
      String signature = "";
      String community = "Hypertopic";
      //
      String mailGodfather = "";
      String firstNameGodfather = "";
      String lastNameGodfather = "";
      int flag = -1;

      if (session.get("username").equals("admin")) {
        firstNameGodfather = "l'administrateur";
        mailGodfather = "Hypertopic Team <*****@*****.**>";
      } else {
        HashMap<String, String> infos = Ldap.getConnectedUserInfos(session.get("username"));
        mailGodfather = infos.get("mail");
        firstNameGodfather = infos.get("firstName");
        lastNameGodfather = infos.get("lastName");
        firstNameGodfather =
            firstNameGodfather.substring(0, 1).toUpperCase()
                + firstNameGodfather.substring(1).toLowerCase();
        lastNameGodfather =
            lastNameGodfather.substring(0, 1).toUpperCase()
                + lastNameGodfather.substring(1).toLowerCase();
      }
      flag = Invitation.verifyMaliciousPassword(login, mail);
      if (flag == Invitation.ADDRESSES_MATCHE || flag == Invitation.USER_NOTEXIST) {

        System.out.println("invitenewmember");
        try {
          url = "http://" + request.domain;
          if (request.port != 80) url += ":" + request.port;
          url +=
              "/inscription?firstname="
                  + URLEncoder.encode(prenom, "UTF-8")
                  + "&lastname="
                  + URLEncoder.encode(nom, "UTF-8")
                  + "&email="
                  + URLEncoder.encode(mail, "UTF-8");
          signature = Crypto.sign(prenom + nom + mail);
          url += "&signature=" + signature;
          System.out.println("url in inviteNewMember: " + url);
        } catch (UnsupportedEncodingException uee) {
          System.err.println(uee);
        }
        if (validation.hasErrors()) {
          render("Invitation/index.html");
        } else {
          if (renderArgs.get("domainName") != null) {
            community = renderArgs.get("domainName").toString();
          }

          System.out.println("I can arrive heeeeeeeeeeeeeeeeeeeeeeeeer");
          if (langue.equals("fr")) {
            Mails.inviteFr(
                "Hypertopic Team <*****@*****.**>",
                mail,
                prenom,
                nom,
                url,
                community,
                firstNameGodfather,
                lastNameGodfather,
                mailGodfather);
          } else {
            Mails.inviteEn(
                "Hypertopic Team <*****@*****.**>",
                mail,
                prenom,
                nom,
                url,
                community,
                firstNameGodfather,
                lastNameGodfather,
                mailGodfather);
          }
          flash.success(Messages.get("invitation_success"));
          System.out.println("community: " + community);

          session.remove("nom");
          session.remove("prenom");
          session.remove("mail");
          Invitation.invitation();
        }

      } else {
        if (langue.equals("fr")) {
          flash.error(Messages.get("invitation_mailadresse_no_match"));
        } else {
          flash.error(Messages.get("invitation_mailadresse_no_match"));
        }

        Invitation.invitation();
      }
    } catch (Exception e) {
      System.out.println("An exception occurred in Invitation.inviteNewMember");
      e.printStackTrace();
      render("Invitation/index.html");
    }
  }