Example #1
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    LOG.debug("api - user info");

    String udid = request.getParameter("udid");
    if (null == udid) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, "udid is required!");
      return;
    }
    LOG.debug("udid - " + udid);

    User user = talkService.getUserByUdid(udid);
    if (null == user) {
      response.sendError(HttpServletResponse.SC_NO_CONTENT, "the udid is not registered!");
      return;
    }

    Set<String> channels = new HashSet<String>();
    for (Channel channel : user.getChannelList()) {
      LOG.debug("channel: " + channel.getName());
      channels.add(ServiceUtils.postfixAliasAndTag(channel.getName()));
    }

    Gson gson = new Gson();
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("username", ServiceUtils.postfixAliasAndTag(user.getName()));
    params.put("channels", channels);

    String info = gson.toJson(params);
    LOG.info("The user info: " + info);

    response.getOutputStream().write(info.getBytes());
  }
Example #2
0
  private void handleRequest(final HttpServletRequest req, final HttpServletResponse resp)
      throws IOException {
    try {
      final URI referer = new URI(req.getHeader("referer")); // $NON-NLS-1$
      if (!referer.getHost().equals(req.getServerName())
          || referer.getPort() != req.getServerPort()
          || !referer.getPath().startsWith(req.getContextPath())) {
        throw new Exception();
      }
    } catch (final Exception e) {
      resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
      return;
    }

    final String command = req.getPathInfo();
    if (command != null && command.equals("/openFile")) { // $NON-NLS-1$
      execOpenFile(req, resp);
      resp.setHeader(
          "Cache-Control", "no-store, no-cache, must-revalidate"); // $NON-NLS-1$ //$NON-NLS-2$
      return;
    }

    resp.sendError(
        HttpServletResponse.SC_BAD_REQUEST, "Unsupported command: " + command); // $NON-NLS-1$
    return;
  }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String companyName = "Hertz";
    String userName = "******";

    req.getSession().setAttribute("renter", userName);

    try {
      boolean fullApplicationDeployed =
          new File(getServletContext().getRealPath(JSPSite.CREATE_QUOTES.url())).exists();

      if (CarRentalModel.get().getReservations(userName).size() == 0 && !fullApplicationDeployed) {

        ReservationConstraints c =
            new ReservationConstraints(
                ViewTools.DATE_FORMAT.parse("01.02.2011"),
                ViewTools.DATE_FORMAT.parse("01.03.2011"),
                "Compact");

        final Quote q = CarRentalModel.get().createQuote(companyName, userName, c);
        List<Quote> quotes = new ArrayList<Quote>();
        quotes.add(q);
        CarRentalModel.get().confirmQuotes(quotes);
      }

      resp.sendRedirect(JSPSite.PERSIST_TEST.url());
    } catch (ParseException e) {
      resp.sendError(
          HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ViewTools.stacktraceToHTMLString(e));
    } catch (ReservationException e) {
      resp.sendError(
          HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ViewTools.stacktraceToHTMLString(e));
    }
  }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String user = userManager.getRemoteUsername();
    if (!userManager.isAdmin(user)) {
      resp.sendError(403, "Must be an administrator to configure Speakeasy");
      return;
    }

    webResourceManager.requireResource("com.atlassian.auiplugin:ajs");
    webResourceManager.requireResourcesForContext("speakeasy.admin");

    try {
      final Settings settings = speakeasyService.getSettings(user);
      resp.setContentType("text/html");
      render(
          "templates/admin.vm",
          ImmutableMap.<String, Object>builder()
              .put("user", user)
              .put("contextPath", req.getContextPath())
              .put(
                  "staticResourcesPrefix",
                  webResourceManager.getStaticResourcePrefix(UrlMode.RELATIVE))
              .put("settings", new JsRenderer(jsonMarshaller.marshal(settings)))
              .put("permissionsJson", new JsRenderer(jsonMarshaller.marshal(Permission.ALL)))
              .put("permissions", Permission.ALL)
              .build(),
          resp.getWriter());
    } catch (UnauthorizedAccessException e) {
      resp.sendError(403, e.getMessage());
    }
    resp.getWriter().close();
  }
