Exemple #1
0
  /**
   * Get all jobs and instances of each job of a given user.
   *
   * @param username
   * @param token
   * @return registrations array json
   */
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public Response getJobs(
      @CookieParam(value = "user") Cookie userc, @CookieParam(value = "token") String token) {

    UserProfile user;
    try {
      // authenticates the user, throw exception if fail
      user = frameworkUserManager.validate(userc, token);
      if (user == null) {
        return Response.status(Response.Status.UNAUTHORIZED).entity("Invalid credentials").build();
      }
    } catch (Exception e) {
      log.error(e);
      e.printStackTrace();
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }

    try {

      List<Registration> userRegistrations = jmanager.getUserJobs(user);
      Gson gson = new Gson();
      String json = "{ \"jobs\" : " + gson.toJson(userRegistrations) + "}";
      return Response.status(Response.Status.OK)
          .entity(json)
          .type(MediaType.APPLICATION_JSON)
          .build();

    } catch (Exception e) {
      log.error(e);
      e.printStackTrace();
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }
  }
Exemple #2
0
  /**
   * Get job information and executions details. This response has one call to the BatchAdminClient
   * to get the job info and a short info about instances, and the response is completed with one
   * getExecutionDetail request for each instance to grab other useful information about the
   * execution.
   *
   * @param username
   * @param token
   * @return job
   */
  @GET
  @Path("/{jobName}")
  @Produces(MediaType.APPLICATION_JSON)
  public Response getJob(
      @CookieParam(value = "user") Cookie userc,
      @CookieParam(value = "token") String token,
      @PathParam("jobName") String jobName) {

    /*
     * authenticates the user, throw exception if failed
     */
    UserProfile user;
    try {
      // authenticates the user, throw exception if fail
      user = frameworkUserManager.validate(userc, token);
      if (user == null) {
        return Response.status(Response.Status.UNAUTHORIZED).entity("Invalid credentials").build();
      }
    } catch (Exception e) {
      log.error(e);
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }

    try {
      Registration job = jmanager.getJob(jobName, user);
      if (job != null) {
        JobExecutions executions = jmanager.getExcecutions(job);
        Gson gson = new Gson();
        String json =
            "{ \"job\" : "
                + gson.toJson(job)
                + ", \"executions\":"
                + gson.toJson(executions.getJobExecutions())
                + "}";
        return Response.status(Response.Status.OK)
            .entity(json)
            .type(MediaType.APPLICATION_JSON)
            .build();
      } else
        return Response.status(Response.Status.NO_CONTENT)
            .entity("User do not have job")
            .type(MediaType.APPLICATION_JSON)
            .build();

    } catch (Exception e) {
      log.error(e);
      e.printStackTrace();
      return Response.status(Response.Status.EXPECTATION_FAILED).entity(e.getMessage()).build();
    }
  }
Exemple #3
0
  /**
   * Stops a job.
   *
   * @param userc
   * @param token
   * @param jobName
   * @return
   */
  @POST
  @Path("/{jobName}/stop")
  @Produces(MediaType.APPLICATION_JSON)
  public Response stopJob(
      @CookieParam(value = "user") Cookie userc,
      @CookieParam(value = "token") String token,
      @PathParam("jobName") String jobName) {

    /*
     * authenticates the user, throw exception if failed
     */
    UserProfile user;
    try {
      user = frameworkUserManager.validate(userc, token);
      if (user == null) {
        return Response.status(Response.Status.UNAUTHORIZED).entity("Invalid credentials").build();
      }
    } catch (Exception e) {
      log.error(e);
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }

    try {
      JobExecution execution = jmanager.stopJob(jobName, user);
      if (execution == null)
        return Response.status(Response.Status.NO_CONTENT)
            .entity("The execution was not found in the system.")
            .build();

      Gson gson = new Gson();
      String json = "{\"execution\" : " + gson.toJson(execution) + "}";
      return Response.status(Response.Status.OK)
          .entity(json)
          .type(MediaType.APPLICATION_JSON)
          .build();

    } catch (ResourceNotFoundException e) {
      log.error(e);
      return Response.status(Response.Status.NO_CONTENT)
          .entity("The job was not found in the system.")
          .build();
    } catch (Exception e) {
      log.error(e);
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }
  }
