Example usage for org.springframework.web.util UriComponentsBuilder fromHttpRequest

List of usage examples for org.springframework.web.util UriComponentsBuilder fromHttpRequest

Introduction

In this page you can find the example usage for org.springframework.web.util UriComponentsBuilder fromHttpRequest.

Prototype

public static UriComponentsBuilder fromHttpRequest(HttpRequest request) 

Source Link

Document

Create a new UriComponents object from the URI associated with the given HttpRequest while also overlaying with values from the headers "Forwarded" (<a href="https://tools.ietf.org/html/rfc7239">RFC 7239</a>), or "X-Forwarded-Host", "X-Forwarded-Port", and "X-Forwarded-Proto" if "Forwarded" is not found.

Usage

From source file:com.epam.reportportal.auth.OAuthSuccessHandler.java

@Override
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
        throws IOException, ServletException {
    OAuth2Authentication oauth = (OAuth2Authentication) authentication;
    OAuth2AccessToken accessToken = tokenServicesFacade.get().createToken(ReportPortalClient.ui,
            oauth.getName(), oauth.getUserAuthentication(), oauth.getOAuth2Request().getExtensions());

    MultiValueMap<String, String> query = new LinkedMultiValueMap<>();
    query.add("token", accessToken.getValue());
    query.add("token_type", accessToken.getTokenType());
    URI rqUrl = UriComponentsBuilder.fromHttpRequest(new ServletServerHttpRequest(request))
            .replacePath("/ui/authSuccess.html").replaceQueryParams(query).build().toUri();

    eventPublisher.publishEvent(new UiUserSignedInEvent(authentication));

    getRedirectStrategy().sendRedirect(request, response, rqUrl.toString());
}

From source file:io.pivotal.cla.mvc.util.UrlBuilder.java

public String build() {
    String url = UriComponentsBuilder //
            .fromHttpRequest(new ServletServerHttpRequest(request))//
            .replacePath(path) //
            .replaceQueryParams(params) //
            .build() //
            .toUriString(); //

    this.path = null;
    this.params.clear();
    if (url.contains("ngrok.io")) {
        url = url.replaceFirst(":80", "");
        url = url.replaceFirst("http:", "https:");
    }/*from w  w w  . jav  a2s.c  o m*/
    return url;
}

From source file:com.epam.ta.reportportal.ws.controller.impl.UserController.java

@Override
@RequestMapping(method = POST)//  www  .j  av  a2s . c  o m
@ResponseBody
@ResponseStatus(CREATED)
@PreAuthorize(ADMIN_ONLY)
@ApiOperation("Create specified user")
public CreateUserRS createUserByAdmin(@RequestBody @Validated CreateUserRQFull rq, Principal principal,
        HttpServletRequest request) {
    String basicURL = UriComponentsBuilder.fromHttpRequest(new ServletServerHttpRequest(request))
            .replacePath(null).replaceQuery(null).build().toUriString();
    return createUserMessageHandler.createUserByAdmin(rq, principal.getName(), basicURL);
}

From source file:org.awesomeagile.webapp.config.SslRedirectConfig.java

@Bean
public TomcatEmbeddedServletContainerFactory tomcatFactory() {
    return new TomcatEmbeddedServletContainerFactory() {
        @Override/*from   www  .j av a 2  s  .  c o m*/
        protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(Tomcat tomcat) {
            Server server = tomcat.getServer();

            Service service = new StandardService();
            service.setName("ssl-redirect-service");
            Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
            connector.setPort(sslRedirectPort);
            service.addConnector(connector);
            server.addService(service);

            Engine engine = new StandardEngine();
            service.setContainer(engine);

            Host host = new StandardHost();
            host.setName("ssl-redirect-host");
            engine.addChild(host);
            engine.setDefaultHost(host.getName());

            Context context = new StandardContext();
            context.addLifecycleListener(new Tomcat.FixContextListener());
            context.setName("ssl-redirect-context");
            context.setPath("");
            host.addChild(context);

            Wrapper wrapper = context.createWrapper();
            wrapper.setServlet(new HttpServlet() {
                @Override
                public void service(HttpServletRequest req, HttpServletResponse res)
                        throws ServletException, IOException {
                    ServletServerHttpRequest r = new ServletServerHttpRequest(req);
                    UriComponentsBuilder b = UriComponentsBuilder.fromHttpRequest(r);
                    b.scheme("https");
                    b.port(null);
                    res.sendRedirect(b.toUriString());
                }
            });
            wrapper.setName("ssl-redirect-servlet");
            context.addChild(wrapper);
            context.addServletMapping("/", wrapper.getName());

            return super.getTomcatEmbeddedServletContainer(tomcat);
        }
    };
}

From source file:com.epam.ta.reportportal.ws.controller.impl.UserController.java