Example #5
0
  void handle(String target, HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    String moduleName = getModuleNameFromRequest(target);
    if (moduleName == null) {
      throw new RuntimeException("invalid request (shouldn't happen): " + target);
    }

    String rootDir = SOURCEMAP_PATH + moduleName + "/";
    if (!target.startsWith(rootDir)) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
      logger.log(TreeLogger.WARN, "returned not found for request: " + target);
      return;
    }

    String rest = target.substring(rootDir.length());

    if (rest.isEmpty()) {
      sendDirectoryListPage(moduleName, response);

    } else if (rest.endsWith("/")) {
      sendFileListPage(moduleName, rest, response);

    } else if (rest.equals("gwtSourceMap.json")) {
      sendSourceMap(moduleName, request, response);

    } else if (rest.endsWith(".java")) {
      sendSourceFile(moduleName, rest, request.getQueryString(), response);

    } else {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
      logger.log(TreeLogger.WARN, "returned not found for request: " + target);
    }
  }
Example #6
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Logger log = LoggerFactory.getLogger(AddEventServlet.class);
    String sid = request.getParameter("id");
    String scontent = request.getParameter("content");
    if (sid == null || !StringUtils.isNumeric(sid)) {
      response.sendError(401, "非法操作,权限终结");
      return;
    }
    Long id = Long.valueOf(sid);
    ContentService cts = new ContentService();
    Content content = new Content();
    HttpSession session = request.getSession();
    Account account = (Account) session.getAttribute("account");
    if (account != null) {
      content.setAccountid(account.getId());
    }
    content.setContent(scontent);
    content.setCustid(id);
    content.setCreatetime(getNowtime());
    if (cts.addContent(content) > 0) {
      log.debug("添加{}备注内容为:{} 存储成功", id, content);
      response.sendRedirect("/cust/event.do?id=" + id);
      return;
    } else {

      response.sendError(500, "请稍后再试");
    }
  }
Example #7
0
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    @SuppressWarnings("unchecked")
    Map<String, String[]> params = req.getParameterMap();

    HttpSession session = req.getSession(true);
    session.setAttribute(LANG, "en"); // Defaults to English //$NON-NLS-1$

    if (params.containsKey("lang")) { // $NON-NLS-1$
      String lang = params.get("lang")[0]; // $NON-NLS-1$
      Messages.setLang(lang);
      if (this.availableLanguages.contains(lang)) {
        session.setAttribute(LANG, lang);
        resp.getWriter()
            .print(
                Messages.getString("localeservlet.lang_set_to")
                    + lang
                    + "'"); //$NON-NLS-1$ //$NON-NLS-2$
      } else {
        resp.sendError(
            HttpServletResponse.SC_BAD_REQUEST,
            Messages.getString("localeservlet.lang_not_available")); // $NON-NLS-1$
      }
    } else {
      resp.sendError(
          HttpServletResponse.SC_BAD_REQUEST,
          Messages.getString("localeservlet.not_lang_parameter") // $NON-NLS-1$
              + this.availableLanguages.toString());
    }
  }
