Example #1
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String login = request.getParameter("login");
    String pass = request.getParameter("password");

    if (login == null || pass == null) {
      response.setContentType("text/html;charset=utf-8");
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
      return;
    }

    UserProfile profile = accountService.getUserByLogin(login);

    if (profile == null || !profile.getPass().equals(pass)) {
      response.setContentType("text/html;charset=utf-8");
      response.setStatus(401);
      response.getWriter().print("Unauthorized");
    } else {
      accountService.addSession(request.getSession().getId(), profile);
      Gson gson = new Gson();
      String json = gson.toJson(profile);
      // response.getWriter().println(json);
      response.setContentType("text/html;charset=utf-8");
      response.setStatus(200);
      response.getWriter().print("Authorized: " + login);
    }
  }
Example #2
0
  @RequestMapping(value = "/adminAddUser", method = RequestMethod.POST)
  @Transactional
  public String admin2(
      @RequestParam("source") String formSource,
      @RequestParam("email") String formEmail,
      @RequestParam("pass") String formPass,
      @RequestParam("firstName") String formName,
      @RequestParam("lastName") String formLastNAme,
      HttpServletRequest request,
      HttpServletResponse response,
      Model model,
      HttpSession session,
      @RequestParam("csrf") String token) {

    if (!isAdmin(session) || !isTokenValid(session, token))
      response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

    if (formEmail == null || formEmail.length() < 4 || formPass == null || formPass.length() < 4) {
      model.addAttribute("loginError", "usuarios y contraseñas: 4 caracteres mínimo");
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

    } else {
      Usuario user = Usuario.crearUsuario(formEmail, formPass, formName, formLastNAme, "user");
      entityManager.persist(user);
      session.setAttribute("user", user);
      // sets the anti-csrf token
      getTokenForSession(session);
    }
    return "redirect:" + formSource;
  }
  protected Object executeScript(
      ScriptFactory scriptFactory,
      HttpServletRequest request,
      HttpServletResponse response,
      String scriptUrl) {
    Map<String, Object> scriptVariables = createScriptVariables(request, response);

    try {
      return scriptFactory.getScript(scriptUrl).execute(scriptVariables);
    } catch (ScriptNotFoundException e) {
      logger.error("Script not found at " + scriptUrl, e);

      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

      return Collections.singletonMap(errorMessageModelAttributeName, "REST script not found");
    } catch (Exception e) {
      logger.error("Error executing REST script at " + scriptUrl, e);

      HttpStatusCodeAwareException cause =
          ExceptionUtils.getThrowableOfType(e, HttpStatusCodeAwareException.class);
      String errorMsg;

      if (cause != null) {
        response.setStatus(cause.getStatusCode());

        errorMsg = ((Exception) cause).getMessage();
      } else {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        errorMsg = e.getMessage();
      }

      return Collections.singletonMap(errorMessageModelAttributeName, errorMsg);
    }
  }
  @RequestMapping(
      value = "",
      method = RequestMethod.POST,
      consumes = MediaType.APPLICATION_JSON_VALUE,
      produces = MediaType.APPLICATION_JSON_VALUE)
  @PreAuthorize("hasRole('ALL') or hasRole('F_PROGRAM_ENROLLMENT')")
  public void postEnrollmentJson(
      @RequestParam(defaultValue = "CREATE") ImportStrategy strategy,
      HttpServletRequest request,
      HttpServletResponse response)
      throws IOException {
    ImportSummaries importSummaries =
        enrollmentService.addEnrollmentsJson(request.getInputStream(), strategy);
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);

    if (importSummaries.getImportSummaries().size() > 1) {
      response.setStatus(HttpServletResponse.SC_CREATED);
      renderService.toJson(response.getOutputStream(), importSummaries);
    } else {
      response.setStatus(HttpServletResponse.SC_CREATED);
      ImportSummary importSummary = importSummaries.getImportSummaries().get(0);

      if (!importSummary.getStatus().equals(ImportStatus.ERROR)) {
        response.setHeader("Location", getResourcePath(request, importSummary));
      }

      webMessageService.send(WebMessageUtils.importSummaries(importSummaries), response, request);
    }
  }
    private void sendHttpResponseFromOnem2mResponse(
        HttpServletResponse httpResponse, ResponsePrimitive onem2mResponse) throws IOException {

      // the content is already in the required format ...
      String content = onem2mResponse.getPrimitive(ResponsePrimitive.CONTENT);
      String rscString = onem2mResponse.getPrimitive(ResponsePrimitive.RESPONSE_STATUS_CODE);
      String rqi = onem2mResponse.getPrimitive(ResponsePrimitive.REQUEST_IDENTIFIER);
      if (rqi != null) {
        httpResponse.setHeader(Onem2m.HttpHeaders.X_M2M_RI, rqi);
      }

      int httpRSC = mapCoreResponseToHttpResponse(httpResponse, rscString);
      if (content != null) {
        httpResponse.setStatus(httpRSC);
        httpResponse.getWriter().println(content);
      } else {
        httpResponse.setStatus(httpRSC);
      }
      if (rscString.charAt(0) == '2') {
        Onem2mStats.getInstance().inc(Onem2mStats.HTTP_REQUESTS_OK);
      } else {
        Onem2mStats.getInstance().inc(Onem2mStats.HTTP_REQUESTS_ERROR);
      }

      String ct = onem2mResponse.getPrimitive(ResponsePrimitive.HTTP_CONTENT_TYPE);
      if (ct != null) {
        httpResponse.setContentType(ct);
      }
      String cl = onem2mResponse.getPrimitive(ResponsePrimitive.HTTP_CONTENT_LOCATION);
      if (cl != null) {
        httpResponse.setHeader("Content-Location", cl);
      }
    }
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String pathInfo = req.getPathInfo();

    if (pathInfo.equals("/")) {
      HttpSession session = req.getSession();
      if (session == null) {
        resp.setStatus(401);
        return;
      }
      String username = (String) session.getAttribute("username");
      if (username == null) {
        resp.setStatus(401);
        return;
      }

      Map userMap = loadUserSettingsMap(username);
      if (userMap == null) {
        resp.setStatus(401);
        return;
      }
      Enumeration parameterNames = req.getParameterNames();
      while (parameterNames.hasMoreElements()) {
        String parameterName = (String) parameterNames.nextElement();
        userMap.put(parameterName, req.getParameter(parameterName));
      }
      saveUserSettingsMap(username, userMap);
      return;
    }

    super.doPost(req, resp);
  }
