Java Code Examples for com.vaadin.flow.server.VaadinService#getCurrent()

The following examples show how to use com.vaadin.flow.server.VaadinService#getCurrent() . 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: InternalServerError.java    From flow with Apache License 2.0 6 votes vote down vote up
private void reportException(Exception exception, String path,
        String exceptionText) {
    getElement().appendChild(Element.createText(exceptionText));

    VaadinService vaadinService = VaadinService.getCurrent();
    // Check that we have a vaadinService as else we will fail on a NPE and
    // the stacktrace we actually got will disappear and getting a NPE is
    // confusing.
    boolean productionMode = vaadinService != null && vaadinService
            .getDeploymentConfiguration().isProductionMode();

    if (!productionMode) {
        checkLogBinding();
        printStacktrace(exception);
    }

    getLogger().error(
            "There was an exception while trying to navigate to '{}'", path,
            exception);
}
 
Example 2
Source File: RouterLinkTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws NoSuchFieldException, IllegalAccessException,
        InvalidRouteConfigurationException {
    registry = new TestRouteRegistry();
    RouteConfiguration routeConfiguration = RouteConfiguration
            .forRegistry(registry);
    routeConfiguration.update(() -> {
        routeConfiguration.getHandledRegistry().clean();
        Arrays.asList(TestView.class, FooNavigationTarget.class,
                ParameterNavigationTarget.class,
                GreetingNavigationTarget.class)
                .forEach(routeConfiguration::setAnnotatedRoute);
    });
    router = new Router(registry);

    ui = new UI() {
        @Override
        public Router getRouter() {
            return router;
        }
    };

    VaadinService service = VaadinService.getCurrent();
    Mockito.when(service.getRouter()).thenReturn(router);
}
 
Example 3
Source File: ServletDeployer.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Ensures there is a valid instance of {@link ServletContext}.
 */
private void ensureServletContext() {
    if (servletContext == null && VaadinService
            .getCurrent() instanceof VaadinServletService) {
        servletContext = ((VaadinServletService) VaadinService
                .getCurrent()).getServlet().getServletContext();
    } else if (servletContext == null) {
        throw new IllegalStateException(
                "The underlying ServletContext of VaadinServletContext is null and there is no VaadinServletService to obtain it from.");
    }
}
 
Example 4
Source File: InternalErrorView.java    From flow with Apache License 2.0 5 votes vote down vote up
protected void showCriticalNotification(String caption, String message,
        String details, String url) {
    VaadinService service = VaadinService.getCurrent();
    VaadinResponse response = VaadinService.getCurrentResponse();

    try {
        service.writeUncachedStringResponse(response,
                JsonConstants.JSON_CONTENT_TYPE,
                VaadinService.createCriticalNotificationJSON(caption,
                        message, details, url));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 5
Source File: VaadinConnectController.java    From flow with Apache License 2.0 4 votes vote down vote up
/**
 * Captures and processes the Vaadin Connect requests.
 * <p>
 * Matches the endpoint name and a method name with the corresponding Java
 * class and a public method in the class. Extracts parameters from a
 * request body if the Java method requires any and applies in the same
 * order. After the method call, serializes the Java method execution result
 * and sends it back.
 * <p>
 * If an issue occurs during the request processing, an error response is
 * returned instead of the serialized Java method return value.
 *
 * @param endpointName
 *            the name of an endpoint to address the calls to, not case
 *            sensitive
 * @param methodName
 *            the method name to execute on an endpoint, not case sensitive
 * @param body
 *            optional request body, that should be specified if the method
 *            called has parameters
 * @param request
 *            the current request which triggers the endpoint call
 * @return execution result as a JSON string or an error message string
 */
@PostMapping(path = "/{endpoint}/{method}", produces =
        MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<String> serveEndpoint(
        @PathVariable("endpoint") String endpointName,
        @PathVariable("method") String methodName,
        @RequestBody(required = false) ObjectNode body,
        HttpServletRequest request) {
    getLogger().debug("Endpoint: {}, method: {}, request body: {}",
            endpointName, methodName, body);

    VaadinEndpointData vaadinEndpointData = vaadinEndpoints
            .get(endpointName.toLowerCase(Locale.ENGLISH));
    if (vaadinEndpointData == null) {
        getLogger().debug("Endpoint '{}' not found", endpointName);
        return ResponseEntity.notFound().build();
    }

    Method methodToInvoke = vaadinEndpointData
            .getMethod(methodName.toLowerCase(Locale.ENGLISH)).orElse(null);
    if (methodToInvoke == null) {
        getLogger().debug("Method '{}' not found in endpoint '{}'",
                methodName, endpointName);
        return ResponseEntity.notFound().build();
    }

    try {

        // Put a VaadinRequest in the instances object so as the request is
        // available in the end-point method
        VaadinServletService service = (VaadinServletService)VaadinService.getCurrent();
        if (service != null) {
            service.setCurrentInstances(new VaadinServletRequest(request, service), null);
        }

        return invokeVaadinEndpointMethod(endpointName, methodName,
                methodToInvoke, body, vaadinEndpointData, request);
    } catch (JsonProcessingException e) {
        String errorMessage = String.format(
                "Failed to serialize endpoint '%s' method '%s' response. "
                        + "Double check method's return type or specify a custom mapper bean with qualifier '%s'",
                endpointName, methodName,
                VAADIN_ENDPOINT_MAPPER_BEAN_QUALIFIER);
        getLogger().error(errorMessage, e);
        try {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createResponseErrorObject(errorMessage));
        } catch (JsonProcessingException unexpected) {
            throw new IllegalStateException(String.format(
                    "Unexpected: Failed to serialize a plain Java string '%s' into a JSON. "
                            + "Double check the provided mapper's configuration.",
                    errorMessage), unexpected);
        }
    }
}
 
Example 6
Source File: LitTemplate.java    From flow with Apache License 2.0 4 votes vote down vote up
/**
 * Creates the component mapped to a LitElement.
 */
protected LitTemplate() {
    LitTemplateInitializer templateInitializer = new LitTemplateInitializer(this, VaadinService.getCurrent());
    templateInitializer.initChildElements();
}
 
Example 7
Source File: PolymerTemplate.java    From flow with Apache License 2.0 4 votes vote down vote up
/**
 * Creates the component that is responsible for Polymer template
 * functionality.
 */
public PolymerTemplate() {
    this(VaadinService.getCurrent().getInstantiator().getTemplateParser(),
            VaadinService.getCurrent());
}
 
Example 8
Source File: RouterLinkTest.java    From flow with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void noImplicitRouter() {
    VaadinService service = VaadinService.getCurrent();
    Mockito.when(service.getRouter()).thenReturn(null);
    new RouterLink("Show something", TestView.class);
}
 
Example 9
Source File: PolymerTemplate.java    From flow with Apache License 2.0 2 votes vote down vote up
/**
 * Creates the component that is responsible for Polymer template
 * functionality using the provided {@code parser}.
 *
 * @param parser
 *            a template parser
 */
public PolymerTemplate(TemplateParser parser) {
    this(parser, VaadinService.getCurrent());
}