Example #8
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    Logger.debug("Order Admin servlet!");
    String cmdName = req.getParameter("cmd");
    AdminOrderCommand command;

    Logger.debug("[OrderAdmin] Cmd: " + cmdName);
    try {
      command = Command.getFromName(cmdName, AdminOrderCommand.class);
      command.execute(req);
      if (!StringUtils.isEmpty(command.getRedirect())) {
        RequestDispatcher dispatcher = req.getRequestDispatcher(command.getRedirect());
        dispatcher.forward(req, resp);
      } else {
        // Se nao tem view pra mostrar, manda status OK pelo menos!
        resp.setStatus(HttpServletResponse.SC_OK);
      }
    } catch (CommandNotFoundException e) {
      Logger.warning("[Order]Comando nao definido! - " + cmdName);
      resp.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (Exception e) {
      Logger.error("Erro!", e);

      // TODO mostrar algo ao usuario
      resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }
  /**
   * Parse the specified filter tokens and setup various request attributes from the parsed values.
   *
   * <p>Attributes that may be created (depending on the tokens passed in):
   *
   * <ul>
   *   <li><code>WebConstants.REQUEST_CID</code>
   *   <li><code>WebConstants.REQUEST_PID</code>
   *   <li><code>WebConstants.REQUEST_PAGE_NUM</code>
   *   <li><code>WebConstants.REQUEST_FILTERS</code>
   * </ul>
   *
   * @param tokens the tokens to parse.
   * @param aRequest the request to set attributes on.
   */
  private void setupRequestAttributes(
      final String[] tokens, final HttpServletRequest aRequest, final HttpServletResponse response)
      throws IOException {

    final StringBuffer sbfFilters = new StringBuffer();
    for (int i = 0; i < tokens.length; i++) {
      final String decodedToken = decodeString(tokens[i]);
      if (decodedToken.startsWith(SeoConstants.CATEGORY_PREFIX)) {
        final String value = getValue(decodedToken, SeoConstants.CATEGORY_PREFIX);
        aRequest.setAttribute(WebConstants.REQUEST_CID, value);
        sbfFilters.append(decodedToken).append(' ');

      } else if (decodedToken.startsWith(SeoConstants.PRODUCT_PREFIX)) {
        final String value = getValue(decodedToken, SeoConstants.PRODUCT_PREFIX);
        aRequest.setAttribute(WebConstants.REQUEST_PID, value);
        // Do not append a filter element for products because it doesn't
        // make sense to filter on a specific product.

      } else if (decodedToken.startsWith(SeoConstants.PRICE_FILTER_PREFIX)) {
        sbfFilters.append(decodedToken).append(' ');

      } else if (decodedToken.startsWith(SeoConstants.ATTRIBUTE_RANGE_FILTER_PREFIX)) {
        sbfFilters.append(decodedToken).append(' ');

      } else if (decodedToken.startsWith(SeoConstants.ATTRIBUTE_FILTER_PREFIX)) {
        sbfFilters.append(decodedToken).append(' ');

      } else if (decodedToken.startsWith(SeoConstants.BRAND_FILTER_PREFIX)) {
        final String value = getValue(decodedToken, SeoConstants.BRAND_FILTER_PREFIX);
        final String brandFilterId = getBrandFilterId(value);
        sbfFilters.append(brandFilterId).append(' ');

      } else if (decodedToken.startsWith(SeoConstants.PAGE_NUMBER_PREFIX)) {
        final String value = getValue(decodedToken, SeoConstants.PAGE_NUMBER_PREFIX);
        Matcher matcher = PAGE_NUMBER_VALIDATOR.matcher(value);
        if (!matcher.matches()) {
          // invalid page number, send "page not found" to prevent
          // the system responding with a page to malicious urls.
          response.sendError(HttpServletResponse.SC_NOT_FOUND);
          return;
        }
        aRequest.setAttribute(WebConstants.REQUEST_PAGE_NUM, value);
        // Do not append a filter element for page numbers because it doesn't
        // make sense to filter by a specific page.
      } else if (decodedToken.equals(SeoConstants.SITEMAP_PREFIX)) {
        // Do nothing, this block explicitly allows sitemap urls through
        continue;
      } else {
        // invalid request parameter, send "page not found" to prevent
        // the system responding with a page to malicious urls.
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
      }
    }

    if (sbfFilters.length() > 0) {
      aRequest.setAttribute(
          WebConstants.REQUEST_FILTERS, sbfFilters.substring(0, sbfFilters.length() - 1));
    }
  }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    LOGGER.info("Received request:\n" + req.getRequestURL());
    Resource resource = null;

    if (req.getParameterMap().isEmpty()) {
      String resourceId = getResourceId(req);
      if (resourceId != null) {
        resource = repository.getPolicy(resourceId);
        if (resource == null) {
          resp.sendError(HttpServletResponse.SC_NOT_FOUND);
          return;
        }
      } else {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
      }
    } else {
      resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
      return;
    }
    resp.setContentType(resource.getContentType());
    resp.setCharacterEncoding(resource.getCharacterEncoding());
    resource.appendContent(resp.getWriter());
  }