Exemple #4
0
  /**
   * Executes job method: Authenticates the user and call the BatchAdminClient to run the job of
   * jobName.
   *
   * @param username
   * @param token
   * @param jobName
   * @return json execution object
   */
  @POST
  @Path("/{jobName}/run")
  @Produces(MediaType.APPLICATION_JSON)
  public Response executesJobs(
      @CookieParam(value = "user") Cookie userc,
      @CookieParam(value = "token") String token,
      @PathParam("jobName") String jobName) {

    /*
     * authenticates the user, throw exception if failed
     */
    UserProfile user;
    try {
      user = frameworkUserManager.validate(userc, token);
      if (user == null) {
        return Response.status(Response.Status.UNAUTHORIZED).entity("Invalid credentials").build();
      }
    } catch (Exception e) {
      log.error(e);
      e.printStackTrace();
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }
    JobExecution execution;
    try {
      execution = jmanager.executesJobs(jobName);
    } catch (Exception e) {
      e.printStackTrace();
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }
    Gson gson = new Gson();
    String json = "{\"execution\" : " + gson.toJson(execution) + "}";
    log.info(json);

    return Response.status(Response.Status.OK)
        .entity(json)
        .type(MediaType.APPLICATION_JSON)
        .build();
  }
Exemple #5
0
  /**
   * Authenticates the users session and creates a xml job file of the required services and
   * registers this job in the batch-admin.
   *
   * <p>OneStepServiceJob.setBody should be encoded to avoid confusion with the job object in the
   * case where the body content for the service is also json.
   *
   * @param userc information about the registered user
   * @param token for authentication
   * @param serviceJob {@link MultiStepJob} JSON
   * @return job in JSON format
   */
  @PUT
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  public Response createMultiStepJob(
      @CookieParam(value = "user") Cookie userc,
      @CookieParam(value = "token") String token,
      MultiStepJob serviceJob) {
    UserProfile user;
    try {
      // authenticates the user, throw exception if fail
      user = frameworkUserManager.validate(userc, token);
      if (user == null) {
        return Response.status(Response.Status.UNAUTHORIZED).entity("Invalid credentials").build();
      }
      log.info(serviceJob.toString());

    } catch (Exception e) {
      log.error(e);
      e.printStackTrace();
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }

    try {
      Registration job = jmanager.createJob(serviceJob, user);
      // read and return response
      Gson gson = new Gson();
      String json = "{ \"job\" : " + gson.toJson(job) + "}";
      log.debug("registered:" + json);

      return Response.status(Response.Status.CREATED).entity(json).build();

    } catch (Exception e) {
      log.error(e);
      e.printStackTrace();
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }
  }