Example #7
0
  /**
   * Delete favorite meal of user
   *
   * <p>QUERY STRING should contain the user_id and meal_id
   *
   * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse)
   */
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Statement stmt = null;
    String delete_fav = null;
    String user_id = null;
    String meal_id = null;

    // establish database connection
    Connection conn = dao.connect();

    try {
      user_id = request.getParameter("user_id");
      meal_id = request.getParameter("meal_id");

      // prepare search statement
      delete_fav =
          "DELETE FROM T_FAVORITES WHERE USER_ID = +" + user_id + " AND MEAL_ID = " + meal_id;

      // execute statements
      stmt = conn.createStatement();
      stmt.executeQuery(delete_fav);

      response.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
      response.setStatus(HttpServletResponse.SC_CONFLICT);
      e.printStackTrace();
    } finally {
      // close connection
      dao.close(conn);
    }
  }
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) {
    if (Security.getUserDetails() == null) {
      LOGGER.debug("No user present");
      response.setStatus(403);
      return;
    }

    String transport = request.getParameter("transport");
    if (transport == null) {
      LOGGER.debug("No transport defined for the long polling call");
      response.setStatus(400);
      return;
    }

    if (transport.equals("longpollajax")
        || transport.equals("longpollxdr")
        || transport.equals("longpolljsonp")) {
      doLongPollConnect(request, response, transport);
      return;
    }

    LOGGER.debug("Do not understand the transport '{}'", transport);
    response.setStatus(400);
  }
 public void doPut(
     HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
   String requestPath =
       httpServletRequest.getPathInfo() != null && httpServletRequest.getContextPath() != null
           ? httpServletRequest.getPathInfo()
           : httpServletRequest.getRequestURI();
   if (requestPath.equals("/dumpToLog")) {
     mockServer.dumpToLog(
         httpRequestSerializer.deserialize(
             IOStreamUtils.readInputStreamToString(httpServletRequest)));
     httpServletResponse.setStatus(HttpStatusCode.ACCEPTED_202.code());
   } else if (requestPath.equals("/reset")) {
     mockServer.reset();
     httpServletResponse.setStatus(HttpStatusCode.ACCEPTED_202.code());
   } else if (requestPath.equals("/clear")) {
     mockServer.clear(
         httpRequestSerializer.deserialize(
             IOStreamUtils.readInputStreamToString(httpServletRequest)));
     httpServletResponse.setStatus(HttpStatusCode.ACCEPTED_202.code());
   } else {
     Expectation expectation =
         expectationSerializer.deserialize(
             IOStreamUtils.readInputStreamToString(httpServletRequest));
     mockServer
         .when(expectation.getHttpRequest(), expectation.getTimes())
         .thenRespond(expectation.getHttpResponse());
     httpServletResponse.setStatus(HttpStatusCode.CREATED_201.code());
   }
 }
  /**
   * méthode pour gérer les problèmes de validation de l'objet resource
   *
   * @param exception
   * @param response
   * @return
   */
  @ExceptionHandler
  @ResponseBody
  public Map<String, Object> handleException(Exception exception, HttpServletResponse response) {

    LOGGER.error("Exception : ", exception);

    Map<String, Object> mapErrorMessage = new HashMap<>();
    if (exception instanceof MethodArgumentNotValidException) {

      BindingResult result = ((MethodArgumentNotValidException) exception).getBindingResult();
      List<FieldError> listFieldErrors = result.getFieldErrors();
      for (FieldError fieldError : listFieldErrors) {
        mapErrorMessage.put(fieldError.getField(), fieldError.getDefaultMessage());
      }
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }

    if (exception instanceof AccessDeniedException) {

      mapErrorMessage.put("Error : ", exception.getMessage());
      response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    } else if (exception instanceof ValidationException
        || exception instanceof HttpMessageNotReadableException
        || exception instanceof DataAccessException
        || exception instanceof MongoException
        || exception instanceof SocketTimeoutException
        || exception instanceof RuntimeException) {

      mapErrorMessage.put("Error : ", exception.getMessage());
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }

    LOGGER.error(mapErrorMessage.toString(), exception);
    return mapErrorMessage;
  }