Example #11
0
  /**
   * Service a GET request as described below. Request: {@code GET http://<nn>:<port>/data[/<path>]
   * HTTP/1.1 }
   */
  @Override
  public void doGet(final HttpServletRequest request, final HttpServletResponse response)
      throws IOException {
    final Configuration conf = NameNodeHttpServer.getConfFromContext(getServletContext());
    final UserGroupInformation ugi = getUGI(request, conf);

    try {
      ugi.doAs(
          new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws IOException {
              ClientProtocol nn = createNameNodeProxy();
              final String path = ServletUtil.getDecodedPath(request, "/data");
              final String encodedPath = ServletUtil.getRawPath(request, "/data");
              String delegationToken = request.getParameter(JspHelper.DELEGATION_PARAMETER_NAME);

              HdfsFileStatus info = nn.getFileInfo(path);
              if (info != null && !info.isDir()) {
                response.sendRedirect(
                    createRedirectURL(path, encodedPath, info, ugi, nn, request, delegationToken)
                        .toString());
              } else if (info == null) {
                response.sendError(400, "File not found " + path);
              } else {
                response.sendError(400, path + ": is a directory");
              }
              return null;
            }
          });
    } catch (IOException e) {
      response.sendError(400, e.getMessage());
    } catch (InterruptedException e) {
      response.sendError(400, e.getMessage());
    }
  }
  private void edit(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    String linkIdParam = request.getParameter(PARAM_LINK_ID);
    String title = request.getParameter(PARAM_TITLE);
    String image = request.getParameter(PARAM_IMAGE);
    String url = request.getParameter(PARAM_URL);
    if (linkIdParam == null || !Utils.isNumeric(linkIdParam)) {
      response.sendError(400);
      return;
    }

    try {
      long linkId = Long.valueOf(linkIdParam);
      Link link = linkDao.getLinkById(linkId);
      if (title != null) {
        link.setTitle(title);
      }
      if (image != null) {
        link.setImage(image);
      }
      if (url != null) {
        link.setUrl(url);
      }
      linkDao.updateLink(link);
      response.sendRedirect(LINK_PAGE_URL);
    } catch (NumberFormatException ex) {
      logger.log(Level.SEVERE, ex.getMessage(), ex);
      response.sendError(400, ex.getMessage());
    } catch (DataAccessException ex) {
      logger.log(Level.SEVERE, ex.getMessage(), ex);
      response.sendError(500, ex.getMessage());
    }
  }
