Example usage for com.vaadin.server VaadinResponse setStatus

List of usage examples for com.vaadin.server VaadinResponse setStatus

Introduction

In this page you can find the example usage for com.vaadin.server VaadinResponse setStatus.

Prototype

public void setStatus(int statusCode);

Source Link

Document

Sets the (http) status code for the response.

Usage

From source file:annis.gui.requesthandler.LoginServletRequestHandler.java

License:Apache License

private void doGet(VaadinSession session, VaadinRequest request, VaadinResponse response) {
    response.setContentType("text/html");
    OutputStream out = null;/*w w w.  j  a v a  2 s  . co  m*/
    try {
        out = response.getOutputStream();

        String htmlSource = Resources.toString(LoginServletRequestHandler.class.getResource("login.html"),
                Charsets.UTF_8);

        htmlSource = htmlSource.replaceAll("%usercaption%", "Username")
                .replaceAll("%passwordcaption%", "Password").replaceAll("%title%", "ANNIS Login")
                .replaceAll("%logincaption%", "Login").replaceAll("%or%", "or")
                .replaceAll("%cancelcaption%", "Cancel");

        try (OutputStreamWriter writer = new OutputStreamWriter(out, Charsets.UTF_8)) {
            CharStreams.copy(new StringReader(htmlSource), writer);
            out.flush();
        }
    } catch (IOException ex) {
        log.error(null, ex);
    } catch (Exception ex) {
        log.error(null, ex);
    } finally {
        response.setStatus(200);
        if (out != null) {
            try {
                out.close();
            } catch (IOException ex) {
                log.error("closing OutputStream filed", ex);
            }
        }
    }
}

From source file:annis.gui.requesthandler.LoginServletRequestHandler.java

License:Apache License

private void doPost(VaadinSession session, VaadinRequest request, VaadinResponse response) throws IOException {

    response.setContentType("text/html");

    String username = request.getParameter("annis-login-user");
    String password = request.getParameter("annis-login-password");

    if (username != null && password != null) {
        // forget any old user information
        session.getSession().removeAttribute(AnnisBaseUI.USER_KEY);
        session.getSession().removeAttribute(AnnisBaseUI.USER_LOGIN_ERROR);

        // get the URL for the REST service
        Object annisServiceURLObject = session.getSession().getAttribute(AnnisBaseUI.WEBSERVICEURL_KEY);

        if (annisServiceURLObject == null || !(annisServiceURLObject instanceof String)) {
            log.warn("AnnisWebService.URL was not set as init parameter in web.xml");
        }/*from w w w. jav a  2  s  .c  om*/

        String webserviceURL = (String) annisServiceURLObject;

        try {
            AnnisUser user = new AnnisUser(username, password);
            WebResource res = user.getClient().resource(webserviceURL).path("admin").path("is-authenticated");
            if ("true".equalsIgnoreCase(res.get(String.class))) {
                // everything ok, save this user configuration for re-use
                Helper.setUser(user);
            }
        } catch (ClientHandlerException ex) {
            session.getSession().setAttribute(AnnisBaseUI.USER_LOGIN_ERROR,
                    "Authentification error: " + ex.getMessage());
            response.setStatus(502); // bad gateway
        } catch (LoginDataLostException ex) {
            session.getSession().setAttribute(AnnisBaseUI.USER_LOGIN_ERROR, "Lost password in memory. Sorry.");
            response.setStatus(500); // server error
        } catch (UniformInterfaceException ex) {
            if (ex.getResponse().getStatus() == Response.Status.UNAUTHORIZED.getStatusCode()) {
                session.getSession().setAttribute(AnnisBaseUI.USER_LOGIN_ERROR, "Username or password wrong");
                response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
            } else if (ex.getResponse().getStatus() == Response.Status.FORBIDDEN.getStatusCode()) {
                session.getSession().setAttribute(AnnisBaseUI.USER_LOGIN_ERROR, "Account has expired");
                response.setStatus(Response.Status.FORBIDDEN.getStatusCode()); // Forbidden
            } else {
                log.error(null, ex);
                session.getSession().setAttribute(AnnisBaseUI.USER_LOGIN_ERROR,
                        "Unexpected exception: " + ex.getMessage());
                response.setStatus(500);
            }
        }

        try (OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream(), Charsets.UTF_8)) {
            String html = Resources.toString(LoginServletRequestHandler.class.getResource("closelogin.html"),
                    Charsets.UTF_8);
            CharStreams.copy(new StringReader(html), writer);
        }

    } // end if login attempt

}