Example #11
0
 @Override
 public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
   if (!ServletFileUpload.isMultipartContent(request)) {
     response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
     return;
   }
   try {
     List<FileItem> files = uploadHandler.parseRequest(request);
     if (files.size() == 0) {
       response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
       return;
     }
     FileItem fileItem = files.get(0);
     if (!fileItem.getContentType().equals(Constants.CLASS_CONTENT_TYPE)
         || fileItem.isFormField()) {
       response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
       return;
     }
     String folderName =
         baseDir + request.getRequestURI().replaceAll("/", Constants.FILE_SEPARATOR);
     File folder = new File(folderName);
     if (folder.exists() && !folder.isDirectory()) {
       response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
       return;
     }
     if (!folder.exists()) {
       folder.mkdirs();
     }
     fileItem.write(new File(folderName + Constants.FILE_SEPARATOR + fileItem.getName()));
   } catch (Exception e) {
     response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
     return;
   }
 }
Example #12
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    Long id = getId(req);
    if (id == null) {
      resp.setStatus(SC_BAD_REQUEST);
      return;
    }

    Movie movie;
    try {
      movie = gson.fromJson(req.getReader(), Movie.class);
    } catch (Exception ignore) {
      resp.setStatus(SC_BAD_REQUEST);
      return;
    }

    if (!isMovieValid(movie) || movie.getId() != null && !movie.getId().equals(id)) {
      resp.setStatus(SC_BAD_REQUEST);
      return;
    }
    movie.setId(id);
    Movie prevMovieVersion = service.updateMovie(movie);
    if (prevMovieVersion == null) {
      resp.setStatus(SC_NOT_FOUND);
    }
  }
