예제 #1
0
  private static Properties createCGIEnvironment(
      HttpServletRequest sreq, URI root_uri, File canonical_script_file) throws URISyntaxException {

    URI full_request_uri =
        new URI(
            sreq.getScheme(),
            null,
            sreq.getServerName(),
            sreq.getServerPort(),
            sreq.getRequestURI(),
            sreq.getQueryString(),
            null);

    Properties p =
        createCGIEnvironment(
            sreq.getMethod(),
            sreq.getProtocol(),
            full_request_uri,
            new InetSocketAddress(sreq.getLocalAddr(), sreq.getLocalPort()),
            new InetSocketAddress(sreq.getRemoteAddr(), sreq.getRemotePort()),
            sreq.getContextPath() + "/",
            root_uri,
            canonical_script_file);

    // Add request headers

    for (Enumeration e = sreq.getHeaderNames(); e.hasMoreElements(); ) {
      String h = (String) e.nextElement();
      p.setProperty(ESXX.httpToCGI(h), sreq.getHeader(h));
    }

    return p;
  }
예제 #2
0
 private void mockCurrentContextHttpRequest() {
   final HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
   Mockito.when(req.getScheme()).thenReturn("http");
   Mockito.when(req.getServerName()).thenReturn("localhost");
   Mockito.when(req.getLocalPort()).thenReturn(80);
   ServletRequestHolder.setRequest(req);
 }
예제 #3
0
  /**
   * Determine the port number that the client targeted with their {@code request}. If {@code
   * considerHostHeader} is {@code true}, and a HTTP {@code Host} header is present, the value of
   * the port in the header will be used as the port number. If the header is not present, or if
   * {@code considerHostHeader} is {@code false}, the port number will be determined using {@link
   * javax.servlet.http.HttpServletRequest#getRemotePort()} (if {@code considerRemotePort} is {@code
   * true}) followed by {@link javax.servlet.http.HttpServletRequest#getLocalPort()} (if {@code
   * considerLocalPort} is {@code true}).
   *
   * @param request the request
   * @return the port number targeted by the {@code request}
   */
  private int determinePort(HttpServletRequest request) {

    int portNumber = -1;

    // If there is a 'Host' header with the request, and if
    // we are supposed to consider it when determining the port,
    // then use it.

    // This is the best way to go, because the client is indicating
    // what host and port they targeted
    final String hostHeader = request.getHeader(HOST_HEADER);
    if (considerHostHeader && hostHeader != null && hostHeader.trim().length() != 0) {
      String temp = parseHostHeader(hostHeader)[1];
      if (temp != null) {
        portNumber = Integer.parseInt(temp);
      }
    }

    // Either the 'Host' header wasn't considered, or parsing it failed for some reason.

    if (portNumber == -1 && considerRemotePort) {
      portNumber = request.getRemotePort();
    }

    if (portNumber == -1 && considerLocalPort) {
      portNumber = request.getLocalPort();
    }

    return portNumber;
  }
예제 #4
0
 /**
  * Adds status field to a representation of a site configuration.
  *
  * @param siteConfigJson The JSONObject representing a single site configuration.
  * @param user The user making the request.
  * @param resource The original request passed to the decorator.
  */
 private void addStatus(
     HttpServletRequest req, JSONObject siteConfigJson, WebUser user, URI resource)
     throws JSONException {
   String id = siteConfigJson.getString(ProtocolConstants.KEY_ID);
   SiteConfiguration siteConfiguration = SiteConfiguration.fromId(id);
   IHostedSite site =
       HostingActivator.getDefault().getHostingService().get(siteConfiguration, user);
   JSONObject hostingStatus = new JSONObject();
   if (site != null) {
     hostingStatus.put(
         SiteConfigurationConstants.KEY_HOSTING_STATUS_STATUS, "started"); // $NON-NLS-1$
     String portSuffix = ":" + req.getLocalPort(); // $NON-NLS-1$
     // Whatever scheme was used to access the resource, assume it's used for the sites too
     // Hosted site also shares same contextPath
     String hostedUrl =
         resource.getScheme()
             + "://"
             + site.getHost()
             + portSuffix
             + req.getContextPath(); // $NON-NLS-1$
     hostingStatus.put(SiteConfigurationConstants.KEY_HOSTING_STATUS_URL, hostedUrl);
   } else {
     hostingStatus.put(
         SiteConfigurationConstants.KEY_HOSTING_STATUS_STATUS, "stopped"); // $NON-NLS-1$
   }
   siteConfigJson.put(SiteConfigurationConstants.KEY_HOSTING_STATUS, hostingStatus);
 }
