Exemplo n.º 1
0
  /**
   * ajax 를 이용한 사용자 검색 요청 헤더의 accept 파라미터에 application/json 값이 없으면 406 응답 응답에 포함되는 데이터 수는
   * MAX_FETCH_USERS 로 제한된다 입력 파라미터 query 가 부분매칭 되는 loginId 목록을 json 형태로 응답
   *
   * @param query 검색어
   * @return
   */
  public static Result users(String query) {
    if (!request().accepts("application/json")) {
      return status(Http.Status.NOT_ACCEPTABLE);
    }

    ExpressionList<User> el = User.find.select("loginId, name").where().disjunction();
    el.icontains("loginId", query);
    el.icontains("name", query);
    el.endJunction();

    int total = el.findRowCount();
    if (total > MAX_FETCH_USERS) {
      el.setMaxRows(MAX_FETCH_USERS);
      response().setHeader("Content-Range", "items " + MAX_FETCH_USERS + "/" + total);
    }

    List<Map<String, String>> users = new ArrayList<>();
    for (User user : el.findList()) {
      StringBuilder sb = new StringBuilder();
      sb.append(String.format("<img class='mention_image' src='%s'>", user.avatarUrl()));
      sb.append(String.format("<b class='mention_name'>%s</b>", user.name));
      sb.append(String.format("<span class='mention_username'> @%s</span>", user.loginId));

      Map<String, String> userMap = new HashMap<>();
      userMap.put("info", sb.toString());
      userMap.put("loginId", user.loginId);
      users.add(userMap);
    }

    return ok(toJson(users));
  }
Exemplo n.º 2
0
 public static void activarAlUsuario(Long id) {
   ServiceUsuarios.updateUserById(id);
   Map result = new HashMap();
   result.put("status", 1);
   result.put("message", "El usuario fue activado");
   JSONSerializer mapeo = new JSONSerializer();
   renderJSON(mapeo.serialize(result));
 }
Exemplo n.º 3
0
  /**
   * Will load additional settings from the web app config. Creates a map object that contains
   * workflow parameters to be provided as input to the runner
   *
   * @param form form definition of the workflow being run
   * @return a map of the settings
   */
  private static Map<String, String> settingsFromConfig(FormDefinition form) {
    try {
      Map<String, String> settings = new HashMap<String, String>();

      // Get the workspace basedir from application.conf
      String workspace = ConfigFactory.defaultApplication().getString("jython.workspace");

      // Load workflow yaml file to check parameters
      GenericApplicationContext springContext = new GenericApplicationContext();
      YamlBeanDefinitionReader yamlBeanReader = new YamlBeanDefinitionReader(springContext);
      yamlBeanReader.loadBeanDefinitions(loadYamlStream(form.yamlFile), "-");
      springContext.refresh();

      WorkflowConfig workflowConfig = springContext.getBean(WorkflowConfig.class);

      // Create a workspace
      Path path = Paths.get(workspace, "workspace_" + UUID.randomUUID());
      path.toFile().mkdir();

      // If the "workspace" parameter is present in the workflow set it to the path defined in the
      // config
      if (workflowConfig.getParameters().containsKey("workspace")) {
        settings.put("workspace", path.toString());
      }

      return settings;
    } catch (IOException e) {
      throw new RuntimeException("Error creating workspace directory.", e);
    } catch (Exception e) {
      throw new RuntimeException("Error reading yaml file for parameters.", e);
    }
  }
Exemplo n.º 4
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;
  }
Exemplo n.º 5
0
  @Test
  public void usingForm() {
    final // sneaky final
    // #create
    Form<User> userForm = Form.form(User.class);
    // #create

    // #bind
    Map<String, String> anyData = new HashMap();
    anyData.put("email", "*****@*****.**");
    anyData.put("password", "secret");

    User user = userForm.bind(anyData).get();
    // #bind

    assertThat(user.email, equalTo("*****@*****.**"));
    assertThat(user.password, equalTo("secret"));
  }