Example #13
0
  /*
   * Create a new data source (metadata entry).
   * If there is another one with the same identifier, then - error.
   */
  @RequestMapping(
      value = "/admin/datasources",
      consumes = "application/json",
      method = RequestMethod.PUT)
  public void put(
      @RequestBody @Valid Metadata metadata,
      BindingResult bindingResult,
      HttpServletResponse response)
      throws IOException {
    if (bindingResult != null && bindingResult.hasErrors()) {
      log.error(
          Status.BAD_REQUEST.getErrorCode()
              + "; "
              + Status.BAD_REQUEST.getErrorMsg()
              + "; "
              + errorFromBindingResult(bindingResult));
      response.sendError(
          Status.BAD_REQUEST.getErrorCode(),
          Status.BAD_REQUEST.getErrorMsg() + "; " + errorFromBindingResult(bindingResult));
    }

    Metadata existing = service.metadata().findByIdentifier(metadata.identifier);
    if (existing == null) {
      service.save(metadata);
    } else {
      response.sendError(
          Status.BAD_REQUEST.getErrorCode(),
          "PUT failed: Metadata already exists for pk: "
              + metadata.identifier
              + " (use POST to update instead)");
    }
  }
  protected void doGet(final HttpServletRequest req, final HttpServletResponse res)
      throws ServletException, IOException {

    final String uuid = req.getParameter("uuid");

    if (uuid == null) {
      res.sendError(SC_BAD_REQUEST);
    }

    final AssetItem asset = repository.loadAssetByUUID(uuid);

    if (asset == null) {
      res.sendError(SC_NO_CONTENT);
      return;
    }

    final ServiceConfig serviceConfig =
        ServiceConfigPersistence.getInstance().unmarshal(asset.getContent());

    try {
      res.setContentType("application/x-download");
      res.setHeader("Content-Disposition", "attachment; filename=drools-service.war;");
      buildWar(serviceConfig, repository, res.getOutputStream());
    } catch (Throwable e) {
      ((OutputStream) res.getOutputStream()).close();
      res.sendError(SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } finally {
    }
  }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    if (this.supportHTTP_HEAD) {
      log("GET not supported as HTTP HEAD has been configured");
      resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
      return;
    } else {
      if (yadisResourceInputStream == null) {
        log("ERROR::yadisResourceInputStream is null");
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
      }

      byte[] barr = new byte[1024];
      for (int i = 0; i < barr.length; i++) {
        int b = yadisResourceInputStream.read();
        if (b == -1) break;
        barr[i] = (byte) b;
      }

      resp.setContentType("application/xrds+xml");
      resp.setStatus(HttpServletResponse.SC_OK);
      OutputStream os = resp.getOutputStream();
      os.write(barr);
      os.flush();
      os.close();
    }
  }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String[] parts = req.getRequestURI().split("/");
    String secret = parts[parts.length - 1];
    String sessionId = parts[parts.length - 2];

    PoorSession session = PoorSessionManager.findSessionById(sessionId);
    if (session == null) {
      resp.sendError(404, "Wrong credentials");
      return;
    }

    Query query = new Query("User").addFilter("external-secret", FilterOperator.EQUAL, secret);
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    PreparedQuery preparedQuery = datastore.prepare(query);
    Entity entity = preparedQuery.asSingleEntity();

    if (entity == null) {
      resp.sendError(404, "Wrong credentials");
      return;
    }

    String userId = entity.getProperty("email").toString();
    log.info("Logging in user " + userId + "with session " + sessionId + " and secret " + secret);

    PoorSessionManager.loginSession(session, userId);

    // send success signal to the ext login page
    ChannelService channelService = ChannelServiceFactory.getChannelService();
    channelService.sendMessage(new ChannelMessage(sessionId, "success"));

    resp.getWriter().write("Your browser is now logged in");
  }
  /**
   * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse)
   */
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (!initParams.getEnabled()) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    long startTime = 0;
    if (logger.isTraceEnabled()) {
      startTime = System.currentTimeMillis();
    }

    FileFilterMode.setClient(Client.webdav);

    try {
      // Create the appropriate WebDAV method for the request and execute it
      final WebDAVMethod method = createMethod(request, response);

      if (method == null) {
        if (logger.isErrorEnabled())
          logger.error("WebDAV method not implemented - " + request.getMethod());

        // Return an error status

        response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
        return;
      } else if (method.getRootNodeRef() == null) {
        if (logger.isDebugEnabled()) {
          logger.debug(
              "No root node for request ["
                  + request.getMethod()
                  + " "
                  + request.getRequestURI()
                  + "]");
        }

        // Return an error status
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
      }

      // Execute the WebDAV request, which must take care of its own transaction
      method.execute();
    } catch (Throwable e) {
      ExceptionHandler exHandler = new ExceptionHandler(e, request, response);
      exHandler.handle();
    } finally {
      if (logger.isTraceEnabled()) {
        logger.trace(
            request.getMethod()
                + " took "
                + (System.currentTimeMillis() - startTime)
                + "ms to execute ["
                + request.getRequestURI()
                + "]");
      }

      FileFilterMode.clearClient();
    }
  }