예제 #5
0
  /**
   * Sets up the given {@link PostMethod} to send the same content POST data (JSON, XML, etc.) as
   * was sent in the given {@link HttpServletRequest}.
   *
   * @param postMethodProxyRequest The {@link PostMethod} that we are configuring to send a standard
   *     POST request
   * @param httpServletRequest The {@link HttpServletRequest} that contains the POST data to be sent
   *     via the {@link PostMethod}
   */
  private void handleContentPost(
      PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
      throws IOException, ServletException {
    StringBuilder content = new StringBuilder();
    BufferedReader reader = httpServletRequest.getReader();
    for (; ; ) {
      String line = reader.readLine();
      if (line == null) {
        break;
      }
      content.append(line);
    }

    String contentType = httpServletRequest.getContentType();
    String postContent = content.toString();

    // Hack to trickle main server gwt rpc servlet
    // this avoids warnings like the following :
    // "ERROR: The module path requested, /testmodule/, is not in the same web application as this
    // servlet"
    // or
    // "WARNING: Failed to get the SerializationPolicy '29F4EA1240F157649C12466F01F46F60' for module
    // 'http://localhost:8888/testmodule/'"
    //
    // Actually it avoids a NullPointerException in server logging :
    // See http://code.google.com/p/google-web-toolkit/issues/detail?id=3624
    if (contentType.startsWith(this.stringMimeType)) {
      String clientHost = httpServletRequest.getLocalName();
      if (clientHost.equals("127.0.0.1") || clientHost.equals("0:0:0:0:0:0:0:1")) {
        clientHost = "localhost";
      }

      int clientPort = httpServletRequest.getLocalPort();
      String clientUrl = clientHost + ((clientPort != 80) ? ":" + clientPort : "");
      String serverUrl =
          targetHost + ((targetPort != 80) ? ":" + targetPort : "") + stringPrefixPath;

      // Replace more completely if destination server is https :
      if (targetSsl) {
        clientUrl = "http://" + clientUrl;
        serverUrl = "https://" + serverUrl;
      }
      postContent = postContent.replace(clientUrl, serverUrl);
    }

    String encoding = httpServletRequest.getCharacterEncoding();
    LOGGER.trace(
        "POST Content Type: {} Encoding: {} Content: {}",
        new Object[] {contentType, encoding, postContent});
    StringRequestEntity entity;
    try {
      entity = new StringRequestEntity(postContent, contentType, encoding);
    } catch (UnsupportedEncodingException e) {
      throw new ServletException(e);
    }
    // Set the proxy request POST data
    postMethodProxyRequest.setRequestEntity(entity);
  }
예제 #6
0
파일: Utilities.java 프로젝트: andydietz/GW
 public static String getBaseUriFromRequest(HttpServletRequest request) {
   try {
     return new java.net.URL(
             "http", request.getServerName(), request.getLocalPort(), request.getContextPath())
         .toString();
   } catch (MalformedURLException e) {
     // should not happen
     throw new RuntimeException("Unable to get local URL", e);
   }
 }
예제 #7
0
 private AuthToken getAuthTokenForApp(
     HttpServletRequest req, HttpServletResponse resp, boolean doNotSendHttpError)
     throws IOException, ServiceException {
   Config config = Provisioning.getInstance().getConfig();
   int adminPort = config.getIntAttr(Provisioning.A_zimbraAdminPort, 0);
   if (adminPort == req.getLocalPort()) {
     return getAdminAuthTokenFromCookie(req, resp, doNotSendHttpError);
   }
   return getAuthTokenFromCookie(req, resp, doNotSendHttpError);
 }
  @Test
  public void shouldSubmitEndpointWithGivenPaths() throws Exception {
    when(endPointSubmitter.endPointSubmitted()).thenReturn(false);
    when(servletRequest.getContextPath()).thenReturn(CONTEXT_PATH);
    when(servletRequest.getLocalAddr()).thenReturn(LOCAL_ADDR);
    when(servletRequest.getLocalPort()).thenReturn(LOCAL_PORT);

    filter.doFilter(servletRequest, servletResponse, filterChain);

    verify(endPointSubmitter).submit(LOCAL_ADDR, LOCAL_PORT, CONTEXT_PATH);
  }
예제 #9
0
 @RequestMapping(params = "method=showFile")
 public ModelAndView showFile(HttpServletRequest request, HttpServletResponse response)
     throws Exception {
   Map map = RequestUtil.getMap(request);
   System.out.println(
       "url: http://localhost:" + request.getLocalPort() + (String) map.get("file"));
   response.sendRedirect((String) map.get("file"));
   // request.getRequestDispatcher("http://localhost:"+request.getLocalPort()+(String)map.get("file")).
   return null; // new
   // ModelAndView("http://localhost:"+request.getLocalPort()+(String)map.get("file"),
   // map);
 }
예제 #10
0
  private void rewriteApiJs(HttpServletRequest request) throws IOException {
    File file = new File(basePath, "api-js/easyrec.js");

    if (!file.exists()) return;

    BufferedReader reader = null;
    FileWriter writer = null;

    try {
      reader = new BufferedReader(new FileReader(file));

      String firstLine = reader.readLine();
      if (firstLine.startsWith("var easyrecApiUrl")) return;

      File tempFile = File.createTempFile("easyrec-api", "js");
      writer = new FileWriter(tempFile, false);

      String localName = request.getLocalName();
      localName = localName.equals("0.0.0.0") ? "localhost" : localName;
      String webappPath = getServletContext().getContextPath();
      String extendedWebAppPath =
          request.getScheme() + "://" + localName + ":" + request.getLocalPort() + webappPath;

      writer.write("var easyrecApiUrl=\"");
      writer.write(extendedWebAppPath);
      writer.write("/api/1.0/json/\";\n");

      String line = null;

      writer.write(firstLine);
      writer.write('\n');

      while ((line = reader.readLine()) != null) {
        writer.write(line);
        writer.write('\n');
      }

      writer.close();
      reader.close();

      if (!file.delete()) log("Failed to delete old api js file.");

      if (!tempFile.renameTo(file)) log("Failed to move temp file to api js file.");
    } catch (Exception ex) {
      log("Error while rewriting api js.", ex);
    } finally {
      close(reader);
      close(writer);
    }
  }
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   if (req.getRequestURI().endsWith("/index.html")) {
     resp.sendRedirect(
         "http://localhost:"
             + req.getLocalPort()
             + req.getContextPath()
             + req.getServletPath()
             + "/other.html?secret=pipo+molo");
   } else {
     resp.setContentType("text/plain");
     if ("pipo molo".equals(req.getParameter("secret"))) resp.getWriter().println("success");
   }
 }