Example #13
0
  public static void serveFile(
      File file, String mimeType, HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    if (!file.exists()) {
      response.setStatus(HttpServletResponse.SC_NOT_FOUND);
      return;
    }
    if (file.isDirectory()) {
      response.setStatus(HttpServletResponse.SC_FORBIDDEN);
      return;
    }

    long lastMod = file.lastModified() / 1000 * 1000;
    long ifModSinc = request.getDateHeader(REQUEST_DATE_HEADER_IF_MOD_SINCE);
    // System.out.println("IF MOD SINCE "+new Date(ifModSinc));
    // System.out.println(file.getAbsolutePath()+" LAST MOD "+new Date(lastMod));
    if (lastMod <= ifModSinc) {
      response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
      return;
    }

    response.setContentType(mimeType);
    response.setContentLength((int) file.length());
    response.setDateHeader(RESPONSE_DATE_HEADER_LAST_MOD, lastMod);
    FileInputStream in = new FileInputStream(file);
    OutputStream out = response.getOutputStream();
    byte[] buf = new byte[SERVE_BLOCK_SIZE];
    int count = 0;
    while ((count = in.read(buf)) >= 0) {
      out.write(buf, 0, count);
    }
    in.close();
    out.close();
  }
 @RequestMapping(method = RequestMethod.POST, value = "/reward")
 @ResponseBody
 public String reward(HttpServletRequest request, HttpServletResponse response)
     throws IOException {
   JSONObject webhooks = Tools.getParams(request);
   logger.debug("webhooks info == " + webhooks);
   JSONObject charge = webhooks.getJSONObject("data").getJSONObject("object");
   logger.debug("charge info == " + charge);
   String dealId = charge.getString("order_no");
   logger.debug("deal id: " + dealId);
   if (charge.getBoolean("paid") == true) {
     Deal deal = new Deal();
     deal.setDealId(dealId);
     deal.setDealStatus(true);
     dealService.updateDealRecord(deal);
   }
   Event event = Webhooks.eventParse(webhooks.toString());
   if ("charge.succeeded".equals(event.getType())) {
     response.setStatus(200);
   } else if ("refund.succeeded".equals(event.getType())) {
     response.setStatus(200);
   } else {
     response.setStatus(500);
   }
   return "complete";
 }
  @RequestMapping(
      method = RequestMethod.POST,
      value = "/eu.trentorise.smartcampus.journeyplanner.sync.BasicJourneyPlannerUserProfile")
  public @ResponseBody void createUserProfile(
      HttpServletRequest request, HttpServletResponse response, HttpSession session)
      throws InvocationException, AcServiceException {
    try {
      User user = getUser(request);
      String userId = getUserId(user);
      if (userId == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
      }

      BasicJourneyPlannerUserProfile profile = new BasicJourneyPlannerUserProfile();

      Map<String, Object> pars = new HashMap<String, Object>();
      pars.put("userProfile", profile.getData());
      String clientId = profile.getClientId();
      if (clientId == null) {
        clientId = new ObjectId().toString();
      }
      pars.put("clientId", clientId);
      domainClient.invokeDomainOperation(
          "createUserProfile",
          "smartcampus.services.journeyplanner.UserProfileFactory",
          "smartcampus.services.journeyplanner.UserProfileFactory.0",
          pars,
          userId,
          "vas_journeyplanner_subscriber");
      storage.storeObject(profile);
    } catch (Exception e) {
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }
  private void getMessage(final Request jettyRequest, final HttpServletResponse response)
      throws IOException {
    // Validation should be done on client side already
    final String topic = jettyRequest.getParameter("topic");
    final int partition = Integer.parseInt(jettyRequest.getParameter("partition"));
    final String group = jettyRequest.getParameter("group");
    final long offset = Long.parseLong(jettyRequest.getParameter("offset"));
    final int maxSize = Integer.parseInt(jettyRequest.getParameter("maxsize"));

    try {
      final GetCommand getCommand =
          this.convert2GetCommand(topic, partition, group, offset, maxSize);
      final ResponseCommand responseCommand =
          this.commandProcessor.processGetCommand(getCommand, null, false);
      if (responseCommand instanceof DataCommand) {
        response.setStatus(HttpStatus.Success);
        response.getOutputStream().write(((DataCommand) responseCommand).getData());
      } else {
        response.setStatus(((BooleanCommand) responseCommand).getCode());
        response.getWriter().write(((BooleanCommand) responseCommand).getErrorMsg());
      }
    } catch (final Throwable e) {
      logger.error("Could not get message from position " + offset, e);
      response.setStatus(HttpStatus.InternalServerError);
      response.getWriter().write(e.getMessage());
    }
  }
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String pathInfo = req.getPathInfo();

    HttpSession session = req.getSession();
    if (session == null) {
      resp.setStatus(401);
      return;
    }
    String username = (String) session.getAttribute("username");
    if (username == null) {
      resp.setStatus(401);
      return;
    }

    Map userMap = loadUserSettingsMap(username);
    if (userMap == null) {
      resp.setStatus(401);
      return;
    }
    if (pathInfo.equals("/")) {
      resp.setContentType("application/json; charset=UTF-8");
      resp.getWriter().write(JSONUtil.write(userMap));
      return;
    }

    String key = pathInfo.substring(1);
    String value = (String) userMap.get(key);

    Map jsonObject = new HashMap();
    jsonObject.put(key, value);
    resp.setContentType("application/json; charset=UTF-8");
    resp.getWriter().write(JSONUtil.write(jsonObject));
  }
 @Override
 public void handle(
     final String target,
     final Request jettyRequest,
     final HttpServletRequest request,
     final HttpServletResponse response)
     throws IOException, ServletException {
   if (target.length() < 2) {
     response.setStatus(HttpStatus.BadRequest);
     response.getWriter().write("Invalid request");
   } else {
     final char command = target.charAt(1);
     switch (command) {
       case 'g':
         this.getMessage(jettyRequest, response);
         break;
       case 'p':
         this.putMessage(jettyRequest, response);
         break;
       case 'o':
         this.getOffset(jettyRequest, response);
         break;
       default:
         response.setStatus(HttpStatus.BadRequest);
         response.getWriter().write("Invalid request");
         break;
     }
   }
   response.flushBuffer();
 }
  protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String pathInfo = req.getPathInfo();

    HttpSession session = req.getSession();
    if (session == null) {
      resp.setStatus(401);
      return;
    }
    String username = (String) session.getAttribute("username");
    if (username == null) {
      resp.setStatus(401);
      return;
    }

    Map userMap = loadUserSettingsMap(username);
    if (userMap == null) {
      resp.setStatus(401);
      return;
    }
    if (pathInfo.equals("/")) {
      userMap.clear();
    }
    String key = pathInfo.substring(1);
    userMap.remove(key);
    saveUserSettingsMap(username, userMap);
    return;
  }
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();

    // String baseUrl = "http://linux06.fomfrv.dk:8081/aisview/rest";
    String baseUrl = "http://localhost:8092/aisview/rest";
    String url = baseUrl;
    if (request.getPathInfo() != null) {
      url += request.getPathInfo();
    }
    if (request.getQueryString() != null) {
      url += "?" + request.getQueryString();
    }

    LOG.debug("JSOPN proxy request for service: " + url);

    String output;
    try {
      output = requestUrl(url);
      response.setStatus(HttpServletResponse.SC_OK);
    } catch (IOException e) {
      output = "{\"error\":true}";
      response.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
    }
    out.print(output);
  }