Example #18
0
  /**
   * Does the user sending the HttpServletRequest have the administrator ACLs? If it isn't the case,
   * response will be modified to send an error to the user.
   *
   * @param servletContext
   * @param request
   * @param response used to send the error response if user does not have admin access.
   * @return true if admin-authorized, false otherwise
   * @throws IOException
   */
  static boolean hasAdministratorAccess(
      ServletContext servletContext, HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    Configuration conf = (Configuration) servletContext.getAttribute(CONF_CONTEXT_ATTRIBUTE);
    // If there is no authorization, anybody has administrator access.
    if (!conf.getBoolean(CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, false)) {
      return true;
    }

    String remoteUser = request.getRemoteUser();
    if (remoteUser == null) {
      response.sendError(
          HttpServletResponse.SC_UNAUTHORIZED,
          "Unauthenticated users are not " + "authorized to access this page.");
      return false;
    }

    if (servletContext.getAttribute(ADMINS_ACL) != null
        && !userHasAdministratorAccess(servletContext, remoteUser)) {
      response.sendError(
          HttpServletResponse.SC_UNAUTHORIZED,
          "User " + remoteUser + " is unauthorized to access this page.");
      return false;
    }

    return true;
  }
Example #19
0
  @Override
  public void service(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    String path = req.getPathInfo();

    File file = new File(content, path);
    if (!file.exists()) {
      res.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found " + file.getAbsolutePath());
      return;
    }
    if (!file.isFile()) {
      res.sendError(
          HttpServletResponse.SC_FORBIDDEN, "Directory not accessible " + file.getAbsolutePath());
      return;
    }

    addUri(req);

    InputStream input = new FileInputStream(file);
    try {
      OutputStream output = res.getOutputStream();
      try {
        final byte[] buffer = new byte[10240];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
          output.write(buffer, 0, n);
        }
      } finally {
        output.close();
      }
    } finally {
      input.close();
    }
  }
Example #20
0
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    HttpSession session = request.getSession();
    Project project = (Project) session.getAttribute("project");
    if (project == null) {
      response.sendRedirect("main.jspx?m=login");
    } else {
      String m = request.getParameter("m");
      if ("login".equals(m) || m == null) {
        login(request, response);
      } else if ("addGoal".equals(m)) {
        if ("POST".equals(request.getMethod())) {
          addGoal(request, response);
        } else {
          response.sendError(405);
        }
      } else if ("editGoal".equals(m)) {
        if ("POST".equals(request.getMethod())) {
          editGoal(request, response);
        } else {
          response.sendError(405);
        }
      } else if ("deleteGoal".equals(m)) {
        deleteGoal(request, response);
      } else {
        response.sendError(404, "参数错误!");
      }
    }
  }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    final String actionString = request.getParameter("action");

    if (actionString != null) {
      final ACCESSLEVEL_ACTION action = ACCESSLEVEL_ACTION_MAPPING.get(actionString);
      if (action != null) {
        switch (action) {
          case READALL:
            request.getServletContext().log("READALL");
            this.readAll(request, response);
            break;
          case UPDATE:
            request.getServletContext().log("UPDATE");
            this.update(request, response);
            break;
          case CREATE:
            request.getServletContext().log("CREATE");
            this.create(request, response);
            break;
          case DELETE:
            request.getServletContext().log("DELETE");
            this.delete(request, response);
            break;
          default:
            response.sendError(404);
            break;
        }
      } else {
        response.sendError(404);
      }
    }
  }