예제 #12
0
파일: RssFeed.java 프로젝트: hotherve/open
  @GET
  @Produces(MediaType.APPLICATION_ATOM_XML)
  public Feed getFeed() throws URISyntaxException, MalformedURLException {
    log.info("appel feed stories sur baseuri : ");
    if (rq != null) {
      log.info("le request available : " + rq.getContextPath());
    } else {
      return null;
    }
    // gestion de l'adresse
    URL u = new URL("http", rq.getServerName(), rq.getLocalPort(), rq.getContextPath());
    String adresse = u.toExternalForm();
    log.info("uri base : " + u.toExternalForm());

    // gestion des histoires
    Feed feed = new Feed();
    feed.setId(new URI(adresse + "/stories.html"));
    feed.setUpdated(new Date());
    feed.setTitle("Listes histoires");
    feed.getAuthors().add(new Person("Play Writers"));

    // boucle sur chaque histoires
    List<Story> ls = storyList.getStoriesForFeed(20);
    String baseSto = "/stories/story/";
    for (Story s : ls) {
      // construction du lien de l'histoire
      Link link = new Link();
      link.setTitle(s.getStoTitle());
      link.setHref(new URI(adresse + baseSto + s.getStoURL() + ".html"));

      // construction de l'entree
      Entry entry = new Entry();
      entry.setTitle(s.getStoTitle());
      entry.setPublished(s.getStoDate());
      entry.setUpdated(s.getStoDateUpd());

      // ajout du lien dans l'entree
      entry.getLinks().add(link);
      Content content = new Content();
      content.setType(MediaType.TEXT_HTML_TYPE);
      content.setText(s.getStoSyn());
      entry.setContent(content);

      // ajout de l'entree dans le flux de sortie
      feed.getEntries().add(entry);
    }
    return feed;
  }
예제 #13
0
  @RequestMapping(value = "/viewer/theme/createSLD", method = RequestMethod.POST)
  @ResponseBody
  public String createSLD(HttpServletRequest request) {
    try {
      long ticks = 0;
      String data = request.getParameter("data");
      String s = URLDecoder.decode(data, "UTF-8");
      synchronized (s) {
        Date date = new Date();
        ticks = date.getTime();
      }
      String fileName = String.valueOf(ticks) + ".xml";
      String relativePath = request.getContextPath();
      String absolutePath = context.getRealPath(request.getContextPath());
      // System.out.println("------- AbsolutePtah: " + absolutePath);

      int index = absolutePath.lastIndexOf("\\");
      // System.out.println("----index value: " + index);
      absolutePath = absolutePath.substring(0, index) + "\\resources\\temp\\sld\\" + fileName;
      // System.out.println("------- Absolute Path: " + absolutePath);

      // Write the SLD file on the disk
      FileWriter writer = new FileWriter(new File(absolutePath));
      writer.write(s);
      writer.close();

      InetAddress address = InetAddress.getLocalHost();

      int port = request.getLocalPort();
      String url =
          "http://"
              + address.getHostAddress()
              + ":"
              + String.valueOf(port)
              + relativePath
              + "/viewer/resources/temp/sld/"
              + fileName;

      // System.out.println("--- URL Address: " + url);

      return url;
    } catch (Exception e) {
      logger.error(e);
    }
    return null;
  }
예제 #14
0
  /**
   * Verifies what we were doing to the current bundle, it was received for this server?, or this
   * server is trying to send it...., we don't want to retry bundles we received.
   *
   * @param request
   * @param config
   * @return
   */
  private Boolean sendingBundle(
      HttpServletRequest request, PushPublisherConfig config, String bundleId)
      throws DotDataException {

    // Get the local address
    String remoteIP = request.getRemoteHost();
    int port = request.getLocalPort();
    if (!UtilMethods.isSet(remoteIP)) {
      remoteIP = request.getRemoteAddr();
    }

    /*
    Getting the bundle end points in order to compare if this current server it is an end point or not.
    If it is is because we received this bundle as we were a targeted end point server.
    */

    List<Environment> environments =
        APILocator.getEnvironmentAPI().findEnvironmentsByBundleId(bundleId);

    for (Environment environment : environments) {

      List<PublishingEndPoint> endPoints =
          APILocator.getPublisherEndPointAPI()
              .findSendingEndPointsByEnvironment(environment.getId());
      for (PublishingEndPoint endPoint : endPoints) {

        // Getting the end point details
        String endPointAddress = endPoint.getAddress();
        String endPointPort = endPoint.getPort();

        if (endPointAddress.equals(remoteIP) && endPointPort.equals(String.valueOf(port))) {
          return false;
        }
      }
    }

    return true;
  }
예제 #15
0
 public RequestNameParser(HttpServletRequest req) {
   StringBuffer reqPath = new StringBuffer();
   if (req.getPathInfo() != null) {
     reqPath.append(req.getPathInfo());
   } else if (req.getServletPath() != null) {
     reqPath.append(req.getServletPath());
   }
   String _path = reqPath.toString();
   if (_path.indexOf(".") >= 0) {
     String[] pathInfos = _path.split("\\.");
     service = pathInfos[0].substring(1);
     action = pathInfos[1];
   } else {
     service = _path.substring(1);
   }
   if (req.getContextPath() != null
       && req.getContextPath().trim().length() > 0
       && !req.getContextPath().equals("/")) {
     context = req.getServletPath();
     context = context.substring(context.lastIndexOf("/") + 1);
   }
   this.request = req;
   host = req.getLocalName() + ":" + req.getLocalPort();
 }
예제 #16
0
 @Override
 public int getLocalPort() {
   return request.getLocalPort();
 }
