Example usage for com.vaadin.server VaadinResponse setContentType

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

Introduction

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

Prototype

public void setContentType(String contentType);

Source Link

Document

Sets the content type of this 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;//from  ww w.j av  a 2 s .  c om
    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 .  j a v a2 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);/*from   www  .  jav a  2  s .c  om*/
        } 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;
}

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);//  www  .j  a v  a2 s  . 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.ejt.vaadin.loginform.LoginForm.java

License:Apache License

private void init() {
    if (initialized) {
        return;//from   w w  w.  j a va  2 s . c  om
    }

    LoginFormState state = getState();
    state.userNameFieldConnector = createUserNameField();
    state.passwordFieldConnector = createPasswordField();
    state.loginButtonConnector = createLoginButton();

    String contextPath = VaadinService.getCurrentRequest().getContextPath();
    if (contextPath.endsWith("/")) {
        contextPath = contextPath.substring(0, contextPath.length() - 1);
    }
    state.contextPath = contextPath;

    VaadinSession.getCurrent().addRequestHandler(new RequestHandler() {
        @Override
        public boolean handleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response)
                throws IOException {
            if (LoginFormConnector.LOGIN_URL.equals(request.getPathInfo())) {
                response.setContentType("text/html; charset=utf-8");
                response.setCacheTime(-1);
                PrintWriter writer = response.getWriter();
                writer.append("<html>Success</html>");
                return true;
            } else {
                return false;
            }
        }
    });

    registerRpc(new LoginFormRpc() {
        @Override
        public void submitCompleted() {
            login();
        }
    });

    initialized = true;

    setContent(createContent(getUserNameField(), getPasswordField(), getLoginButton()));
}

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;
    }/*  ww  w  . j av a  2s .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();
        }
    }
}

From source file:de.uni_tuebingen.qbic.qbicmainportlet.ProxyForGenomeViewerRestApi.java

License:Open Source License

@Override
public boolean handleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response)
        throws IOException {
    if (UI.getCurrent() != null && UI.getCurrent().getPage() != null
            && UI.getCurrent().getPage().getUriFragment() != null) {
        System.out.println(UI.getCurrent().getPage().getUriFragment());
    }/*from   w  w  w.  j a v a 2 s  . c o m*/
    System.out.println("is handling request");
    System.out.println(request.getPathInfo());
    System.out.println(request.getContextPath());
    PortletRequest portletRequest = VaadinPortletService.getCurrentPortletRequest();
    Map<String, String[]> para = request.getParameterMap();
    Set<Entry<String, String[]>> s = para.entrySet();
    Iterator<Entry<String, String[]>> it = s.iterator();
    while (it.hasNext()) {
        Entry<String, String[]> en = it.next();
        System.out.println("Key: " + en.getKey());
        System.out.println("Value:");
        for (int i = 0; i < en.getValue().length; i++) {
            System.out.println(en.getValue()[i]);
        }
        System.out.println("Next");
    }
    Enumeration<String> enu = portletRequest.getParameterNames();
    while (enu.hasMoreElements()) {
        String su = enu.nextElement();
        System.out.println(su + " " + portletRequest.getParameter(su));
    }
    enu = portletRequest.getPropertyNames();
    while (enu.hasMoreElements()) {
        String su = enu.nextElement();
        System.out.println(su + " " + portletRequest.getProperty(su));
    }
    HttpServletRequest httpRequest = PortalUtil.getHttpServletRequest(portletRequest);
    System.out.println(httpRequest.getPathInfo());
    enu = httpRequest.getParameterNames();
    while (enu.hasMoreElements()) {
        String su = enu.nextElement();
        System.out.println(su + " " + httpRequest.getParameter(su));
    }
    System.out.println(httpRequest.getQueryString());
    enu = PortalUtil.getOriginalServletRequest(httpRequest).getParameterNames();
    System.out.println(PortalUtil.getOriginalServletRequest(httpRequest).getPathInfo());
    while (enu.hasMoreElements()) {
        String su = enu.nextElement();
        System.out.println(su + " " + PortalUtil.getOriginalServletRequest(httpRequest).getParameter(su));
    }

    if (!String.valueOf(session).equals(request.getPathInfo())) {
        return false;
    }

    String fileId = request.getParameter("fileId");
    String filepaths = request.getParameter("filepath");
    String removeZeroGenotypes = request.getParameter("removeZeroGenotypes");
    String region = request.getParameter("region");
    String interval = request.getParameter("interval");
    String histogram = request.getParameter("histogram");

    URL u;
    try {
        StringBuilder sb = new StringBuilder();
        sb.append(ConfigurationManagerFactory.getInstance().getGenomeViewerRestApiUrl());
        sb.append(fileId);
        sb.append("/fetch?filepaths=");
        sb.append(filepaths);
        sb.append("&region=");
        sb.append(region);
        if (interval != null) {
            sb.append("&interval=");
            sb.append(interval);
        }
        if (histogram != null) {
            sb.append("&histogram=");
            sb.append(histogram);
        }
        if (removeZeroGenotypes != null) {
            sb.append("");
        }
        u = new URL(sb.toString());
        // u = new
        // URL("http://localhost:7777/vizrest/rest/data/QBAMS001AB.bam/fetch?filepaths=/store/1/0EEF79A2-8140-4FC7-BA67-E51908FE4619/f0/91/36/20141116104428925-3161/original/QBAMS001AB.bam&removeZeroGenotypes=false&region=9:117163200-117164799,9:117164800-117166399,9:117166400-117167999,9:117168000-117169599&interval=1600&h");
        URLConnection urlConnection = u.openConnection();

        urlConnection.setUseCaches(false);
        urlConnection.setDoOutput(false);
        urlConnection.connect();
        InputStream is = urlConnection.getInputStream();
        response.setContentType("application/json");
        response.setHeader("Content-Type", "application/json");
        OutputStream out = response.getOutputStream();
        byte[] buffer = new byte[com.vaadin.server.Constants.DEFAULT_BUFFER_SIZE];
        while (true) {
            int readCount = is.read(buffer);
            if (readCount < 0) {
                break;
            }
            out.write(buffer, 0, readCount);
        }

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return true;
}

From source file:pl.exsio.plupload.PluploadReceiver.java

License:Open Source License

protected void writeResponse(PluploadChunk chunk, VaadinResponse response) throws IOException {
    if (chunk.isLast()) {
        response.getWriter().append("file " + chunk.getName() + " uploaded successfuly");
    } else {//w ww  . ja  v a 2s. c  om
        response.getWriter().append(
                "file chunk " + (chunk.getChunk() + 1) + " of " + chunk.getChunks() + " uploaded successfuly");
    }
    response.setContentType("text/plain");
}