From source file:annis.gui.requesthandler.ResourceRequestHandler.java

License:Apache License

@Override
public boolean handleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response)
        throws IOException {
    if (request.getPathInfo() != null && request.getPathInfo().startsWith(prefix)) {
        String uuidString = StringUtils.removeStart(request.getPathInfo(), prefix);
        UUID uuid = UUID.fromString(uuidString);
        IFrameResourceMap map = VaadinSession.getCurrent().getAttribute(IFrameResourceMap.class);
        if (map == null) {
            response.setStatus(404);
        } else {/*from   ww w.  j  av  a 2s .  c  o  m*/
            IFrameResource res = map.get(uuid);
            if (res != null) {
                response.setStatus(200);
                response.setContentType(res.getMimeType());
                response.getOutputStream().write(res.getData());
            }
        }
        return true;
    }
    return false;
}

From source file:annis.gui.SearchUI.java

License:Apache License

@Override
protected void init(VaadinRequest request) {
    super.init(request);

    this.instanceConfig = getInstanceConfig(request);

    getPage().setTitle(instanceConfig.getInstanceDisplayName() + " (ANNIS Corpus Search)");

    queryController = new QueryController(this);

    refresh = new Refresher();
    // deactivate refresher by default
    refresh.setRefreshInterval(-1);/*from w w w  .j  a v a 2s. c o  m*/
    refresh.addListener(queryController);
    addExtension(refresh);

    // always get the resize events directly
    setImmediate(true);

    VerticalLayout mainLayout = new VerticalLayout();
    setContent(mainLayout);

    mainLayout.setSizeFull();
    mainLayout.setMargin(false);

    final ScreenshotMaker screenshot = new ScreenshotMaker(this);
    addExtension(screenshot);

    css = new CSSInject(this);

    HorizontalLayout layoutToolbar = new HorizontalLayout();
    layoutToolbar.setWidth("100%");
    layoutToolbar.setHeight("-1px");

    mainLayout.addComponent(layoutToolbar);
    layoutToolbar.addStyleName("toolbar");
    layoutToolbar.addStyleName("border-layout");

    Button btAboutAnnis = new Button("About ANNIS");
    btAboutAnnis.addStyleName(ChameleonTheme.BUTTON_SMALL);
    btAboutAnnis.setIcon(new ThemeResource("info.gif"));

    btAboutAnnis.addClickListener(new AboutClickListener());

    btBugReport = new Button("Report Bug");
    btBugReport.addStyleName(ChameleonTheme.BUTTON_SMALL);
    btBugReport.setDisableOnClick(true);
    btBugReport.setIcon(new ThemeResource("../runo/icons/16/email.png"));
    btBugReport.addListener(new Button.ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            screenshot.makeScreenshot();
            btBugReport.setCaption("bug report is initialized...");
        }
    });

    String bugmail = (String) VaadinSession.getCurrent().getAttribute("bug-e-mail");
    if (bugmail != null && !bugmail.isEmpty() && !bugmail.startsWith("${")
            && new EmailValidator("").isValid(bugmail)) {
        this.bugEMailAddress = bugmail;
    }
    btBugReport.setVisible(this.bugEMailAddress != null);

    lblUserName = new Label("not logged in");
    lblUserName.setWidth("-1px");
    lblUserName.setHeight("-1px");
    lblUserName.addStyleName("right-aligned-text");

    btLoginLogout = new Button("Login", new Button.ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            if (isLoggedIn()) {
                // logout
                Helper.setUser(null);
                Notification.show("Logged out", Notification.Type.TRAY_NOTIFICATION);
                updateUserInformation();
            } else {
                showLoginWindow();
            }
        }
    });
    btLoginLogout.setSizeUndefined();
    btLoginLogout.setStyleName(ChameleonTheme.BUTTON_SMALL);
    btLoginLogout.setIcon(new ThemeResource("../runo/icons/16/user.png"));

    Button btOpenSource = new Button("Help us to make ANNIS better!");
    btOpenSource.setStyleName(BaseTheme.BUTTON_LINK);
    btOpenSource.addListener(new Button.ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            Window w = new HelpUsWindow();
            w.setCaption("Help us to make ANNIS better!");
            w.setModal(true);
            w.setResizable(true);
            w.setWidth("600px");
            w.setHeight("500px");
            addWindow(w);
            w.center();
        }
    });

    layoutToolbar.addComponent(btAboutAnnis);
    layoutToolbar.addComponent(btBugReport);
    layoutToolbar.addComponent(btOpenSource);
    layoutToolbar.addComponent(lblUserName);
    layoutToolbar.addComponent(btLoginLogout);

    layoutToolbar.setSpacing(true);
    layoutToolbar.setComponentAlignment(btAboutAnnis, Alignment.MIDDLE_LEFT);
    layoutToolbar.setComponentAlignment(btBugReport, Alignment.MIDDLE_LEFT);
    layoutToolbar.setComponentAlignment(btOpenSource, Alignment.MIDDLE_CENTER);
    layoutToolbar.setComponentAlignment(lblUserName, Alignment.MIDDLE_RIGHT);
    layoutToolbar.setComponentAlignment(btLoginLogout, Alignment.MIDDLE_RIGHT);
    layoutToolbar.setExpandRatio(btOpenSource, 1.0f);

    //HorizontalLayout hLayout = new HorizontalLayout();
    final HorizontalSplitPanel hSplit = new HorizontalSplitPanel();
    hSplit.setSizeFull();

    mainLayout.addComponent(hSplit);
    mainLayout.setExpandRatio(hSplit, 1.0f);

    AutoGeneratedQueries autoGenQueries = new AutoGeneratedQueries("example queries", this);

    controlPanel = new ControlPanel(queryController, instanceConfig, autoGenQueries);
    controlPanel.setWidth(100f, Layout.Unit.PERCENTAGE);
    controlPanel.setHeight(100f, Layout.Unit.PERCENTAGE);
    hSplit.setFirstComponent(controlPanel);

    tutorial = new TutorialPanel();
    tutorial.setHeight("99%");

    mainTab = new TabSheet();
    mainTab.setSizeFull();
    mainTab.addTab(autoGenQueries, "example queries");
    mainTab.addTab(tutorial, "Tutorial");

    queryBuilder = new QueryBuilderChooser(queryController, this, instanceConfig);
    mainTab.addTab(queryBuilder, "Query Builder");

    hSplit.setSecondComponent(mainTab);
    hSplit.setSplitPosition(CONTROL_PANEL_WIDTH, Unit.PIXELS);
    hSplit.addSplitterClickListener(new AbstractSplitPanel.SplitterClickListener() {
        @Override
        public void splitterClick(AbstractSplitPanel.SplitterClickEvent event) {
            if (event.isDoubleClick()) {
                if (hSplit.getSplitPosition() == CONTROL_PANEL_WIDTH) {
                    // make small
                    hSplit.setSplitPosition(0.0f, Unit.PIXELS);
                } else {
                    // reset to default width
                    hSplit.setSplitPosition(CONTROL_PANEL_WIDTH, Unit.PIXELS);
                }
            }
        }
    });
    // hLayout.setExpandRatio(mainTab, 1.0f);

    addAction(new ShortcutListener("^Query builder") {
        @Override
        public void handleAction(Object sender, Object target) {
            mainTab.setSelectedTab(queryBuilder);
        }
    });

    addAction(new ShortcutListener("Tutor^eial") {
        @Override
        public void handleAction(Object sender, Object target) {
            mainTab.setSelectedTab(tutorial);
        }
    });

    getPage().addUriFragmentChangedListener(this);

    getSession().addRequestHandler(new RequestHandler() {
        @Override
        public boolean handleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response)
                throws IOException {
            checkCitation(request);

            if (request.getPathInfo() != null && request.getPathInfo().startsWith("/vis-iframe-res/")) {
                String uuidString = StringUtils.removeStart(request.getPathInfo(), "/vis-iframe-res/");
                UUID uuid = UUID.fromString(uuidString);
                IFrameResourceMap map = VaadinSession.getCurrent().getAttribute(IFrameResourceMap.class);
                if (map == null) {
                    response.setStatus(404);
                } else {
                    IFrameResource res = map.get(uuid);
                    if (res != null) {
                        response.setStatus(200);
                        response.setContentType(res.getMimeType());
                        response.getOutputStream().write(res.getData());
                    }
                }
                return true;
            }

            return false;
        }
    });

    getSession().setAttribute(MediaController.class, new MediaControllerImpl());

    getSession().setAttribute(PDFController.class, new PDFControllerImpl());

    loadInstanceFonts();

    checkCitation(request);
    lastQueriedFragment = "";
    evaluateFragment(getPage().getUriFragment());

    updateUserInformation();
}