예제 #17
0
  @RequestMapping(value = "/viewer/theme/createMarkupSLD", method = RequestMethod.POST)
  @ResponseBody
  public String createMarkupSLD(HttpServletRequest request, HttpServletResponse response) {
    // String principal = getPrincipalFromToken(request, response);
    String principal = request.getUserPrincipal().getName();
    System.out.println("Principal name ----- " + principal);

    String fileName = null;
    boolean appendFlag = false;
    try {
      String data = request.getParameter("data");
      String s = URLDecoder.decode(data, "UTF-8");
      // System.out.println("########### Decoded String: "+ s);

      String relativePath = request.getContextPath();
      String absolutePath = context.getRealPath(request.getContextPath());
      // System.out.println("------- AbsolutePath: " + absolutePath);

      int index = absolutePath.lastIndexOf("\\");
      // System.out.println("----index value: " + index);
      fileName = principal + "_sld.xml";
      absolutePath = absolutePath.substring(0, index) + "\\resources\\temp\\sld\\" + fileName;
      // System.out.println("------- Absolute Path: " + absolutePath);
      // Check if file exists
      File file = new File(absolutePath);

      synchronized (s) {
        if (!file.exists()) {
          // Write the SLD file on the disk
          FileWriter writer = new FileWriter(new File(absolutePath));
          FileWriter writer1 = new FileWriter(absolutePath);
          writer.write(s);
          writer.close();
        } else {
          appendFlag = true;
        }
      }

      if (appendFlag) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        Document document = factory.newDocumentBuilder().parse(file);
        document = parseDOM(document, s);
        synchronized (document) {
          Source source = new DOMSource(document);
          Result result = new StreamResult(file);

          // Write the DOM document to the file
          Transformer xformer = TransformerFactory.newInstance().newTransformer();
          xformer.transform(source, result);
        }
      }

      String address = request.getLocalAddr();
      int port = request.getLocalPort();
      String url =
          "http://"
              + address
              + ":"
              + String.valueOf(port)
              + relativePath
              + "/resources/temp/sld/"
              + fileName;

      // System.out.println("--- URL Address: " + url);

      return url;
    } catch (Exception e) {
      logger.error(e);
    }
    return null;
  }
  /*
   * (non-Javadoc)
   *
   * @see
   * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
   * , javax.servlet.http.HttpServletResponse)
   */
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String request = req.getRequestURI();
    // System.out.println("URI : " + request);
    request = URLDecoder.decode(request, "UTF-8");
    // System.out.println("Decoded URI : " + request);
    String key = request;
    // to work around a bug in the displayator app where the JSON part does
    // not handle relative uris correctly.
    if (key.startsWith("//")) {
      key = key.substring(1);
    }
    if (key.startsWith("/")) {
      key = key.substring(1);
    }
    // if (imaginaryMap.containsKey(key)){//.substring(1))) {
    // key = key.substring(1);
    // }
    // if (key.equals(Ref.sharing_cssRef)) {
    // try {
    // sendRessource(Ref.sharing_cssLocation, resp);
    // return;
    // } catch (Exception ex) {
    // resp.sendError(500,
    // "The server encountered an error while trying to send the content for request ["
    // + request + "]");
    // return;
    // }
    // }

    if (key.equals("")) {
      key = Ref.sharing_htmlRef;
    }
    if (imaginaryMap.containsKey(key)) {
      String val = imaginaryMap.get(key);
      System.out.println("[" + key + "]{" + val + "}");
      try {
        File f = new File(val);
        if (f.exists()) {
          sendFile(f, resp);
          return;
        } else {
          sendString(val, resp);
          return;
        }
      } catch (Exception ex) {
        resp.sendError(
            500,
            "The server encountered an error while trying to send the content for request ["
                + request
                + "]");
        return;
      }
    }
    System.out.println("Could not find [" + key + "] amongst:");
    for (String k : imaginaryMap.keySet()) {
      System.out.println("{" + k + "}");
    }

    resp.sendError(404, "The server could not find or get access to [" + request + "]");
    if (true) {
      System.out.println("Sending 404 for " + request);
      return;
    }
    if (request.equals("/" + Ref.sharing_jsonRef) || request.equals(Ref.URI_jsonRef)) {
      String k = "/" + Ref.sharing_jsonRef;
      // System.out.println("should be returning the Displayable Feed [" +
      // imaginaryMap.get(k).length() + "]");
      try {
        sendString(imaginaryMap.get(k), resp);
        return;
      } catch (Exception ex) {
        resp.sendError(
            500,
            "The server encountered an error while trying to send the content for request ["
                + request
                + "]");
        return;
      }
    }

    if (request.equals("/") || request.equals(Ref.URI_htmlRef)) {
      request = Ref.URI_htmlRef;
      // System.out.println("should be returning the html list [" +
      // imaginaryMap.get(request).length() + "]");
      try {
        String resolvedAddressItem =
            Ref.app_handle_item
                + req.getScheme()
                + "://"
                + req.getLocalAddr()
                + ":"
                + req.getLocalPort();
        String resolvedAddressList =
            Ref.app_handle_list
                + req.getScheme()
                + "://"
                + req.getLocalAddr()
                + ":"
                + req.getLocalPort();
        System.out.println("resolved Address item : " + resolvedAddressItem);
        System.out.println("resolved Address list : " + resolvedAddressList);
        String htmlListing =
            imaginaryMap.get(request).replaceAll(Ref.app_handle_item, resolvedAddressItem);
        htmlListing = htmlListing.replaceAll(Ref.app_handle_list, resolvedAddressList);
        sendString(htmlListing, resp);
        return;
      } catch (Exception ex) {
        resp.sendError(
            500,
            "The server encountered an error while trying to send the requested content for request ["
                + request
                + "]");
        return;
      }
    }

    if (request.startsWith("/")) {
      request = request.substring(1);
    }
    if (null == imaginaryMap
        || !imaginaryMap.containsKey(request)
        || imaginaryMap.get(request) == null) {
      resp.sendError(404, "The server could not find or get access to [" + request + "]");
      System.out.println("404");
      return;
    }

    String string = imaginaryMap.get(request);
    System.out.println("String from the imaginary map : [" + string + "]");
    File f = new File(string);
    if (f.exists()) {
      try {
        sendFile(f, resp);
      } catch (Exception ex) {
        resp.sendError(
            500,
            "The server encountered an error while trying to send the requested file [ "
                + f.getName()
                + "] for request ["
                + request
                + "]");
        return;
      }
    } else {
      resp.sendError(404, "The server could not find or get access to [" + f.getName() + "]");
      return;
    }
  }
  /** 重写父类方法,当登录成功后,重置失败标志 */
  @Override
  protected boolean onLoginSuccess(
      AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response)
      throws Exception {
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;

    SourceUsernamePasswordToken sourceUsernamePasswordToken = (SourceUsernamePasswordToken) token;
    User authAccount =
        userService.findByAuthTypeAndAuthUid(
            User.AuthTypeEnum.SYS, sourceUsernamePasswordToken.getUsername());
    Date now = DateUtils.currentDate();

    // 更新Access Token,并设置半年后过期
    if (StringUtils.isBlank(authAccount.getAccessToken())
        || authAccount.getAccessTokenExpireTime().before(now)) {
      authAccount.setAccessToken(UUID.randomUUID().toString());
      authAccount.setAccessTokenExpireTime(
          new DateTime(DateUtils.currentDate()).plusMonths(6).toDate());
      userService.save(authAccount);
    }

    // 写入登入记录信息
    UserLogonLog userLogonLog = new UserLogonLog();
    userLogonLog.setLogonTime(DateUtils.currentDate());
    userLogonLog.setLogonYearMonthDay(DateUtils.formatDate(userLogonLog.getLogoutTime()));
    userLogonLog.setRemoteAddr(httpServletRequest.getRemoteAddr());
    userLogonLog.setRemoteHost(httpServletRequest.getRemoteHost());
    userLogonLog.setRemotePort(httpServletRequest.getRemotePort());
    userLogonLog.setLocalAddr(httpServletRequest.getLocalAddr());
    userLogonLog.setLocalName(httpServletRequest.getLocalName());
    userLogonLog.setLocalPort(httpServletRequest.getLocalPort());
    userLogonLog.setServerIP(IPAddrFetcher.getGuessUniqueIP());
    userLogonLog.setHttpSessionId(httpServletRequest.getSession().getId());
    userLogonLog.setUserAgent(httpServletRequest.getHeader("User-Agent"));
    userLogonLog.setXforwardFor(IPAddrFetcher.getRemoteIpAddress(httpServletRequest));
    userLogonLog.setAuthType(authAccount.getAuthType());
    userLogonLog.setAuthUid(authAccount.getAuthUid());
    userLogonLog.setAuthGuid(authAccount.getAuthGuid());
    userService.userLogonLog(authAccount, userLogonLog);

    if (isMobileAppAccess(request)) {
      return true;
    } else {
      // 根据不同登录类型转向不同成功界面
      AuthUserDetails authUserDetails = AuthContextHolder.getAuthUserDetails();

      // 判断密码是否已到期,如果是则转向密码修改界面
      Date credentialsExpireTime = authAccount.getCredentialsExpireTime();
      if (credentialsExpireTime != null && credentialsExpireTime.before(DateUtils.currentDate())) {
        httpServletResponse.sendRedirect(
            httpServletRequest.getContextPath()
                + authUserDetails.getUrlPrefixBySource()
                + "/profile/credentials-expire");
        return false;
      }

      // 如果是强制转向指定successUrl则清空SavedRequest
      if (forceSuccessUrl) {
        WebUtils.getAndClearSavedRequest(httpServletRequest);
      }

      return super.onLoginSuccess(token, subject, request, httpServletResponse);
    }
  }
  @Override
  protected void doRequest(
      HttpServletRequest request, HttpServletResponse response, RequestType requestType)
      throws ServletException, IOException {
    RegexHelper MATCH_URL_REGEX = new RegexHelper("/+(.+)", "i");
    RegexHelper TEST_HOST_IN_URL_REGEX = new RegexHelper("^http\\:/{2}([^/]+)/", "i");
    RegexHelper SQUARE_BRACKETS_REGEX = new RegexHelper("\\[\\]", "g");

    logRequest(logger, request, requestType);

    String url = MATCH_URL_REGEX.matchFirst(request.getPathInfo());
    url =
        url.replaceFirst(
            "http:/{1,2}", "http://"); // stupid hack as tomcat 6.0 removes second forward slash
    String queryString = request.getQueryString();

    if (0 < url.length()) {
      if (!TEST_HOST_IN_URL_REGEX.test(url)) { // no host here, will self
        url = "http://localhost:" + String.valueOf(request.getLocalPort()) + "/" + url;
      }
      logger.debug("Will access [{}]", url);

      GetMethod getMethod = new GetMethod(url);

      if (null != queryString) {
        queryString = SQUARE_BRACKETS_REGEX.replace(queryString, "%5B%5D");
        getMethod.setQueryString(queryString);
      }

      Enumeration requestHeaders = request.getHeaderNames();
      while (requestHeaders.hasMoreElements()) {
        String name = (String) requestHeaders.nextElement();
        String value = request.getHeader(name);
        if (null != value) {
          getMethod.setRequestHeader(name, value);
        }
      }

      try {
        httpClient.executeMethod(getMethod);

        int statusCode = getMethod.getStatusCode();
        long contentLength = getMethod.getResponseContentLength();
        logger.debug("Got response [{}], length [{}]", statusCode, contentLength);

        Header[] responseHeaders = getMethod.getResponseHeaders();
        for (Header responseHeader : responseHeaders) {
          String name = responseHeader.getName();
          String value = responseHeader.getValue();
          if (null != name
              && null != value
              && !(name.equals("Server")
                  || name.equals("Date")
                  || name.equals("Transfer-Encoding"))) {
            response.setHeader(responseHeader.getName(), responseHeader.getValue());
          }
        }

        if (200 != statusCode) {
          response.setStatus(statusCode);
        }

        InputStream inStream = getMethod.getResponseBodyAsStream();
        if (null != inStream) {
          BufferedReader in = new BufferedReader(new InputStreamReader(inStream));

          BufferedWriter out =
              new BufferedWriter(new OutputStreamWriter(response.getOutputStream()));

          CharBuffer buffer = CharBuffer.allocate(PROXY_BUFFER_SIZE);
          while (in.read(buffer) >= 0) {
            buffer.flip();
            out.append(buffer);
            buffer.clear();
          }

          in.close();
          out.close();
        }
      } catch (Exception x) {
        if (x.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException")) {
          logger.warn("Client aborted connection");
        } else {
          logger.error("Caught an exception:", x);
          response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, x.getMessage());
        }
      } finally {
        getMethod.releaseConnection();
      }
    }
  }
  /**
   * On submission of the signup form, a user is created and saved to the data store.
   *
   * @see
   *     org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse, java.lang.Object,
   *     org.springframework.validation.BindException)
   */
  @Override
  @Transactional(
      rollbackFor = {
        DuplicateUsernameException.class,
        ObjectNotFoundException.class,
        PeriodNotFoundException.class
      })
  protected synchronized ModelAndView onSubmit(
      HttpServletRequest request,
      HttpServletResponse response,
      Object command,
      BindException errors)
      throws Exception {
    String domain = "http://" + request.getServerName();
    String domainWithPort = domain + ":" + request.getLocalPort();
    String referrer = request.getHeader("referer");
    String registerUrl = "/webapp/student/registerstudent.html";

    if (referrer != null
        && (referrer.contains(domain + registerUrl)
            || referrer.contains(domainWithPort + registerUrl))) {
      StudentAccountForm accountForm = (StudentAccountForm) command;
      StudentUserDetails userDetails = (StudentUserDetails) accountForm.getUserDetails();

      if (accountForm.isNewAccount()) {
        try {
          // get the first name and last name
          String firstName = userDetails.getFirstname();
          String lastName = userDetails.getLastname();

          // check if first name and last name only contain letters
          Pattern pattern = Pattern.compile("[a-zA-Z]*");
          Matcher firstNameMatcher = pattern.matcher(firstName);
          Matcher lastNameMatcher = pattern.matcher(lastName);

          if (!firstNameMatcher.matches()) {
            // first name contains non letter characters
            errors.rejectValue("userDetails.firstname", "error.firstname-illegal-characters");
            return showForm(request, response, errors);
          }

          if (!lastNameMatcher.matches()) {
            // last name contains non letter characters
            errors.rejectValue("userDetails.lastname", "error.lastname-illegal-characters");
            return showForm(request, response, errors);
          }

          User user = userService.createUser(userDetails);
          Projectcode projectcode = new Projectcode(accountForm.getProjectCode());
          studentService.addStudentToRun(user, projectcode);
        } catch (DuplicateUsernameException e) {
          errors.rejectValue(
              "userDetails.username",
              "error.duplicate-username",
              new Object[] {userDetails.getUsername()},
              "Duplicate Username.");
          return showForm(request, response, errors);
        } catch (ObjectNotFoundException e) {
          errors.rejectValue("projectCode", "error.illegal-projectcode");
          return showForm(request, response, errors);
        } catch (PeriodNotFoundException e) {
          errors.rejectValue("projectCode", "error.illegal-projectcode");
          return showForm(request, response, errors);
        }
      } else {
        // userService.updateUser(userDetails);    // TODO HT: add updateUser() to UserService
      }

      ModelAndView modelAndView = new ModelAndView(getSuccessView());

      modelAndView.addObject(USERNAME_KEY, userDetails.getUsername());
      return modelAndView;
    } else {
      response.sendError(HttpServletResponse.SC_FORBIDDEN);
      return null;
    }
  }