@Override
@RequestMapping(value = "/bid", method = POST)
@ResponseBody//  w w  w.j a  v  a  2  s.com
@ResponseStatus(CREATED)
@PreAuthorize("hasPermission(#createUserRQ.getDefaultProject(), 'projectLeadPermission')")
@ApiOperation("Register invitation for user who will be created")
public CreateUserBidRS createUserBid(@RequestBody @Validated CreateUserRQ createUserRQ, Principal principal,
        HttpServletRequest request) {
    /*
     * Use Uri components since they are aware of x-forwarded-host headers
     */
    URI rqUrl = UriComponentsBuilder.fromHttpRequest(new ServletServerHttpRequest(request)).replacePath(null)
            .replaceQuery(null).build().toUri();
    return createUserMessageHandler.createUserBid(createUserRQ, principal, rqUrl.toASCIIString());
}

From source file:com.epam.ta.reportportal.ws.controller.impl.UserController.java

@Override
@RequestMapping(value = "/password/restore", method = POST)
@ResponseStatus(OK)/*  w ww . ja v a  2 s.c om*/
@ResponseBody
@ApiOperation("Create a restore password request")
public OperationCompletionRS restorePassword(@RequestBody @Validated RestorePasswordRQ rq,
        HttpServletRequest request) {
    /*
     * Use Uri components since they are aware of x-forwarded-host headers
     */
    String baseUrl = UriComponentsBuilder.fromHttpRequest(new ServletServerHttpRequest(request))
            .replacePath(null).replaceQuery(null).build().toUriString();
    return createUserMessageHandler.createRestorePasswordBid(rq, baseUrl);
}

From source file:com.epam.ta.reportportal.events.handler.LaunchFinishedEventHandler.java

/**
 * Try to send email when it is needed//from w  w w. jav a2s  . c om
 *
 * @param launch       Launch to be used
 * @param project      Project to be used
 * @param emailService Mail Service
 */
void sendEmailRightNow(Launch launch, Project project, EmailService emailService) {
    ProjectEmailConfig projectConfig = project.getConfiguration().getEmailConfig();
    for (EmailSenderCase one : projectConfig.getEmailCases()) {
        Optional<SendCase> option = SendCase.findByName(one.getSendCase());
        boolean successRate = isSuccessRateEnough(launch, option.get());
        boolean matchedNames = isLaunchNameMatched(launch, one);
        boolean matchedTags = isTagsMatched(launch, one);
        List<String> recipients = one.getRecipients();
        if (successRate && matchedNames && matchedTags) {
            String[] recipientsArray = findRecipients(launch.getUserRef(), recipients);
            try {
                /* Update with static Util resources provider */
                String basicURL = UriComponentsBuilder
                        .fromHttpRequest(new ServletServerHttpRequest(currentRequest.get()))
                        .replacePath(String.format("/#%s/launches/all/", project.getName())).build()
                        .toUriString();

                emailService.sendLaunchFinishNotification(recipientsArray, basicURL + launch.getId(), launch,
                        project.getConfiguration());
            } catch (Exception e) {
                LOGGER.error("Unable to send email. Error: \n{}", e);
            }
        }
    }
}

From source file:org.springframework.cloud.gateway.filter.RouteToRequestUrlFilter.java

@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    Route route = getAttribute(exchange, GATEWAY_ROUTE_ATTR, Route.class);
    if (route == null) {
        return chain.filter(exchange);
    }/* w w  w .  ja  v a2  s .  c  om*/
    log.info("RouteToRequestUrlFilter start");
    URI requestUrl = UriComponentsBuilder.fromHttpRequest(exchange.getRequest()).uri(route.getUri()).build(true)
            .toUri();
    exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, requestUrl);
    return chain.filter(exchange);
}

From source file:org.springframework.web.util.WebUtils.java

/**
 * Check the given request origin against a list of allowed origins.
 * A list containing "*" means that all origins are allowed.
 * An empty list means only same origin is allowed.
 * @return true if the request origin is valid, false otherwise
 * @since 4.1.5/*from  w ww  . ja  va 2  s  .com*/
 * @see <a href="https://tools.ietf.org/html/rfc6454">RFC 6454: The Web Origin Concept</a>
 */
public static boolean isValidOrigin(HttpRequest request, Collection<String> allowedOrigins) {
    Assert.notNull(request, "Request must not be null");
    Assert.notNull(allowedOrigins, "Allowed origins must not be null");

    String origin = request.getHeaders().getOrigin();
    if (origin == null || allowedOrigins.contains("*")) {
        return true;
    } else if (allowedOrigins.isEmpty()) {
        UriComponents originComponents;
        try {
            originComponents = UriComponentsBuilder.fromHttpUrl(origin).build();
        } catch (IllegalArgumentException ex) {
            if (logger.isWarnEnabled()) {
                logger.warn("Failed to parse Origin header value [" + origin + "]");
            }
            return false;
        }
        UriComponents requestComponents = UriComponentsBuilder.fromHttpRequest(request).build();
        int originPort = getPort(originComponents);
        int requestPort = getPort(requestComponents);
        return (originComponents.getHost().equals(requestComponents.getHost()) && originPort == requestPort);
    } else {
        return allowedOrigins.contains(origin);
    }
}