Example #22
0
  @Override
  public void doPost(final HttpServletRequest req, final HttpServletResponse rsp)
      throws IOException {
    if (!REQ_TYPE.equals(req.getContentType())) {
      rsp.sendError(SC_UNSUPPORTED_MEDIA_TYPE);
      return;
    }

    final Repository db = getRepository(req);
    try {
      final UploadPack up = uploadPackFactory.create(req, db);
      up.setBiDirectionalPipe(false);
      rsp.setContentType(RSP_TYPE);

      final SmartOutputStream out = new SmartOutputStream(req, rsp);
      up.upload(getInputStream(req), out, null);
      out.close();

    } catch (ServiceNotAuthorizedException e) {
      rsp.reset();
      rsp.sendError(SC_UNAUTHORIZED);
      return;

    } catch (ServiceNotEnabledException e) {
      rsp.reset();
      rsp.sendError(SC_FORBIDDEN);
      return;

    } catch (IOException e) {
      getServletContext().log("Internal error during upload-pack", e);
      rsp.reset();
      rsp.sendError(SC_INTERNAL_SERVER_ERROR);
      return;
    }
  }
  /* goodG2B2() - use goodsource and badsink by reversing statements in if */
  private void goodG2B2(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (IO.static_t) {
      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");
      /* FIX: Use a hardcoded string */
      data = "foo";
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      Logger log_bad = Logger.getLogger("local-logger");

      /* read parameter from cookie */
      Cookie cookieSources[] = request.getCookies();
      if (cookieSources != null) {
        data = cookieSources[0].getValue();
      } else {
        data = null;
      }
    }

    if (data != null) {
      /* POTENTIAL FLAW: script code (e.g. id=<script>alert('xss')</script>) is sent to the client; The built-in J2EE server automatically does some HTML entity encoding.  Therefore, to test this, change response.sendError to response.getWriter().println and remove the 404,
       */
      response.sendError(404, "<br>bad() - Parameter name has value " + data);
    }
  }
Example #24
0
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    CharSequence pathInfo = request.getPathInfo();
    if (pathInfo == null) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No path");
      return;
    }
    Iterator<String> pathComponents = SLASH.split(pathInfo).iterator();
    String userID;
    List<String> itemIDsList;
    try {
      userID = pathComponents.next();
      itemIDsList = Lists.newArrayList();
      while (pathComponents.hasNext()) {
        itemIDsList.add(pathComponents.next());
      }
    } catch (NoSuchElementException nsee) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
      return;
    }

    String[] itemIDs = itemIDsList.toArray(new String[itemIDsList.size()]);
    unescapeSlashHack(itemIDs);

    OryxRecommender recommender = getRecommender();
    try {
      float[] estimates = recommender.estimatePreferences(userID, itemIDs);
      output(request, response, estimates);
    } catch (NotReadyException nre) {
      response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, nre.toString());
    }
  }
Example #25
0
 void handleFileUpload(HttpServletRequest request, HttpServletResponse response)
     throws IOException {
   try {
     ServletFileUpload upload = createUpload();
     FileItemIterator iter = upload.getItemIterator(request);
     while (iter.hasNext()) {
       FileItemStream item = iter.next();
       if (!item.isFormField()) {
         receive(item);
       }
     }
     if (tracker.isEmpty()) {
       String errorMessage = "No file upload data found in request";
       tracker.setException(new Exception(errorMessage));
       tracker.handleFailed();
       response.sendError(HttpServletResponse.SC_BAD_REQUEST, errorMessage);
     } else {
       tracker.handleFinished();
     }
   } catch (Exception exception) {
     Throwable cause = exception.getCause();
     if (cause instanceof FileSizeLimitExceededException) {
       exception = (Exception) cause;
     }
     tracker.setException(exception);
     tracker.handleFailed();
     int errorCode =
         exception instanceof FileSizeLimitExceededException
             ? HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE
             : HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
     response.sendError(errorCode, exception.getMessage());
   }
 }
  public boolean isValid(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    String vsName = request.getParameter("name");

    // Added by Behnaz
    HttpSession session = request.getSession();
    User user = (User) session.getAttribute("user");

    if (vsName == null || vsName.trim().length() == 0) {
      response.sendError(WebConstants.MISSING_VSNAME_ERROR, "The virtual sensor name is missing");
      return false;
    }
    VSensorConfig sensorConfig = Mappings.getVSensorConfig(vsName);
    if (sensorConfig == null) {
      response.sendError(
          WebConstants.ERROR_INVALID_VSNAME, "The specified virtual sensor doesn't exist.");
      return false;
    }

    // Added by Behnaz.
    if (user != null) // meaning, that a login session is active, otherwise we couldn't get there
    if (Main.getContainerConfig().isAcEnabled() == true) {
        if (user.hasReadAccessRight(vsName) == false && user.isAdmin() == false) // ACCESS_DENIED
        {
          response.sendError(
              WebConstants.ACCESS_DENIED, "Access denied to the specified virtual sensor .");
          return false;
        }
      }

    return true;
  }