Exemple #6
0
  /**
   * Method to delete a job by its name.
   *
   * @param userc
   * @param token
   * @param jobName
   * @return
   */
  @DELETE
  @Path("/{jobName}")
  @Produces(MediaType.APPLICATION_JSON)
  public Response deleteJob(
      @CookieParam(value = "user") Cookie userc,
      @CookieParam(value = "token") String token,
      @PathParam("jobName") String jobName) {
    UserProfile user;
    try {
      user = frameworkUserManager.validate(userc, token);
      if (user == null) {
        return Response.status(Response.Status.UNAUTHORIZED).entity("Invalid credentials").build();
      }
    } catch (Exception e) {
      log.error(e);
      e.printStackTrace();
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }
    try {
      log.debug("delete job" + jobName);
      if (jmanager.deleteJob(jobName, user))
        return Response.status(Response.Status.NO_CONTENT).build();
      else
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
            .entity("For some reason, the record was not deleted")
            .build();
    } catch (ResourceNotFoundException e) {
      e.printStackTrace();
      return Response.status(Response.Status.NOT_FOUND)
          .entity("The job was not found in the system.")
          .build();
    } catch (Exception e) {

      return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }
  }
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String mode = request.getParameter("mode");

    PrintWriter out = response.getWriter();

    if ("login".equals(mode)) {
      String username = request.getParameter("username");
      String password = request.getParameter("password");

      // check username and password
      boolean correctCredentials = false;
      try {
        if (username != null && !username.isEmpty())
          correctCredentials = frameworkUserManager.checkPassword(username, password);
      } catch (Exception e) {
        e.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        return;
      }

      if (!correctCredentials) {
        response.sendError(HttpServletResponse.SC_OK);
        return;
      }

      // save user's password in password store
      PasswordStore.put(username, password);

      // create and save session token
      String token = UUID.randomUUID().toString();
      try {
        frameworkUserManager.saveSessionToken(username, token);
      } catch (Exception e) {
        e.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        return;
      }

      // get user profile
      UserProfile userProfile;
      try {
        userProfile = frameworkUserManager.getUserProfile(username);
        // send request with session token and user profile

        ObjectMapper objectMapper = new ObjectMapper();
        String responseStr = objectMapper.writeValueAsString(userProfile);

        response.addCookie(new Cookie("token", token));
        response.addCookie(new Cookie("user", URLEncoder.encode(responseStr, "utf-8")));
        response.setHeader("content-type", "application/json");
        out.print(responseStr);

      } catch (Exception e) {
        e.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        return;
      }

    } else if ("logout".equals(mode)) {
      String username = request.getParameter("username");
      // remove user session tokens
      try {
        if (username != null && !username.isEmpty())
          frameworkUserManager.removeAllSessionTokens(username);
        // remove session token from cookies
        Cookie tokenCookie = new Cookie("token", "");
        Cookie userCookie = new Cookie("user", "");
        tokenCookie.setMaxAge(0);
        userCookie.setMaxAge(0);

      } catch (Exception e) {
        e.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
      }

    } else if ("create".equals(mode)) {

      String username = request.getParameter("username");
      String emailTo = request.getParameter("email");
      // check if user already exists
      boolean userExists = false;
      try {
        userExists = frameworkUserManager.checkUserExists(username, emailTo);
      } catch (Exception e) {
        e.printStackTrace();
      }
      if (userExists) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setHeader("content-type", "application/json");
        out.print("{\"code\" : \"1\", \"message\" : \"User already exists\"}");
        return;
      }
      // create user
      String password = new RandomStringGenerator().generateBasic(6);

      try {
        frameworkUserManager.createUser(username, password, emailTo);

        EmailSender emailSender = FrameworkConfiguration.getInstance().getDefaultEmailSender();
        emailSender.send(
            emailTo, "GeoKnow registration", "Your login: "******", password: "******"{\"message\" : \"Your password will be sent to your e-mail address "
                + emailTo
                + " \"}";
        response.getWriter().print(responseStr);

      } catch (MessagingException e) {
        e.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
      } catch (Exception e) {
        e.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
      }

    } else if ("changePassword".equals(mode)) {
      String username = request.getParameter("username");
      String oldPassword = request.getParameter("oldPassword");
      String newPassword = request.getParameter("newPassword");

      // check token
      String token = HttpUtils.getCookieValue(request, "token");
      boolean valid;
      try {
        valid = frameworkUserManager.checkToken(username, token);
        if (!valid) {
          response.sendError(
              HttpServletResponse.SC_UNAUTHORIZED,
              "invalid token " + token + " for user " + username);
        } else {
          // check old password
          boolean isCorrect = frameworkUserManager.checkPassword(username, oldPassword);
          if (!isCorrect) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            out.print("{\"code\" : \"2\", \"message\" : \"Incorrect old password\"}");
            return;
          }

          // change password
          frameworkUserManager.changePassword(username, oldPassword, newPassword);

          // send new password to user
          UserProfile userProfile = frameworkUserManager.getUserProfile(username);
          if (userProfile == null) {
            response.sendError(
                HttpServletResponse.SC_NOT_FOUND, "User profile " + username + " not found");
            return;
          }
          FrameworkConfiguration frameworkConfiguration = FrameworkConfiguration.getInstance();
          EmailSender emailSender = frameworkConfiguration.getDefaultEmailSender();
          emailSender.send(
              userProfile.getEmail(),
              "GeoKnow change password",
              "Your password was changed. Your login: "******", new password: "******"{\"message\" : \"Your password was changed\"}";
          response.getWriter().print(responseStr);
        }
      } catch (Exception e) {
        e.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
      }

    } else if ("restorePassword".equals(mode)) {
      String username = request.getParameter("username");

      // get user profile
      UserProfile userProfile;
      try {
        userProfile = frameworkUserManager.getUserProfile(username);
        if (userProfile == null) {
          response.setStatus(HttpServletResponse.SC_NOT_FOUND);
          out.print("{\"code\" : \"3\", \"message\" : \"User doesn't exists\"}");
          return;
        }
        // change password
        String password = new RandomStringGenerator().generateBasic(6);
        frameworkUserManager.setPassword(username, password);

        // send new password to user
        FrameworkConfiguration frameworkConfiguration = FrameworkConfiguration.getInstance();
        EmailSender emailSender = frameworkConfiguration.getDefaultEmailSender();
        emailSender.send(
            userProfile.getEmail(),
            "GeoKnow registration",
            "Your login: "******", password: "******"{\"message\" : \"Your password will be sent to your e-mail address "
                + userProfile.getEmail()
                + " \"}";

        response.getWriter().print(responseStr);

      } catch (MessagingException e) {
        e.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
      } catch (Exception e) {
        e.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
      }

    } else if ("getUsers".equals(mode)) {
      Collection<UserProfile> profiles;
      try {
        profiles = frameworkUserManager.getAllUsersProfiles();
      } catch (Exception e) {
        e.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        return;
      }

      Collection<String> accounts = new ArrayList<String>();
      for (UserProfile p : profiles) accounts.add(p.getAccountURI());
      String responseStr = new ObjectMapper().writeValueAsString(accounts);
      response.getWriter().print(responseStr);

    } else {

      // throw new ServletException("Unexpected mode: " + mode);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unexpected mode: " + mode);
    }
  }