예제 #22
0
 public int getLocalPort() {
   return _request.getLocalPort();
 }
예제 #23
0
파일: Start.java 프로젝트: cad188/eecs4413
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // Redirects to /Start if the Startup/YorkRedirect address is attempted
    if (request.getRequestURI().equals("/mCalc0/Startup/YorkRedirect")) {
      response.sendRedirect("/mCalc0/Start");
      System.out.println("Redirect successful\n");
    }

    // Send message to the console
    System.out.println("doGet Hello World\n");
    response.setContentType("plain");
    // Output message in the browser
    response.getWriter().println("doGet Hello World\n");

    double i = extractParameter("interest", request) / 100; // interest in %
    double a = extractParameter("amortization", request); // amortization
    double p = extractParameter("principle", request); // principle
    DecimalFormat truncate = new DecimalFormat("#.##");

    PrintWriter out = response.getWriter();
    out.println(
        "\tThe Networking Layer\n"
            + "Server IP: "
            + request.getLocalAddr()
            + "\n"
            + "Server Port: "
            + request.getLocalPort()
            + "\n"
            + "Client IP: "
            + request.getRemoteAddr()
            + "\n"
            + "Client Port: "
            + request.getRemotePort()
            + "\n"
            + "\n"
            + "\tThe HTTP Layer\n"
            + "Request Protocol: "
            + request.getProtocol()
            + "\n"
            + "Request Method: "
            + request.getMethod()
            + "\n"
            + "Client's query string: ("
            + request.getQueryString()
            + ")\n"
            + "Named Request Parameter: "
            + request.getParameter("name")
            + "\n"
            + "\n\tThe URL\n"
            + "URI: "
            + request.getRequestURI()
            + "\n"
            + "Context Path: "
            + request.getContextPath()
            + "\n"
            + "Servlet/Extra Path: "
            + request.getServletPath()
            + "\n"
            + "Translated Path: "
            + request.getPathTranslated()
            + "\n"
            + "\n\tContext Parameter\n"
            + "name - "
            + request.getSession().getServletContext().getServletContextName()
            + "\n"
            + "value - "
            + request.getSession().getServletContext().getInitParameter("ContextParameter")
            + "\n"
            + "\n\tThe Computation"
            + "\n"
            + "Principle: "
            + p
            + "\n"
            + "Amortization: "
            + a
            + "\n"
            + "Interest: "
            + i
            + "\n"
            + "Monthly payment: $"
            + truncate.format(computePayment(p, i, a))
            + "\n");
    // Error to be caught
    // int x = 0;
    // int y = 20/x;

  }