Exemplo n.º 6
0
 public static void cambiarContrasenia() {
   String clave = params.get("clave");
   Long coUsuario = Long.parseLong(params.get("coUsuario"));
   Map result = new HashMap();
   String deUsuario = session.get("usuario");
   VmdbUsuario usuario = VmdbUsuario.find("coUsuario = ? and stUsuario = '1'", coUsuario).first();
   usuario.setDeClave(clave);
   usuario.setDaFechaModificacion(new Date());
   usuario.setCoUsuarioModificacion(deUsuario);
   usuario.save();
   /** Actualizar clave en Persona * */
   VmdbPersona objPersona = VmdbPersona.findById(usuario.getVmdbPersona().getCoPersona());
   objPersona.setDeClave(clave);
   objPersona.setCoUsuarioModificacion(deUsuario);
   objPersona.setDaFechaModificacion(new Date());
   objPersona.save();
   /** -----------------------------* */
   result.put("status", 1);
   result.put("message", "Su clave fue actualizado correctamente");
   JSONSerializer mapeo = new JSONSerializer();
   renderJSON(mapeo.serialize(result));
 }
Exemplo n.º 7
0
  /**
   * Start the workflow run asynchronously.
   *
   * @param name The name of the workflow
   * @return json response containing id
   */
  @Security.Authenticated(Secured.class)
  public Result runWorkflow(String name) {
    FormDefinition form = formDefinitionForWorkflow(name);

    // Process file upload first if present in form data
    Http.MultipartFormData body = request().body().asMultipartFormData();

    for (Object obj : body.getFiles()) {
      Http.MultipartFormData.FilePart filePart = (Http.MultipartFormData.FilePart) obj;
      UserUpload userUpload = uploadFile(filePart);

      BasicField fileInputField = form.getField(filePart.getKey());
      fileInputField.setValue(userUpload);
    }

    //  Set the form definition field values from the request data
    Map<String, String[]> data = body.asFormUrlEncoded();
    for (String key : data.keySet()) {
      BasicField field = form.getField(key);
      field.setValue(data.get(key));
    }

    // Transfer form field data to workflow settings map
    Map<String, Object> settings = new HashMap<>();

    for (BasicField field : form.fields) {
      settings.put(field.name, field.value());
    }

    settings.putAll(settingsFromConfig(form));

    // Update the workflow model object and persist to the db
    Workflow workflow = Workflow.find.where().eq("name", form.name).findUnique();

    if (workflow == null) {
      workflow = new Workflow();
    }

    workflow.name = form.name;
    workflow.title = form.title;
    workflow.yamlFile = form.yamlFile;

    workflow.save();

    // Run the workflow
    ObjectNode response = runYamlWorkflow(form.yamlFile, workflow, settings);

    return redirect(routes.Application.index());
  }
Exemplo n.º 8
0
  public static List sortByValue(Map map) {
    List list = new LinkedList(map.entrySet());
    Collections.sort(
        list,
        new Comparator() {
          public int compare(Object o1, Object o2) {
            return ((Comparable) ((Map.Entry) (o1)).getValue())
                .compareTo(((Map.Entry) (o2)).getValue());
          }
        });

    Map result = new LinkedHashMap();
    for (Iterator it = list.iterator(); it.hasNext(); ) {
      Map.Entry entry = (Map.Entry) it.next();
      result.put(entry.getKey(), entry.getValue());
    }
    Collections.reverse(list);
    return list;
  }
Exemplo n.º 9
0
  public Result interactionsBasket(String lang, String basket) {
    String article_title = "";
    String interactions_html = "";
    String titles_html = "";

    // Decompose string coming from client and fill up linkedhashmap
    Map<String, Medication> med_basket = new LinkedHashMap<>();
    if (!basket.isEmpty() && !basket.equals("null")) {
      // Decompose the basket string
      String[] eans = basket.split(",", -1);
      for (String ean : eans) {
        if (!ean.isEmpty()) {
          Medication m = getMedicationWithEan(lang, ean);
          if (m != null) {
            article_title = m.getTitle();
            med_basket.put(ean, m);
          }
        }
      }
    }
    InteractionsData inter_data = InteractionsData.getInstance();
    interactions_html = inter_data.updateHtml(med_basket, lang);
    // Associate section titles and anchors
    String[] section_titles = inter_data.sectionTitles();
    String[] section_anchors = inter_data.sectionAnchors();
    titles_html = "<ul style=\"list-style-type:none;\n\">";
    for (int i = 0; i < section_titles.length; ++i) {
      // Spaces before and after of &rarr; are important...
      String anchor =
          section_anchors[
              i]; // section_titles[i].replaceAll("<html>", "").replaceAll("</html>",
                  // "").replaceAll(" &rarr; ", "-");
      titles_html +=
          "<li><a onclick=\"move_to_anchor('" + anchor + "')\">" + section_titles[i] + "</a></li>";
    }
    titles_html += "</ul>";
    if (interactions_html == null) interactions_html = "";

    return ok(index.render(interactions_html, titles_html, article_title));
  }