Example #27
0
 public void doFilter(ServletRequest _request, ServletResponse _response)
     throws IOException, ServletException {
   HttpServletResponse response = (HttpServletResponse) _response;
   HttpServletRequest request = (HttpServletRequest) _request;
   String schunks = getParameter(request, "chunks");
   if (schunks == null) {
     response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No chunks param specified");
     return;
   }
   int chunks = Integer.parseInt(schunks);
   if (chunks < 1) {
     response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid chunks param specified");
     return;
   }
   String schunksize = getParameter(request, "chunksize");
   if (schunksize == null) {
     schunksize = "512";
   }
   int chunksize = Integer.parseInt(schunksize);
   if (chunksize < 1) {
     response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid chunksize param specified");
     return;
   }
   if (buf == null || buf.length < chunksize) {
     buf = new byte[chunksize];
     fillBuf();
   }
   response.setContentType("application/binary");
   ServletOutputStream ostr = response.getOutputStream();
   for (int i = 0; i < chunks; ++i) {
     ostr.write(buf, 0, chunksize);
   }
 }
Example #28
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    final ImageSize size = ImageSize.fromString(req.getParameter(SIZE_PARAM));

    URL url = null;
    try {
      url = new URL(req.getParameter(URL_PARAM));
      Preconditions.checkNotNull(url);
    } catch (Exception e) {
      LOG.error("Invalid image url requested", e);
      resp.sendError(
          HttpServletResponse.SC_BAD_REQUEST, "Please provide a valid image url parameter");
      return;
    }

    try {
      CachedImage img = cache.get(url, size);
      resp.setHeader(HttpHeaders.CONTENT_TYPE, img.getMimeType());
      ByteStreams.copy(img, resp.getOutputStream());
    } catch (IOException e) {
      String errMsg = String.format("No image found for url '%s'", url);
      LOG.error(errMsg, e);
      resp.sendError(HttpServletResponse.SC_NOT_FOUND, errMsg);
    } finally {
      resp.flushBuffer();
    }
  }
  public void service(ServletRequest request, ServletResponse response)
      throws ServletException, IOException {
    HttpServletResponse res = (HttpServletResponse) response;

    if (_message != null) res.sendError(_statusCode, _message);
    else res.sendError(_statusCode);
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    super.doPost(request, response);

    try {
      if (!ServletFileUpload.isMultipartContent(request)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
      }

      ServletFileUpload sfU = new ServletFileUpload();
      FileItemIterator items = sfU.getItemIterator(request);
      while (items.hasNext()) {
        FileItemStream item = items.next();
        if (!item.isFormField()) {
          InputStream stream = item.openStream();
          Document doc = editor.toDocument(stream);
          stream.close();
          handleDocument(request, response, doc);
          return;
        }
      }

      response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No XML uploaded");
    } catch (FileUploadException fuE) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, fuE.getMessage());
    } catch (JDOMException jE) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, jE.getMessage());
    }
  }