예제 #24
0
 @Override
 public int getLocalPort() {
   return _outerRequest.getLocalPort();
 }
예제 #25
0
  public TaskHttpServletRequest(HttpServletRequest wrapping, Task task) {
    this.session = wrapping.getSession();
    String location = wrapping.getParameter("url");

    cookies = wrapping.getCookies();
    characterEncoding = wrapping.getCharacterEncoding();
    authType = wrapping.getAuthType();
    headerNames = new Vector<String>();
    headers = new MultiMap();
    for (Enumeration e = wrapping.getHeaderNames(); e.hasMoreElements(); ) {
      String headerName = (String) e.nextElement();
      for (Enumeration f = wrapping.getHeaders(headerName); f.hasMoreElements(); ) {
        String headerValue = (String) f.nextElement();
        headers.add(headerName, headerValue);
      }
    }
    contextPath = wrapping.getContextPath();
    pathInfo = wrapping.getPathInfo();
    pathTranslated = wrapping.getPathTranslated();
    remoteUser = wrapping.getRemoteUser(); // TODO check if needed
    requestedSessionId = wrapping.getRequestedSessionId(); // TODO check if needed
    userPrincipal = wrapping.getUserPrincipal(); // TODO check if needed
    requestedSessionIdFromCookie = wrapping.isRequestedSessionIdFromCookie();
    requestedSessionIdFromURL = wrapping.isRequestedSessionIdFromURL();
    requestedSessionIdValid = wrapping.isRequestedSessionIdValid();
    localAddr = wrapping.getLocalAddr();
    localName = wrapping.getLocalName();
    localPort = wrapping.getLocalPort();
    locale = wrapping.getLocale();
    locales = new Vector<Locale>();
    for (Enumeration e = wrapping.getLocales();
        e.hasMoreElements();
        locales.add((Locale) e.nextElement())) ;
    protocol = wrapping.getProtocol();
    remoteAddr = wrapping.getRemoteAddr();
    remoteHost = wrapping.getRemoteHost();
    remotePort = wrapping.getRemotePort();
    scheme = wrapping.getScheme();
    serverName = wrapping.getServerName();
    serverPort = wrapping.getServerPort();
    secure = wrapping.isSecure();

    // Extract the query (everything after ?)
    int idx = location.indexOf('?');
    query = null;
    if (idx != -1) {
      query = location.substring(idx + 1);
    }

    // Extract the URI (everything before ?)
    uri = location;
    if (idx != -1) {
      uri = uri.substring(0, idx);
    }

    // Servlet path (same as URI?)
    servletPath = uri;

    // Extract parameters
    params = new Hashtable<String, String[]>();
    if (query != null) {
      StringTokenizer t = new StringTokenizer(query, "&");
      while (t.hasMoreTokens()) {
        String token = t.nextToken();
        idx = token.indexOf('=');
        String name = token;
        String val = null;
        if (idx != -1) {
          name = token.substring(0, idx);
          val = token.substring(idx + 1);
        } else {
          val = "";
        }
        String[] vals = params.get(name);
        if (vals == null) {
          vals = new String[] {val};
        } else {
          String[] nvals = new String[vals.length + 1];
          System.arraycopy(vals, 0, nvals, 0, vals.length);
          nvals[vals.length] = val;
          vals = nvals;
        }
        params.put(name, vals);
      }
    }

    // Initialise attributes
    attributes = new Hashtable<String, Object>();

    // Create the URL (the URL with protocol / host / post)
    try {
      URL u = new URL(new URL(wrapping.getRequestURL().toString()), uri);
      url = new StringBuffer(u.toExternalForm());
    } catch (MalformedURLException e) {
    }

    setAttribute(ATTR_TASK, task);
  }
 /**
  * Shuffle specific utils - build string for encoding from URL
  *
  * @param request
  * @return string for encoding
  */
 public static String buildMsgFrom(HttpServletRequest request) {
   return buildMsgFrom(request.getRequestURI(), request.getQueryString(), request.getLocalPort());
 }
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    PrintWriter writer = response.getWriter();
    String message = "Bilinmeyen Bir Browser Kullanýyorsunuz.";

    if (request.getHeader("User-Agent").indexOf("Firefox") != -1)
      message = "Siz Firefox Kullanýcýsýnýz";
    if (request.getHeader("User-Agent").indexOf("MSIE") != -1)
      message = "Siz Microsoft Internet Explorer Kullanýcýsýnýz";
    if (request.getHeader("User-Agent").indexOf("Chrome") != -1)
      message = "Siz Google Chrome Kullanýcýsýnýz";

    writer.println(
        "<!DOCTYPE html 4.0>"
            + "<html>"
            + "<head><title>requestHeadaer</title></head>"
            + "<body bgcolor = \"pink\" style=\"text-align = center;\">"
            + message
            + "<form>"
            + "<table border=2>"
            + "<tr>"
            + "<td>"
            + "<b>RequestCharacterEncoding : </b>"
            + request.getCharacterEncoding()
            + " ---- <b>RequestContentLength : </b>"
            + request.getContentLength()
            + "<p><b>RequestContentType : </b>"
            + request.getContentType()
            + " ---- <b>RequestContextPath : </b>"
            + request.getContextPath()
            + "<p><b>RequestLocalAddress : </b>"
            + request.getLocalAddr()
            + " ---- <b>RequestLocalName : </b>"
            + request.getLocalName()
            + "<p><b>RequestLocalPort : </b>"
            + request.getLocalPort()
            + " ---- <b>RequestMethod : </b>"
            + request.getMethod()
            + "<p><b>RequestPathInfo : </b>"
            + request.getPathInfo()
            + " ---- <b>RequestPathTranslated : </b>"
            + request.getPathTranslated()
            + "<p><b>RequestProtocol : </b>"
            + request.getProtocol()
            + " ---- <b>RequestQueryString : </b>"
            + request.getQueryString()
            + "<p><b>RequestSessionID : </b>"
            + request.getRequestedSessionId()
            + " ---- <b>RequestServerName : </b>"
            + request.getServerName()
            + "<p><b>RequestServerPort : </b>"
            + request.getServerPort()
            + " ---- <b>RequestPath : </b>"
            + request.getServletPath()
            + "<p><b>RequestURL : </b>"
            + request.getRequestURL()
            + " ---- <b>RequestSession : </b>"
            + request.getSession()
            + "<td>"
            + "<table border = 2>");
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
      String headerName = headerNames.nextElement();
      String headerValues = request.getHeader(headerName);
      writer.println("<tr><th>" + headerName + "<td><i>" + headerValues + "</i></tr>");
    }
    writer.println("</table></td></tr></table></body></html>");
  }