Example #21
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    try {

      Payload payload = gson.fromJson(req.getReader(), Payload.class);

      if (payload != null && payload.getMarkdown() != null) {

        String html = "";
        if (payload.getLinkAttributes() != null && payload.getLinkAttributes().size() > 0) {
          AttributesLinkRederer linkRenderer =
              new AttributesLinkRederer(payload.getLinkAttributes());
          html = processor.markdownToHtml(payload.getMarkdown(), linkRenderer);
        } else {
          html = processor.markdownToHtml(payload.getMarkdown());
        }

        resp.getWriter().write(html);
      }

      resp.getWriter().close();
      resp.setStatus(200);
    } catch (Exception e) {
      e.printStackTrace();
      resp.setStatus(500);
    }
  }
Example #22
0
  /**
   * Check the manifest cookie.
   *
   * <p>This routine checks the cookie and parameter on the request and sets the response code
   * appropriately if we should not send back a manifest.
   *
   * @param request the request (for the incoming cookie).
   * @param response the response (for the outgoing cookie and status)
   * @return false if the caller should bolt because we already set the status.
   */
  public static boolean checkManifestCookie(
      HttpServletRequest request, HttpServletResponse response) {
    Cookie cookie = getManifestCookie(request);
    String cookieString = null;

    if (cookie != null) {
      cookieString = cookie.getValue();
    }
    cookieString = updateManifestCookieValue(cookieString);
    if (cookieString == null) {
      deleteManifestCookie(response);
      response.setStatus(HttpServletResponse.SC_NOT_FOUND);
      return false;
    }
    //
    // Now we look for the client telling us we need to break a cycle, in which case we set a cookie
    // and give the client no content.
    //
    if (errorParam.get(request) != null) {
      addManifestErrorCookie(response);
      response.setStatus(HttpServletResponse.SC_NO_CONTENT);
      return false;
    }

    addManifestCookie(response, cookieString, SHORT_EXPIRE_SECONDS);
    return true;
  }
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
      throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    try {
      Authentication authentication = authenticationService.getAuthentication(httpRequest);
      SecurityContextHolder.getContext().setAuthentication(authentication);
      filterChain.doFilter(httpRequest, httpResponse);

    } catch (SignatureException exception) {
      httpResponse.setCharacterEncoding("UTF-8");
      httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
      httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

      ObjectMapper mapper = new ObjectMapper();

      FailureResponse error =
          new FailureResponse(
              httpRequest.getMethod(),
              httpRequest.getRequestURI(),
              "unauthorized JWT (invalid signature or expired token). Please use auth api to take another valid token.");
      httpResponse.getWriter().println(mapper.writeValueAsString(error));

      SecurityContextHolder.clearContext();

    } catch (MalformedJwtException exception) {
      httpResponse.setCharacterEncoding("UTF-8");
      httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
      httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

      ObjectMapper mapper = new ObjectMapper();

      FailureResponse error =
          new FailureResponse(
              httpRequest.getMethod(),
              httpRequest.getRequestURI(),
              "malformed token. Please use auth api to take another valid token.");
      httpResponse.getWriter().println(mapper.writeValueAsString(error));

      SecurityContextHolder.clearContext();

    } catch (Exception exception) {
      httpResponse.setCharacterEncoding("UTF-8");
      httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
      httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

      ObjectMapper mapper = new ObjectMapper();

      FailureResponse error =
          new FailureResponse(
              httpRequest.getMethod(),
              httpRequest.getRequestURI(),
              "Internal server error, please contact the backend team.");
      httpResponse.getWriter().println(mapper.writeValueAsString(error));
      LOGGER.error(exception.getMessage(), exception);
      SecurityContextHolder.clearContext();
    }
  }