From source file:com.haulmont.cuba.web.sys.CubaWebJarsHandler.java

License:Apache License

@Override
public boolean handleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response)
        throws IOException {
    String path = request.getPathInfo();

    if (StringUtils.isEmpty(path) || StringUtils.isNotEmpty(path) && !path.startsWith(VAADIN_WEBJARS_PREFIX)) {
        return false;
    }//from   w  ww .  j  a  va  2 s.c om

    log.trace("WebJar resource requested: {}", path.replace(VAADIN_WEBJARS_PREFIX, ""));

    String errorMessage = checkResourcePath(path);
    if (StringUtils.isNotEmpty(errorMessage)) {
        log.warn(errorMessage);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, errorMessage);
        return false;
    }

    URL resourceUrl = getStaticResourceUrl(path);

    if (resourceUrl == null) {
        resourceUrl = getClassPathResourceUrl(path);
    }

    if (resourceUrl == null) {
        String msg = String.format("Requested WebJar resource is not found: %s", path);
        response.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        log.warn(msg);
        return false;
    }

    String resourceName = getResourceName(path);
    String mimeType = servletContext.getMimeType(resourceName);
    response.setContentType(mimeType != null ? mimeType : FileTypesHelper.DEFAULT_MIME_TYPE);

    String cacheControl = "public, max-age=0, must-revalidate";
    int resourceCacheTime = getCacheTime(resourceName);
    if (resourceCacheTime > 0) {
        cacheControl = "max-age=" + String.valueOf(resourceCacheTime);
    }
    response.setHeader("Cache-Control", cacheControl);
    response.setDateHeader("Expires", System.currentTimeMillis() + (resourceCacheTime * 1000));

    InputStream inputStream = null;
    try {
        URLConnection connection = resourceUrl.openConnection();
        long lastModifiedTime = connection.getLastModified();
        // Remove milliseconds to avoid comparison problems (milliseconds
        // are not returned by the browser in the "If-Modified-Since"
        // header).
        lastModifiedTime = lastModifiedTime - lastModifiedTime % 1000;
        response.setDateHeader("Last-Modified", lastModifiedTime);

        if (browserHasNewestVersion(request, lastModifiedTime)) {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return true;
        }

        inputStream = connection.getInputStream();

        copy(inputStream, response.getOutputStream());

        return true;
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
}