예제 #28
0
 /**
  * Helper routine to dump the HTTP servlet request being serviced. Primarily for debugging.
  *
  * @param request - Servlet request (from a POST/GET/PUT/etc.)
  */
 public static void dumpRequest(HttpServletRequest request) {
   if (logger.isDebugEnabled()) {
     // special-case for receiving heartbeat - don't need to repeatedly output all of the
     // information
     // in multiple lines
     if (request.getMethod().equals("GET") && "hb".equals(request.getParameter("type"))) {
       logger.debug("GET type=hb : heartbeat received");
       return;
     }
     logger.debug(
         request.getMethod()
             + ":"
             + request.getRemoteAddr()
             + " "
             + request.getRemoteHost()
             + " "
             + request.getRemotePort());
     logger.debug(
         request.getLocalAddr() + " " + request.getLocalName() + " " + request.getLocalPort());
     Enumeration<String> en = request.getHeaderNames();
     logger.debug("Headers:");
     while (en.hasMoreElements()) {
       String element = en.nextElement();
       Enumeration<String> values = request.getHeaders(element);
       while (values.hasMoreElements()) {
         String value = values.nextElement();
         logger.debug(element + ":" + value);
       }
     }
     logger.debug("Attributes:");
     en = request.getAttributeNames();
     while (en.hasMoreElements()) {
       String element = en.nextElement();
       logger.debug(element + ":" + request.getAttribute(element));
     }
     logger.debug("ContextPath: " + request.getContextPath());
     if (request.getMethod().equals("PUT") || request.getMethod().equals("POST")) {
       // POST and PUT are allowed to have parameters in the content, but in our usage the
       // parameters
       // are always in the Query string.
       // More importantly, there are cases where the POST and PUT content is NOT parameters (e.g.
       // it
       // might contain a Policy file).
       // Unfortunately the request.getParameterMap method reads the content to see if there are
       // any
       // parameters,
       // and once the content is read it cannot be read again.
       // Thus for PUT and POST we must avoid reading the content here so that the main code can
       // read
       // it.
       logger.debug("Query String:" + request.getQueryString());
       try {
         if (request.getInputStream() == null) {
           logger.debug("Content: No content inputStream");
         } else {
           logger.debug("Content available: " + request.getInputStream().available());
         }
       } catch (Exception e) {
         logger.debug(
             "Content: inputStream exception: " + e.getMessage() + ";  (May not be relevant)");
       }
     } else {
       logger.debug("Parameters:");
       Map<String, String[]> params = request.getParameterMap();
       Set<String> keys = params.keySet();
       for (String key : keys) {
         String[] values = params.get(key);
         logger.debug(key + "(" + values.length + "): " + (values.length > 0 ? values[0] : ""));
       }
     }
     logger.debug("Request URL:" + request.getRequestURL());
   }
 }
예제 #29
0
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   resp.sendRedirect(
       "http://" + req.getLocalAddr() + ":" + req.getLocalPort() + "/pong/ui/pong.html");
 }
 @Override
 public InetSocketAddress getLocalAddress() {
   return new InetSocketAddress(_req.getLocalAddr(), _req.getLocalPort());
 }