Example #24
0
  @Override
  public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
      throws IOException, ServletException {
    GitilesView.Builder view;
    try {
      view = parse(req);
    } catch (IOException err) {
      String name = urls.getHostName(req);
      log.warn("Cannot parse view" + (name != null ? " for " + name : ""), err);
      res.setStatus(SC_SERVICE_UNAVAILABLE);
      return;
    }
    if (view == null) {
      res.setStatus(SC_NOT_FOUND);
      return;
    }

    @SuppressWarnings("unchecked")
    Map<String, String[]> params = req.getParameterMap();
    view.setHostName(urls.getHostName(req))
        .setServletPath(req.getContextPath() + req.getServletPath())
        .putAllParams(params);
    if (normalize(view, res)) {
      return;
    }

    setView(req, view.build());
    try {
      chain.doFilter(req, res);
    } finally {
      removeView(req);
    }
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html;charset=utf-8");

    String remove = request.getParameter("remove");

    if (remove != null) {
      accountServer.removeUser();
      response.getWriter().println("Hasta la vista!");
      response.setStatus(HttpServletResponse.SC_OK);
      return;
    }

    int limit = accountServer.getUsersLimit();
    int count = accountServer.getUsersCount();

    logger.info("Limit: {}. Count {}", limit, count);

    if (limit > count) {
      logger.info("User pass");
      accountServer.addNewUser();
      response.getWriter().println("Hello, world!");
      response.setStatus(HttpServletResponse.SC_OK);
    } else {
      logger.info("User were rejected");
      response.getWriter().println("Server is closed for maintenance!");
      response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    }
  }
