Java Code Examples for javax.servlet.http.HttpServletRequest#getLocalPort()

The following examples show how to use javax.servlet.http.HttpServletRequest#getLocalPort() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JNLPSeasonTcpServlet.java    From ramus with GNU General Public License v3.0 6 votes vote down vote up
private void accept(HttpServletRequest req, HttpServletResponse resp) {
    try {
        String localAddr = req.getLocalAddr();
        Properties properties = EngineFactory.getPropeties();
        if (properties.getProperty("hostname") != null) {
            localAddr = properties.getProperty("hostname");
        }
        String path = "http://" + localAddr + ":" + req.getLocalPort()
                + req.getContextPath();
        InputStream is = getClass().getResourceAsStream(
                "/com/ramussoft/jnlp/season-tcp-client.jnlp");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int r;
        while ((r = is.read()) >= 0)
            out.write(r);
        String string = MessageFormat.format(new String(out.toByteArray(),
                "UTF8"), path);
        resp.setContentType("application/x-java-jnlp-file");
        OutputStream o = resp.getOutputStream();
        o.write(string.getBytes("UTF8"));
        o.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
 
Example 2
Source File: HttpUrlConnectionTestServlet.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    final URL url = new URL("http",  req.getLocalAddr(), req.getLocalPort(),req.getServletContext().getContextPath() + "/hello-world.jsp");
    final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.connect();
    final InputStream inputStream = urlConnection.getInputStream();
    resp.setStatus(urlConnection.getResponseCode());
    resp.setContentType(urlConnection.getHeaderField("Content-Type"));
    final byte[] buffer = new byte[1024];
    final ServletOutputStream outputStream = resp.getOutputStream();
    for (int limit = inputStream.read(buffer); limit != -1; limit = inputStream.read(buffer)) {
        outputStream.write(buffer, 0, limit);
    }
    inputStream.close();
    urlConnection.disconnect();
    outputStream.close();
}
 
Example 3
Source File: LocalServerResolver.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
public static String resolve(String url, HttpServletRequest request) {
    if (request == null) {
        return url;
    }
    if (isLocal(url)) {
        try {
            URL urlValue = new URL(url);
            URL updatedUrl = new URL(urlValue.getProtocol(), urlValue.getHost(), request.getLocalPort(),
                                     urlValue.getFile());
            LOG.debug("URL updated to {}", updatedUrl.toString());
            return updatedUrl.toString();
        } catch (MalformedURLException e) {
            LOG.error("Invalid Url '{}': {}", url, e.getMessage());
        }
    }
    return url;
}
 
Example 4
Source File: JNLPLocalServlet.java    From ramus with GNU General Public License v3.0 6 votes vote down vote up
private void accept(HttpServletRequest req, HttpServletResponse resp) {
    try {
        String path = "http://" + req.getLocalAddr() + ":" + req.getLocalPort() + req.getContextPath();
        InputStream is = getClass().getResourceAsStream(
                "/com/ramussoft/jnlp/ramus-local.jnlp");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int r;
        while ((r = is.read()) >= 0)
            out.write(r);
        String string = MessageFormat.format(new String(out.toByteArray(),
                "UTF8"), path);
        resp.setContentType("application/x-java-jnlp-file");
        OutputStream o = resp.getOutputStream();
        o.write(string.getBytes("UTF8"));
        o.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
 
Example 5
Source File: MonitoringServiceImpl.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
@POST
@Path( "stopMonitoring")
@Produces( MediaType.APPLICATION_JSON)
public Response stopMonitoring(
                                @Context HttpServletRequest request,
                                BasePojo basePojo ) {

    final String caller = getCaller(request, basePojo, false);
    ThreadsPerCaller.registerThread(caller);
    try {
        SessionData sd = getSessionData(request, basePojo);

        RestSystemMonitor restSystemMonitor = sd.getSystemMonitor();

        String agent = request.getLocalAddr() + ":" + request.getLocalPort();

        restSystemMonitor.stopMonitoring(agent);
    } catch (Exception e) {
        return Response.serverError().entity(new ErrorPojo(e)).build();
    } finally {
        ThreadsPerCaller.unregisterThread();
    }

    return Response.ok("{\"status\":\"monitoring stopped.\"}").build();
}
 
Example 6
Source File: AdminController.java    From Blog-System with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/main")
public ModelAndView toMain(HttpServletRequest request){
    ModelAndView modelAndView=new ModelAndView("admin/main");
    String clientIp=request.getRemoteAddr();    //获取客户端IP,如:127.0.0.1
    String hostIp=request.getLocalAddr();
    int hostPort=request.getLocalPort();
    Date date = new Date();
    SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm");//设置日期格式
    String dates = df.format(date);
    Admin admin=(Admin) request.getSession().getAttribute("admin");
    AdminLoginLog lastLoginLog=null;
    try {
        if (adminLoginLogService.selectRencent(admin.getId())!=null && adminLoginLogService.selectRencent(admin.getId()).size()==2){
            List<AdminLoginLog> adminLoginLogs=adminLoginLogService.selectRencent(admin.getId());
            lastLoginLog=adminLoginLogs.get(1);
        }

    }catch (Exception e){
        e.printStackTrace();
    }finally {
        int articleCount=articleService.selectCount();
        int commentCount=commentService.countAllNum();
        int loginNum=adminLoginLogService.selectCountByAdminId(admin.getId());
        modelAndView.addObject("clientIp",clientIp);
        modelAndView.addObject("hostIp",hostIp);
        modelAndView.addObject("hostPort",hostPort);
        modelAndView.addObject("date",dates);
        if (lastLoginLog!=null){
            modelAndView.addObject("loginLog",lastLoginLog);
        }
        modelAndView.addObject("articleCount",articleCount);
        modelAndView.addObject("commentCount",commentCount);
        modelAndView.addObject("loginNum",loginNum);
        return modelAndView;
    }


}
 
Example 7
Source File: TestHttpClient.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    final ControllerDTO controller = new ControllerDTO();

    if (req.getLocalPort() == httpConnector.getLocalPort()) {
        controller.setRemoteSiteHttpListeningPort(httpConnector.getLocalPort());
        controller.setSiteToSiteSecure(false);
    } else {
        controller.setRemoteSiteHttpListeningPort(sslConnector.getLocalPort());
        controller.setSiteToSiteSecure(true);
    }

    controller.setId("remote-controller-id");
    controller.setInstanceId("remote-instance-id");
    controller.setName("Remote NiFi Flow");

    assertNotNull("Test case should set <inputPorts> depending on the test scenario.", inputPorts);
    controller.setInputPorts(inputPorts);
    controller.setInputPortCount(inputPorts.size());

    assertNotNull("Test case should set <outputPorts> depending on the test scenario.", outputPorts);
    controller.setOutputPorts(outputPorts);
    controller.setOutputPortCount(outputPorts.size());

    final ControllerEntity controllerEntity = new ControllerEntity();
    controllerEntity.setController(controller);

    respondWithJson(resp, controllerEntity);
}
 
Example 8
Source File: RemoteIpFilter.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
public XForwardedRequest(HttpServletRequest request) {
    super(request);
    this.localPort = request.getLocalPort();
    this.remoteAddr = request.getRemoteAddr();
    this.remoteHost = request.getRemoteHost();
    this.scheme = request.getScheme();
    this.secure = request.isSecure();
    this.serverPort = request.getServerPort();
    
    headers = new HashMap<String, List<String>>();
    for (Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements();) {
        String header = headerNames.nextElement();
        headers.put(header, Collections.list(request.getHeaders(header)));
    }
}
 
Example 9
Source File: RequestData.java    From sample.ferret with Apache License 2.0 5 votes vote down vote up
public RequestData(final HttpServletRequest request) {
    method = request.getMethod();
    uri = request.getRequestURI();
    protocol = request.getProtocol();
    servletPath = request.getServletPath();
    pathInfo = request.getPathInfo();
    pathTranslated = request.getPathTranslated();
    characterEncoding = request.getCharacterEncoding();
    queryString = request.getQueryString();
    contentLength = request.getContentLength();
    contentType = request.getContentType();
    serverName = request.getServerName();
    serverPort = request.getServerPort();
    remoteUser = request.getRemoteUser();
    remoteAddress = request.getRemoteAddr();
    remoteHost = request.getRemoteHost();
    remotePort = request.getRemotePort();
    localAddress = request.getLocalAddr();
    localHost = request.getLocalName();
    localPort = request.getLocalPort();
    authorizationScheme = request.getAuthType();
    preferredClientLocale = request.getLocale();
    allClientLocales = Collections.list(request.getLocales());
    contextPath = request.getContextPath();
    userPrincipal = request.getUserPrincipal();
    requestHeaders = getRequestHeaders(request);
    cookies = getCookies(request.getCookies());
    requestAttributes = getRequestAttributes(request);
}
 
Example 10
Source File: HttpUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static URI toAbsoluteUri(URI u, Message message) {
    HttpServletRequest request =
        (HttpServletRequest)message.get(AbstractHTTPDestination.HTTP_REQUEST);
    boolean absolute = u.isAbsolute();
    StringBuilder uriBuf = new StringBuilder();
    if (request != null && (!absolute || isLocalHostOrAnyIpAddress(u, uriBuf, message))) {
        String serverAndPort = request.getServerName();
        boolean localAddressUsed = false;
        if (absolute) {
            if (ANY_IP_ADDRESS.equals(serverAndPort)) {
                serverAndPort = request.getLocalAddr();
                localAddressUsed = true;
            }
            if (LOCAL_HOST_IP_ADDRESS.equals(serverAndPort)) {
                serverAndPort = "localhost";
                localAddressUsed = true;
            }
        }


        int port = localAddressUsed ? request.getLocalPort() : request.getServerPort();
        if (port != DEFAULT_HTTP_PORT) {
            serverAndPort += ":" + port;
        }
        String base = request.getScheme() + "://" + serverAndPort;
        if (!absolute) {
            u = URI.create(base + u.toString());
        } else {
            int originalPort = u.getPort();
            String hostValue = uriBuf.toString().contains(ANY_IP_ADDRESS_SCHEME)
                ? ANY_IP_ADDRESS : LOCAL_HOST_IP_ADDRESS;
            String replaceValue = originalPort == -1 ? hostValue : hostValue + ":" + originalPort;
            u = URI.create(u.toString().replace(replaceValue, serverAndPort));
        }
    }
    return u;
}
 
Example 11
Source File: MonitoringServiceImpl.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize Monitoring context Must be called before calling any
 * scheduleXYZMonitoring REST method
 */
@POST
@Path( "initializeMonitoring")
@Consumes( MediaType.APPLICATION_JSON)
@Produces( MediaType.APPLICATION_JSON)
public Response initializeMonitoring(
                                      @Context HttpServletRequest request,
                                      BasePojo basePojo ) {

    final String caller = getCaller(request, basePojo, false);
    ThreadsPerCaller.registerThread(caller);

    try {

        SessionData sd = getSessionData(request, basePojo);

        RestSystemMonitor restSystemMonitor = sd.getSystemMonitor();

        String agent = request.getLocalAddr() + ":" + request.getLocalPort();

        restSystemMonitor.initializeMonitoringContext(agent);

        return Response.ok("{\"status\":\"monitoring context initialized.\"}").build();

    } catch (Exception e) {
        return Response.serverError().entity(new ErrorPojo(e)).build();
    } finally {
        ThreadsPerCaller.unregisterThread();
    }

}
 
Example 12
Source File: HttpServletRequestSnapshot.java    From cxf with Apache License 2.0 5 votes vote down vote up
public HttpServletRequestSnapshot(HttpServletRequest request) {
    super(request);
    authType = request.getAuthType();
    characterEncoding = request.getCharacterEncoding();
    contentLength = request.getContentLength();
    contentType = request.getContentType();
    contextPath = request.getContextPath();
    cookies = request.getCookies();
    requestHeaderNames = request.getHeaderNames();
    Enumeration<String> tmp = request.getHeaderNames();
    while (tmp.hasMoreElements()) {
        String key = tmp.nextElement();
        headersMap.put(key, request.getHeaders(key));
    }
    localAddr = request.getLocalAddr();
    local = request.getLocale();
    localName = request.getLocalName();
    localPort = request.getLocalPort();
    method = request.getMethod();
    pathInfo = request.getPathInfo();
    pathTranslated = request.getPathTranslated();
    protocol = request.getProtocol();
    queryString = request.getQueryString();
    remoteAddr = request.getRemoteAddr();
    remoteHost = request.getRemoteHost();
    remotePort = request.getRemotePort();
    remoteUser = request.getRemoteUser();
    requestURI = request.getRequestURI();
    requestURL = request.getRequestURL();
    requestedSessionId = request.getRequestedSessionId();
    schema = request.getScheme();
    serverName = request.getServerName();
    serverPort = request.getServerPort();
    servletPath = request.getServletPath();
    if (request.isRequestedSessionIdValid()) {
        session = request.getSession();
    }
    principal = request.getUserPrincipal();
}
 
Example 13
Source File: ZTSImpl.java    From athenz with Apache License 2.0 5 votes vote down vote up
void validateRequest(HttpServletRequest request, final String principalDomain, final String caller,
                     boolean statusRequest) {
    
    // first validate if we're required process this over TLS only
    
    if (secureRequestsOnly && !request.isSecure()) {
        throw requestError(caller + "request must be over TLS", caller,
                ZTSConsts.ZTS_UNKNOWN_DOMAIN, principalDomain);
    }
    
    // second check if this is a status port so we can only
    // process on status requests
    
    if (statusPort > 0 && statusPort != httpPort && statusPort != httpsPort) {
        
        // non status requests must not take place on the status port
        
        if (!statusRequest && request.getLocalPort() == statusPort) {
            throw requestError("incorrect port number for a non-status request",
                    caller, ZTSConsts.ZTS_UNKNOWN_DOMAIN, principalDomain);
        }
        
        // status requests must not take place on a non-status port
        
        if (statusRequest && request.getLocalPort() != statusPort) {
            throw requestError("incorrect port number for a status request",
                    caller, ZTSConsts.ZTS_UNKNOWN_DOMAIN, principalDomain);
        }
    }
}
 
Example 14
Source File: HueMulator.java    From amazon-echo-ha-bridge with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/{userId}/lights", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<Map<String, String>> getUpnpConfiguration(@PathVariable(value = "userId") String userId, HttpServletRequest request) {
    log.info("hue lights list requested: " + userId + " from " + request.getRemoteAddr() + request.getLocalPort());

    int pageNumber = request.getLocalPort()-portBase;
    Page<DeviceDescriptor> deviceList = repository.findByDeviceType("switch", new PageRequest(pageNumber, 25));
    Map<String, String> deviceResponseMap = new HashMap<>();
    for (DeviceDescriptor device : deviceList) {
        deviceResponseMap.put(device.getId(), device.getName());
    }
    return new ResponseEntity<>(deviceResponseMap, null, HttpStatus.OK);
}
 
Example 15
Source File: ServerInInterceptor.java    From peer-os with Apache License 2.0 4 votes vote down vote up
/**
 * Intercepts a message. Interceptors should NOT invoke handleMessage or handleFault on the next interceptor - the
 * interceptor chain will take care of this.
 */
@Override
public void handleMessage( final Message message )
{
    try
    {
        if ( InterceptorState.SERVER_IN.isActive( message ) )
        {
            //obtain client request
            HttpServletRequest req = ( HttpServletRequest ) message.getExchange().getInMessage()
                                                                   .get( AbstractHTTPDestination.HTTP_REQUEST );

            if ( req.getLocalPort() == Common.DEFAULT_PUBLIC_SECURE_PORT )
            {
                HttpHeaders headers = new HttpHeadersImpl( message.getExchange().getInMessage() );
                String subutaiHeader = headers.getHeaderString( Common.SUBUTAI_HTTP_HEADER );

                String path = req.getRequestURI();

                if ( path.startsWith( "/rest/v1/peer" ) )
                {
                    handlePeerMessage( subutaiHeader, message );
                }
                else
                {
                    final String prefix = "/rest/v1/env";
                    if ( path.startsWith( prefix ) )
                    {
                        String s = path.substring( prefix.length() + 1 );
                        String environmentId = s.substring( 0, s.indexOf( "/" ) );
                        handleEnvironmentMessage( subutaiHeader, environmentId, message );
                    }
                }
            }
        }
    }
    catch ( Exception e )
    {
        throw new Fault( e );
    }
}
 
Example 16
Source File: DataTransferResource.java    From nifi with Apache License 2.0 4 votes vote down vote up
private Peer constructPeer(final HttpServletRequest req, final InputStream inputStream,
                           final OutputStream outputStream, final String portId, final String transactionId) {
    String clientHostName = req.getRemoteHost();
    try {
        // req.getRemoteHost returns IP address, try to resolve hostname to be consistent with RAW protocol.
        final InetAddress clientAddress = InetAddress.getByName(clientHostName);
        clientHostName = clientAddress.getHostName();
    } catch (UnknownHostException e) {
        logger.info("Failed to resolve client hostname {}, due to {}", clientHostName, e.getMessage());
    }
    final int clientPort = req.getRemotePort();

    final PeerDescription peerDescription = new PeerDescription(clientHostName, clientPort, req.isSecure());

    final NiFiUser user = NiFiUserUtils.getNiFiUser();
    final String userDn = user == null ? null : user.getIdentity();
    final HttpServerCommunicationsSession commSession = new HttpServerCommunicationsSession(inputStream, outputStream, transactionId, userDn);

    boolean useCompression = false;
    final String useCompressionStr = req.getHeader(HANDSHAKE_PROPERTY_USE_COMPRESSION);
    if (!isEmpty(useCompressionStr) && Boolean.valueOf(useCompressionStr)) {
        useCompression = true;
    }

    final String requestExpiration = req.getHeader(HANDSHAKE_PROPERTY_REQUEST_EXPIRATION);
    final String batchCount = req.getHeader(HANDSHAKE_PROPERTY_BATCH_COUNT);
    final String batchSize = req.getHeader(HANDSHAKE_PROPERTY_BATCH_SIZE);
    final String batchDuration = req.getHeader(HANDSHAKE_PROPERTY_BATCH_DURATION);

    commSession.putHandshakeParam(HandshakeProperty.PORT_IDENTIFIER, portId);
    commSession.putHandshakeParam(HandshakeProperty.GZIP, String.valueOf(useCompression));

    if (!isEmpty(requestExpiration)) {
        commSession.putHandshakeParam(REQUEST_EXPIRATION_MILLIS, requestExpiration);
    }
    if (!isEmpty(batchCount)) {
        commSession.putHandshakeParam(BATCH_COUNT, batchCount);
    }
    if (!isEmpty(batchSize)) {
        commSession.putHandshakeParam(BATCH_SIZE, batchSize);
    }
    if (!isEmpty(batchDuration)) {
        commSession.putHandshakeParam(BATCH_DURATION, batchDuration);
    }

    if (peerDescription.isSecure()) {
        final NiFiUser nifiUser = NiFiUserUtils.getNiFiUser();
        logger.debug("initiating peer, nifiUser={}", nifiUser);
        commSession.setUserDn(nifiUser.getIdentity());
    }

    // TODO: Followed how SocketRemoteSiteListener define peerUrl and clusterUrl, but it can be more meaningful values, especially for clusterUrl.
    final String peerUrl = "nifi://" + clientHostName + ":" + clientPort;
    final String clusterUrl = "nifi://localhost:" + req.getLocalPort();

    return new Peer(peerDescription, commSession, peerUrl, clusterUrl);
}
 
Example 17
Source File: AgentConfigurationServiceImpl.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Tell the DbEventRequestProcess which run and test must receive the DB
 * messages/data
 */
@POST
@Path( "joinTestcase")
@Consumes( MediaType.APPLICATION_JSON)
@Produces( MediaType.APPLICATION_JSON)
public Response joinTestcase(
                              @Context HttpServletRequest request,
                              JoinTestcasePojo testCaseStatePojo ) {

    final String caller = getCaller(request, testCaseStatePojo, false);
    ThreadsPerCaller.registerThread(caller);

    try {
        SessionData sd = getSessionData(request, testCaseStatePojo);

        RestSystemMonitor restSystemMonitor = sd.getSystemMonitor();

        // cancel all action tasks, that are started on an agent, located on
        // the current caller host.
        // current caller and the agent must have the same IP, in order for
        // the queue to be cancelled
        dbLog.debug("Cancelling all action task on the agent, that were started form the current caller.");
        MultiThreadedActionHandler.cancellAllQueuesFromAgent(ThreadsPerCaller.getCaller());

        // cancel all running system monitoring tasks on the agent
        dbLog.debug("Cancelling all running system monitoring tasks on the agent, that were started form the current caller.");
        String agent = request.getLocalAddr() + ":" + request.getLocalPort();
        restSystemMonitor.stopMonitoring(agent);

        TestCaseState newTestCaseState = new TestCaseState();
        newTestCaseState.setRunId(testCaseStatePojo.getRunId());
        newTestCaseState.setTestcaseId(testCaseStatePojo.getTestcaseId());
        newTestCaseState.setLastExecutedTestcaseId(testCaseStatePojo.getLastExecutedTestcaseId());

        // get the current state on the agent
        TestCaseState currentState = dbLog.getCurrentTestCaseState();
        boolean joinToNewTescase = true;
        if (currentState != null && currentState.isInitialized()) {
            /* This agent is already configured.
             *
             * Now check if the state is the same as the new one, this would mean we are trying to
             * configure this agent for second time.
             * This is normal as we get here when Test Executor or another agent calls this agent for first time.
             *
             * If the state is different, we hit an error which means this agent did not get On Test End event
             * for the previous test case.
             */
            if (!currentState.equals(newTestCaseState)) {

                dbLog.error("This test appears to be aborted by the user on the test executor side, but it kept running on the agent side."
                            + " Now we cancel any further logging from the agent.");
                dbLog.leaveTestCase();
            } else {
                joinToNewTescase = false;

            }
        }

        if (joinToNewTescase) {

            /* previous RestSystemMonitor instance is still in the sessionData for that caller 
             * so we create new RestSystemMonitor for this caller
             * */
            restSystemMonitor = new RestSystemMonitor();
            sd.setSystemMonitor(restSystemMonitor);
            dbLog.joinTestCase(newTestCaseState);
            
            logClassPath(newTestCaseState);

            return Response.ok("{\"status\": \"testcase joined.\"}").build();
        } else {
            
            return Response.ok("{\"status\": \"testcase already joined.\"}").build();
        }

        
    } catch (Exception e) {
        return Response.serverError().entity(new ErrorPojo(e)).build();
    } finally {
        ThreadsPerCaller.unregisterThread();
    }

}
 
Example 18
Source File: ServletRequestCopy.java    From onedev with MIT License 4 votes vote down vote up
public ServletRequestCopy(HttpServletRequest request) {
	this.servletPath = request.getServletPath();
	this.contextPath = request.getContextPath();
	this.pathInfo = request.getPathInfo();
	this.requestUri = request.getRequestURI();
	this.requestURL = request.getRequestURL();
	this.method = request.getMethod();
	this.serverName = request.getServerName();
	this.serverPort = request.getServerPort();
	this.protocol = request.getProtocol();
	this.scheme = request.getScheme();
	
	
	/*
	 * have to comment out below two lines as otherwise web socket will
	 * report UnSupportedOperationException upon connection
	 */
	//this.characterEncoding = request.getCharacterEncoding();
	//this.contentType = request.getContentType();
	//this.requestedSessionId = request.getRequestedSessionId();
	this.characterEncoding = null;
	this.contentType = null;
	this.requestedSessionId = null;
	
	this.locale = request.getLocale();
	this.locales = request.getLocales();
	this.isSecure = request.isSecure();
	this.remoteUser = request.getRemoteUser();
	this.remoteAddr = request.getRemoteAddr();
	this.remoteHost = request.getRemoteHost();
	this.remotePort = request.getRemotePort();
	this.localAddr = request.getLocalAddr();
	this.localName = request.getLocalName();
	this.localPort = request.getLocalPort();
	this.pathTranslated = request.getPathTranslated();
	this.principal = request.getUserPrincipal();

	HttpSession session = request.getSession(true);
	httpSession = new HttpSessionCopy(session);

	String s;
	Enumeration<String> e = request.getHeaderNames();
	while (e != null && e.hasMoreElements()) {
		s = e.nextElement();
		Enumeration<String> headerValues = request.getHeaders(s);
		this.headers.put(s, headerValues);
	}

	e = request.getAttributeNames();
	while (e != null && e.hasMoreElements()) {
		s = e.nextElement();
		attributes.put(s, request.getAttribute(s));
	}

	e = request.getParameterNames();
	while (e != null && e.hasMoreElements()) {
		s = e.nextElement();
		parameters.put(s, request.getParameterValues(s));
	}
}
 
Example 19
Source File: KeycloakSessionServletFilter.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    servletRequest.setCharacterEncoding("UTF-8");

    final HttpServletRequest request = (HttpServletRequest)servletRequest;

    KeycloakSessionFactory sessionFactory = (KeycloakSessionFactory) servletRequest.getServletContext().getAttribute(KeycloakSessionFactory.class.getName());
    KeycloakSession session = sessionFactory.create();
    Resteasy.pushContext(KeycloakSession.class, session);
    ClientConnection connection = new ClientConnection() {
        @Override
        public String getRemoteAddr() {
            return request.getRemoteAddr();
        }

        @Override
        public String getRemoteHost() {
            return request.getRemoteHost();
        }

        @Override
        public int getRemotePort() {
            return request.getRemotePort();
        }

        @Override
        public String getLocalAddr() {
            return request.getLocalAddr();
        }

        @Override
        public int getLocalPort() {
            return request.getLocalPort();
        }
    };
    session.getContext().setConnection(connection);
    Resteasy.pushContext(ClientConnection.class, connection);

    KeycloakTransaction tx = session.getTransactionManager();
    Resteasy.pushContext(KeycloakTransaction.class, tx);
    tx.begin();

    try {
        filterChain.doFilter(servletRequest, servletResponse);
    } finally {
        if (servletRequest.isAsyncStarted()) {
            servletRequest.getAsyncContext().addListener(createAsyncLifeCycleListener(session));
        } else {
            closeSession(session);
        }
    }
}
 
