use of com.vaadin.flow.server.VaadinServletRequest in project flow by vaadin.
the class AccessAnnotationCheckerTest method hasMethodAccessUsingCurrentRequest.
@Test
public void hasMethodAccessUsingCurrentRequest() throws Exception {
try {
CurrentInstance.set(VaadinRequest.class, new VaadinServletRequest(createRequest(USER_PRINCIPAL), null));
Assert.assertTrue(accessAnnotationChecker.hasAccess(PermitAllClass.class.getMethod("permitAll")));
} finally {
CurrentInstance.clearAll();
}
}
use of com.vaadin.flow.server.VaadinServletRequest in project flow by vaadin.
the class InvalidUrlTest method initUI.
private static void initUI(UI ui, String initialLocation, ArgumentCaptor<Integer> statusCodeCaptor) throws InvalidRouteConfigurationException, ServiceException {
VaadinServletRequest request = Mockito.mock(VaadinServletRequest.class);
VaadinResponse response = Mockito.mock(VaadinResponse.class);
String pathInfo;
if (initialLocation.isEmpty()) {
pathInfo = null;
} else {
Assert.assertFalse(initialLocation.startsWith("/"));
pathInfo = "/" + initialLocation;
}
Mockito.when(request.getPathInfo()).thenReturn(pathInfo);
VaadinService service = new MockVaadinServletService() {
@Override
public VaadinContext getContext() {
return new MockVaadinContext();
}
};
service.setCurrentInstances(request, response);
MockVaadinSession session = new AlwaysLockedVaadinSession(service);
DeploymentConfiguration config = Mockito.mock(DeploymentConfiguration.class);
Mockito.when(config.isProductionMode()).thenReturn(false);
session.lock();
session.setConfiguration(config);
ui.getInternals().setSession(session);
RouteConfiguration routeConfiguration = RouteConfiguration.forRegistry(ui.getRouter().getRegistry());
routeConfiguration.update(() -> {
routeConfiguration.getHandledRegistry().clean();
Arrays.asList(UITest.RootNavigationTarget.class, UITest.FooBarNavigationTarget.class).forEach(routeConfiguration::setAnnotatedRoute);
});
ui.doInit(request, 0);
ui.getRouter().initializeUI(ui, BootstrapHandlerTest.requestToLocation(request));
session.unlock();
if (statusCodeCaptor != null) {
Mockito.verify(response).setStatus(statusCodeCaptor.capture());
}
}
use of com.vaadin.flow.server.VaadinServletRequest in project flow by vaadin.
the class StreamResourceHandler method handleRequest.
/**
* Handle sending for a stream resource request.
*
* @param session
* session for the request
* @param request
* request to handle
* @param response
* response object to which a response can be written.
* @param streamResource
* stream resource that handles data writer
*
* @throws IOException
* if an IO error occurred
*/
public void handleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response, StreamResource streamResource) throws IOException {
StreamResourceWriter writer;
session.lock();
try {
ServletContext context = ((VaadinServletRequest) request).getServletContext();
response.setContentType(streamResource.getContentTypeResolver().apply(streamResource, context));
response.setCacheTime(streamResource.getCacheTime());
streamResource.getHeaders().forEach((name, value) -> response.setHeader(name, value));
writer = streamResource.getWriter();
if (writer == null) {
throw new IOException("Stream resource produces null input stream");
}
} catch (Exception exception) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
throw exception;
} finally {
session.unlock();
}
// don't use here "try resource" syntax sugar because in case there is
// an exception the {@code outputStream} will be closed before "catch"
// block which sets the status code and this code will not have any
// effect being called after closing the stream (see #8740).
OutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
writer.accept(outputStream, session);
} catch (Exception exception) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
throw exception;
} finally {
if (outputStream != null) {
outputStream.close();
}
}
}
use of com.vaadin.flow.server.VaadinServletRequest in project flow by vaadin.
the class PushHandler method handleConnectionLost.
private VaadinSession handleConnectionLost(AtmosphereResourceEvent event) {
if (event == null) {
getLogger().error("Could not get event. This should never happen.");
return null;
}
// We don't want to use callWithUi here, as it assumes there's a client
// request active and does requestStart and requestEnd among other
// things.
AtmosphereResource resource = event.getResource();
if (resource == null) {
return null;
}
// In development mode we may have a live-reload push channel
// that should be closed.
Optional<BrowserLiveReload> liveReload = BrowserLiveReloadAccessor.getLiveReloadFromService(service);
if (isDebugWindowConnection(resource) && liveReload.isPresent() && liveReload.get().isLiveReload(resource)) {
liveReload.get().onDisconnect(resource);
return null;
}
VaadinServletRequest vaadinRequest = new VaadinServletRequest(resource.getRequest(), service);
VaadinSession session = null;
try {
session = service.findVaadinSession(vaadinRequest);
} catch (SessionExpiredException e) {
// This happens at least if the server is restarted without
// preserving the session. After restart the client reconnects, gets
// a session expired notification and then closes the connection and
// ends up here
getLogger().debug("Session expired before push disconnect event was received", e);
return session;
}
UI ui;
session.lock();
try {
VaadinSession.setCurrent(session);
// Sets UI.currentInstance
ui = service.findUI(vaadinRequest);
if (ui == null) {
/*
* UI not found, could be because FF has asynchronously closed
* the websocket connection and Atmosphere has already done
* cleanup of the request attributes.
*
* In that case, we still have a chance of finding the right UI
* by iterating through the UIs in the session looking for one
* using the same AtmosphereResource.
*/
ui = findUiUsingResource(resource, session.getUIs());
if (ui == null) {
getLogger().debug("Could not get UI. This should never happen," + " except when reloading in Firefox and Chrome -" + " see http://dev.vaadin.com/ticket/14251.");
return session;
} else {
getLogger().info("No UI was found based on data in the request," + " but a slower lookup based on the AtmosphereResource succeeded." + " See http://dev.vaadin.com/ticket/14251 for more details.");
}
}
PushMode pushMode = ui.getPushConfiguration().getPushMode();
AtmospherePushConnection pushConnection = getConnectionForUI(ui);
String id = resource.uuid();
if (pushConnection == null) {
getLogger().warn("Could not find push connection to close: {} with transport {}", id, resource.transport());
} else {
if (!pushMode.isEnabled()) {
/*
* The client is expected to close the connection after push
* mode has been set to disabled.
*/
getLogger().debug("Connection closed for resource {}", id);
} else {
/*
* Unexpected cancel, e.g. if the user closes the browser
* tab.
*/
getLogger().debug("Connection unexpectedly closed for resource {} with transport {}", id, resource.transport());
}
pushConnection.connectionLost();
}
} catch (final Exception e) {
callErrorHandler(session, e);
} finally {
try {
session.unlock();
} catch (Exception e) {
getLogger().warn("Error while unlocking session", e);
// can't call ErrorHandler, we (hopefully) don't have a lock
}
}
return session;
}
use of com.vaadin.flow.server.VaadinServletRequest in project flow by vaadin.
the class PushHandler method callWithService.
/**
* Invokes a command with the current service set.
*
* @param resource
* the atmosphere resource for the current request
* @param command
* the command to run
*/
void callWithService(final AtmosphereResource resource, final Consumer<AtmosphereRequest> command) {
AtmosphereRequest req = resource.getRequest();
VaadinServletRequest vaadinRequest = new VaadinServletRequest(req, service);
service.setCurrentInstances(vaadinRequest, null);
try {
command.accept(req);
} finally {
CurrentInstance.clearAll();
}
}
Aggregations