Example #26
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    SessionController sc = null;
    String gameid = null;
    try {
      if (request.getParameter("game") != null) {
        gameid = request.getParameter("game");
        sc = SessionController.getSessionController(gameid);
      } else {
        throw new RuntimeException("GameParameter missing");
      }

      if (sc.isUser(request)) {
        String user = sc.getUser(request);
        sc.removeSession(request.getSession().getId());
        sc.endRound.remove(user);
        sc.endReturned.remove(user);
        Tycoon.deleteUser(gameid, user);
      } else {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
      }
    } catch (Exception e) {
      try {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        PrintWriter pr = response.getWriter();
        e.printStackTrace(pr);
        pr.close();
      } catch (Exception ex) {
      }
    }
  }
Example #27
0
  public HttpServletRequest addurl(HttpServletRequest req, HttpServletResponse response) {
    int idUser = Integer.parseInt(req.getParameter("id"));
    String siteUrl = req.getParameter("url");
    String nomUrl = req.getParameter("nomUrl");
    Url url = new Url(idUser, siteUrl, nomUrl, 0);
    User userInstance = User.getInstance();
    Url oldurl = userInstance.getUrlByUri(siteUrl);
    if (oldurl == null) {
      try {
        url.addUrlToDBB();
        url.setuId(url.getIdFromBDD());
        User user = (User) this.parent.user();
        user.addOneUrl(url);
        response.setStatus(200);
      } catch (MySQLIntegrityConstraintViolationException e) {
        // URL existe d�j� dans la BDD
        System.out.println("URL duppliquee");
        response.setStatus(201);

      } catch (SQLException e) {
        // erreur dans l'insertion a la BDD
        e.printStackTrace();
        response.setStatus(400);
      }
    } else {
      System.out.println("URL duppliquee");
      response.setStatus(201);
    }

    return req;
  }
  @RequestMapping(method = RequestMethod.GET, value = "/getparkingsbyagency/{agencyId}")
  public @ResponseBody void getParkingsByAgency(
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession session,
      @PathVariable String agencyId)
      throws InvocationException, AcServiceException {
    //		if ("COMUNE_DI_TRENTO".equals(agencyId)) {
    //			getParkings(request,response,session);
    //			return;
    //		}
    try {
      String address = otpURL + SMARTPLANNER + "getParkingsByAgency?agencyId=" + agencyId;

      String routes = HTTPConnector.doGet(address, null, null, MediaType.APPLICATION_JSON, "UTF-8");

      response.setContentType("application/json; charset=utf-8");
      response.getWriter().write(routes);

    } catch (ConnectorException e0) {
      response.setStatus(e0.getCode());
    } catch (Exception e) {
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }
Example #29
0
 @Override
 public void service(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   String pathInfo = request.getPathInfo();
   if (pathInfo == null) {
     response.setStatus(HttpServletResponse.SC_NOT_FOUND);
   } else {
     try {
       // Handle JSP requests.
       if (pathInfo.endsWith(".jsp")) {
         if (handleDevJSP(pathInfo, request, response)) {
           return;
         }
         handleJSP(pathInfo, request, response);
       }
       // Handle servlet requests.
       else if (getServlet(pathInfo) != null) {
         handleServlet(pathInfo, request, response);
       }
       // Handle image/other requests.
       else {
         handleOtherRequest(pathInfo, response);
       }
     } catch (Exception e) {
       Log.error(e.getMessage(), e);
       response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
     }
   }
 }
Example #30
0
  @ResponseBody
  @RequestMapping(value = "modify", method = RequestMethod.POST)
  public String modify(HttpServletRequest request, HttpServletResponse response) {
    JSONObject json = FormRequestUtil.parseData(request);

    Object _id = json.get("id");
    if (_id == null) {
      response.setStatus(HttpStatus.BAD_REQUEST.value());
      return "媒体Id不能为空";
    }

    int id = Integer.parseInt(_id.toString());
    Media media = service.getById(id);
    if (media != null) {
      String desc = (String) json.get("desc");
      String logourl = (String) json.get("logourl");
      String siteurl = (String) json.get("siteurl");
      if (StringUtils.isNotBlank(desc)) {
        media.setDesc(desc);
      }
      if (StringUtils.isNotBlank(logourl)) {
        media.setLogourl(logourl);
      }
      if (StringUtils.isNotBlank(siteurl)) {
        media.setSiteurl(siteurl);
      }

      return media.toJson().toJSONString();
    } else {
      response.setStatus(HttpStatus.NOT_FOUND.value());
      return "媒体[id=" + _id + "]不存在";
    }
  }