Example 20
Source File: OpenController.java    From java-starthere with MIT License 4 votes vote down vote up
@PostMapping(value = "/createnewuser",
             consumes = {"application/json"},
             produces = {"application/json"})
public ResponseEntity<?> addNewUser(HttpServletRequest httpServletRequest,
                                    @RequestParam(defaultValue = "true")
                                            boolean getaccess,
                                    @Valid
                                    @RequestBody
                                            UserMinimum newminuser) throws URISyntaxException
{
    logger.trace(httpServletRequest.getMethod()
                                   .toUpperCase() + " " + httpServletRequest.getRequestURI() + " accessed");

    // Create the user
    User newuser = new User();

    newuser.setUsername(newminuser.getUsername());
    newuser.setPassword(newminuser.getPassword());
    newuser.setPrimaryemail(newminuser.getPrimaryemail());

    ArrayList<UserRoles> newRoles = new ArrayList<>();
    newRoles.add(new UserRoles(newuser,
                               roleService.findByName("user")));
    newuser.setUserroles(newRoles);

    newuser = userService.save(newuser);

    // set the location header for the newly created resource - to another controller!
    HttpHeaders responseHeaders = new HttpHeaders();
    URI newUserURI = ServletUriComponentsBuilder.fromUriString(httpServletRequest.getServerName() + ":" + httpServletRequest.getLocalPort() + "/users/user/{userId}")
                                                .buildAndExpand(newuser.getUserid())
                                                .toUri();
    responseHeaders.setLocation(newUserURI);

    String theToken = "";
    if (getaccess)
    {
        // return the access token
        RestTemplate restTemplate = new RestTemplate();
        String requestURI = "http://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getLocalPort() + "/login";

        List<MediaType> acceptableMediaTypes = new ArrayList<>();
        acceptableMediaTypes.add(MediaType.APPLICATION_JSON);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.setAccept(acceptableMediaTypes);
        headers.setBasicAuth(System.getenv("OAUTHCLIENTID"),
                             System.getenv("OAUTHCLIENTSECRET"));

        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("grant_type",
                "password");
        map.add("scope",
                "read write trust");
        map.add("username",
                newminuser.getUsername());
        map.add("password",
                newminuser.getPassword());

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map,
                                                                             headers);

        theToken = restTemplate.postForObject(requestURI,
                                              request,
                                              String.class);
    } else
    {
        // nothing;
    }
    return new ResponseEntity<>(theToken,
                                responseHeaders,
                                HttpStatus.CREATED);
}