List of usage examples for com.vaadin.server VaadinSession getCurrent
public static VaadinSession getCurrent()
From source file:annis.gui.controlpanel.ExportPanel.java
License:Apache License
@Override public void buttonClick(ClickEvent event) { // clean up old export if (tmpOutputFile != null && tmpOutputFile.exists()) { if (!tmpOutputFile.delete()) { log.warn("Could not delete {}", tmpOutputFile.getAbsolutePath()); }/*ww w .jav a 2s . c o m*/ } tmpOutputFile = null; String exporterName = (String) cbExporter.getValue(); final Exporter exporter = exporterMap.get(exporterName); if (exporter != null) { if (corpusListPanel.getSelectedCorpora().isEmpty()) { Notification.show("Please select a corpus", Notification.Type.WARNING_MESSAGE); btExport.setEnabled(true); return; } Callable<File> callable = new Callable<File>() { @Override public File call() throws Exception { File currentTmpFile = File.createTempFile("annis-export", ".txt"); currentTmpFile.deleteOnExit(); exporter.convertText(queryPanel.getQuery(), Integer.parseInt((String) cbLeftContext.getValue()), Integer.parseInt((String) cbRightContext.getValue()), corpusListPanel.getSelectedCorpora(), null, (String) txtParameters.getValue(), Helper.getAnnisWebResource().path("query"), new OutputStreamWriter(new FileOutputStream(currentTmpFile), "UTF-8")); return currentTmpFile; } }; FutureTask<File> task = new FutureTask<File>(callable) { @Override protected void done() { VaadinSession session = VaadinSession.getCurrent(); session.lock(); try { btExport.setEnabled(true); progressIndicator.setEnabled(false); try { // copy the result to the class member in order to delete if // when not longer needed tmpOutputFile = get(); } catch (InterruptedException ex) { log.error(null, ex); } catch (ExecutionException ex) { log.error(null, ex); } if (tmpOutputFile == null) { Notification.show("Could not create the Exporter", "The server logs might contain more information about this " + "so you should contact the provider of this ANNIS installation " + "for help.", Notification.Type.ERROR_MESSAGE); } else { if (downloader != null && btDownload.getExtensions().contains(downloader)) { btDownload.removeExtension(downloader); } downloader = new FileDownloader(new FileResource(tmpOutputFile)); downloader.extend(btDownload); btDownload.setEnabled(true); Notification.show("Export finished", "Click on the button right to the export button to actually download the file.", Notification.Type.HUMANIZED_MESSAGE); } } finally { session.unlock(); } } }; progressIndicator.setEnabled(true); ExecutorService singleExecutor = Executors.newSingleThreadExecutor(); singleExecutor.submit(task); } }
From source file:annis.gui.LoginWindow.java
License:Apache License
@Override public void attach() { super.attach(); this.loginURL = (String) VaadinSession.getCurrent().getAttribute(LOGIN_URL_KEY); Resource loginRes;/* w w w. j av a 2 s. c o m*/ if (loginURL == null || loginURL.isEmpty()) { loginRes = new ExternalResource(Helper.getContext() + "/login"); } else { loginRes = new ExternalResource(loginURL); } BrowserFrame frame = new BrowserFrame("login", loginRes); frame.setWidth("100%"); frame.setHeight("100%"); setContent(frame); String loginMaximizedRaw = (String) getSession().getAttribute(LOGIN_MAXIMIZED_KEY); if (Boolean.parseBoolean(loginMaximizedRaw)) { setWindowMode(WindowMode.MAXIMIZED); } }
From source file:annis.gui.MainToolbar.java
License:Apache License
public MainToolbar() { String bugmail = (String) VaadinSession.getCurrent().getAttribute(BUG_MAIL_KEY); if (bugmail != null && !bugmail.isEmpty() && !bugmail.startsWith("${") && new EmailValidator("").isValid(bugmail)) { this.bugEMailAddress = bugmail; } else {//from w w w. j av a2 s. c o m this.bugEMailAddress = null; } UI ui = UI.getCurrent(); if (ui instanceof CommonUI) { ((CommonUI) ui).getSettings().addedLoadedListener(MainToolbar.this); } setWidth("100%"); setHeight("-1px"); addStyleName("toolbar"); addStyleName("border-layout"); btAboutAnnis = new Button("About ANNIS"); btAboutAnnis.addStyleName(ValoTheme.BUTTON_SMALL); btAboutAnnis.setIcon(new ThemeResource("images/annis_16.png")); btAboutAnnis.addClickListener(new AboutClickListener()); btSidebar = new Button(); btSidebar.setDisableOnClick(true); btSidebar.addStyleName(ValoTheme.BUTTON_SMALL); btSidebar.setDescription("Show and hide search sidebar"); btSidebar.setIconAlternateText(btSidebar.getDescription()); btBugReport = new Button("Report Problem"); btBugReport.addStyleName(ValoTheme.BUTTON_SMALL); btBugReport.setDisableOnClick(true); btBugReport.setIcon(FontAwesome.ENVELOPE_O); btBugReport.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { reportBug(); } }); btBugReport.setVisible(this.bugEMailAddress != null); btNavigate = new Button(); btNavigate.setVisible(false); btNavigate.setDisableOnClick(true); btNavigate.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { btNavigate.setEnabled(true); if (navigationTarget != null) { UI.getCurrent().getNavigator().navigateTo(navigationTarget.state); } } }); lblUserName = new Label("not logged in"); lblUserName.setWidth("-1px"); lblUserName.setHeight("-1px"); lblUserName.addStyleName("right-aligned-text"); btLogin = new Button("Login", new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { showLoginWindow(false); } }); btLogout = new Button("Logout", new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { // logout Helper.setUser(null); for (LoginListener l : loginListeners) { l.onLogout(); } Notification.show("Logged out", Notification.Type.TRAY_NOTIFICATION); updateUserInformation(); } }); btLogin.setSizeUndefined(); btLogin.setStyleName(ValoTheme.BUTTON_SMALL); btLogin.setIcon(FontAwesome.USER); btLogout.setSizeUndefined(); btLogout.setStyleName(ValoTheme.BUTTON_SMALL); btLogout.setIcon(FontAwesome.USER); btOpenSource = new Button("Help us to make ANNIS better!"); btOpenSource.setStyleName(BaseTheme.BUTTON_LINK); btOpenSource.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.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"); UI.getCurrent().addWindow(w); w.center(); } }); addComponent(btSidebar); setComponentAlignment(btSidebar, Alignment.MIDDLE_LEFT); addComponent(btAboutAnnis); addComponent(btBugReport); addComponent(btNavigate); addComponent(btOpenSource); setSpacing(true); setComponentAlignment(btAboutAnnis, Alignment.MIDDLE_LEFT); setComponentAlignment(btBugReport, Alignment.MIDDLE_LEFT); setComponentAlignment(btNavigate, Alignment.MIDDLE_LEFT); setComponentAlignment(btOpenSource, Alignment.MIDDLE_CENTER); setExpandRatio(btOpenSource, 1.0f); addLoginButton(); btSidebar.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { btSidebar.setEnabled(true); // decide new state switch (sidebarState) { case VISIBLE: if (event.isCtrlKey()) { sidebarState = SidebarState.AUTO_VISIBLE; } else { sidebarState = SidebarState.HIDDEN; } break; case HIDDEN: if (event.isCtrlKey()) { sidebarState = SidebarState.AUTO_HIDDEN; } else { sidebarState = SidebarState.VISIBLE; } break; case AUTO_VISIBLE: if (event.isCtrlKey()) { sidebarState = SidebarState.VISIBLE; } else { sidebarState = SidebarState.AUTO_HIDDEN; } break; case AUTO_HIDDEN: if (event.isCtrlKey()) { sidebarState = SidebarState.HIDDEN; } else { sidebarState = SidebarState.AUTO_VISIBLE; } break; } updateSidebarState(); } }); screenshotExtension = new ScreenshotMaker(this); JavaScript.getCurrent().addFunction("annis.gui.logincallback", new LoginCloseCallback()); updateSidebarState(); MainToolbar.this.updateUserInformation(); }
From source file:annis.gui.MainToolbar.java
License:Apache License
/** * Adds the login button + login text to the toolbar. This is only happened, * when the gui is not started via the kickstarter. * * <p>/*from w w w. j a v a 2 s . c o m*/ * The Kickstarter overrides the "kickstarterEnvironment" context parameter * and set it to "true", so the gui can detect, that is not necessary to offer * a login button.</p> * * component. */ private void addLoginButton() { VaadinSession session = VaadinSession.getCurrent(); if (session != null) { boolean kickstarter = Helper.isKickstarter(session); if (!kickstarter) { addComponent(lblUserName); setComponentAlignment(lblUserName, Alignment.MIDDLE_RIGHT); addComponent(btLogin); setComponentAlignment(btLogin, Alignment.MIDDLE_RIGHT); } } }
From source file:annis.gui.MainToolbar.java
License:Apache License
private void updateUserInformation() { if (lblUserName == null) { return;//from w w w . ja v a 2s .c o m } if (navigationTarget == NavigationTarget.ADMIN) { // don't show administration link per default btNavigate.setVisible(false); } AnnisUser user = Helper.getUser(); // always close the window if (windowLogin != null) { windowLogin.close(user != null); } if (user == null) { Object loginErrorOject = VaadinSession.getCurrent().getSession().getAttribute(USER_LOGIN_ERROR); if (loginErrorOject != null && loginErrorOject instanceof String) { Notification.show((String) loginErrorOject, Notification.Type.WARNING_MESSAGE); } VaadinSession.getCurrent().getSession().removeAttribute(AnnisBaseUI.USER_LOGIN_ERROR); lblUserName.setValue("not logged in"); if (getComponentIndex(btLogout) > -1) { replaceComponent(btLogout, btLogin); setComponentAlignment(btLogin, Alignment.MIDDLE_RIGHT); } } else { // logged in if (user.getUserName() != null) { Notification.show("Logged in as \"" + user.getUserName() + "\"", Notification.Type.TRAY_NOTIFICATION); lblUserName.setValue("logged in as \"" + user.getUserName() + "\""); } if (getComponentIndex(btLogin) > -1) { replaceComponent(btLogin, btLogout); setComponentAlignment(btLogout, Alignment.MIDDLE_RIGHT); } // do not show the logout button if the user cannot logout using ANNIS btLogout.setVisible(!user.isRemote()); if (navigationTarget == NavigationTarget.ADMIN) { // check in background if display is necessary if (user.getUserName() != null) { Background.run(new CheckIfUserIsAdministratorJob(user.getUserName(), UI.getCurrent())); } } } }
From source file:annis.gui.QueryController.java
License:Apache License
/** * Executes a query.//from www. j a v a 2 s. com * @param replaceOldTab * @param freshQuery If true the offset and the selected matches are reset before executing the query. */ public void executeSearch(boolean replaceOldTab, boolean freshQuery) { if (freshQuery) { getState().getOffset().setValue(0l); getState().getSelectedMatches().setValue(new TreeSet<Long>()); // get the value for the visible segmentation from the configured context Set<String> selectedCorpora = getState().getSelectedCorpora().getValue(); CorpusConfig config = new CorpusConfig(); if (selectedCorpora != null && !selectedCorpora.isEmpty()) { config = ui.getCorpusConfigWithCache(selectedCorpora.iterator().next()); } if (config.containsKey(SearchOptionsPanel.KEY_DEFAULT_BASE_TEXT_SEGMENTATION)) { String configVal = config.getConfig(SearchOptionsPanel.KEY_DEFAULT_BASE_TEXT_SEGMENTATION); if ("".equals(configVal) || "tok".equals(configVal)) { configVal = null; } getState().getVisibleBaseText().setValue(configVal); } else { getState().getVisibleBaseText().setValue(getState().getContextSegmentation().getValue()); } } // construct a query from the current properties DisplayedResultQuery displayedQuery = getSearchQuery(); searchView.getControlPanel().getQueryPanel().setStatus("Searching..."); cancelSearch(); // cleanup resources VaadinSession session = VaadinSession.getCurrent(); session.setAttribute(IFrameResourceMap.class, new IFrameResourceMap()); if (session.getAttribute(MediaController.class) != null) { session.getAttribute(MediaController.class).clearMediaPlayers(); } searchView.updateFragment(displayedQuery); if (displayedQuery.getCorpora() == null || displayedQuery.getCorpora().isEmpty()) { Notification.show("Please select a corpus", Notification.Type.WARNING_MESSAGE); return; } if ("".equals(displayedQuery.getQuery())) { Notification.show("Empty query", Notification.Type.WARNING_MESSAGE); return; } addHistoryEntry(displayedQuery); AsyncWebResource res = Helper.getAnnisAsyncWebResource(); // // begin execute match fetching // ResultViewPanel oldPanel = searchView.getLastSelectedResultView(); if (replaceOldTab) { // remove old panel from view searchView.closeTab(oldPanel); } ResultViewPanel newResultView = new ResultViewPanel(ui, ui, ui.getInstanceConfig(), displayedQuery); newResultView.getPaging() .addCallback(new SpecificPagingCallback(ui, searchView, newResultView, displayedQuery)); TabSheet.Tab newTab; List<ResultViewPanel> existingResultPanels = getResultPanels(); String caption = existingResultPanels.isEmpty() ? "Query Result" : "Query Result #" + (existingResultPanels.size() + 1); newTab = searchView.getMainTab().addTab(newResultView, caption); newTab.setClosable(true); newTab.setIcon(FontAwesome.SEARCH); searchView.getMainTab().setSelectedTab(newResultView); searchView.notifiyQueryStarted(); Background.run(new ResultFetchJob(displayedQuery, newResultView, ui)); // // end execute match fetching // // // begin execute count // // start count query searchView.getControlPanel().getQueryPanel().setCountIndicatorEnabled(true); AsyncWebResource countRes = res.path("query").path("search").path("count") .queryParam("q", Helper.encodeJersey(displayedQuery.getQuery())) .queryParam("corpora", Helper.encodeJersey(StringUtils.join(displayedQuery.getCorpora(), ","))); Future<MatchAndDocumentCount> futureCount = countRes.get(MatchAndDocumentCount.class); state.getExecutedTasks().put(QueryUIState.QueryType.COUNT, futureCount); Background.run(new CountCallback(newResultView, displayedQuery.getLimit(), ui)); // // end execute count // }
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.j a v a 2 s. c o m } 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.resultview.ResultSetPanel.java
License:Apache License
public ResultSetPanel(List<Match> matches, PluginSystem ps, InstanceConfig instanceConfig, int contextLeft, int contextRight, String segmentationName, ResultViewPanel parent, int firstMatchOffset) { this.ps = ps; this.segmentationName = segmentationName; this.contextLeft = contextLeft; this.contextRight = contextRight; this.parent = parent; this.matches = Collections.synchronizedList(matches); this.firstMatchOffset = firstMatchOffset; this.instanceConfig = instanceConfig; resultPanelList = Collections.synchronizedList(new LinkedList<SingleResultPanel>()); cacheResolver = Collections//from w w w .j a v a 2s.com .synchronizedMap(new HashMap<HashSet<SingleResolverRequest>, List<ResolverEntry>>()); setSizeFull(); layout = new CssLayout(); setContent(layout); layout.addStyleName("result-view-css"); addStyleName(ChameleonTheme.PANEL_BORDERLESS); addStyleName("result-view"); indicatorLayout = new VerticalLayout(); indicator = new ProgressIndicator(); indicator.setIndeterminate(false); indicator.setValue(0f); indicator.setPollingInterval(250); indicator.setSizeUndefined(); indicatorLayout.addComponent(indicator); indicatorLayout.setWidth("100%"); indicatorLayout.setHeight("-1px"); indicatorLayout.setComponentAlignment(indicator, Alignment.TOP_CENTER); indicatorLayout.setVisible(true); layout.addComponent(indicatorLayout); // enable indicator in order to get refresh GUI regulary indicator.setEnabled(true); ExecutorService singleExecutor = Executors.newSingleThreadExecutor(); Callable<Boolean> run = new AllResultsFetcher(); FutureTask<Boolean> task = new FutureTask<Boolean>(run) { @Override protected void done() { VaadinSession session = VaadinSession.getCurrent(); session.lock(); try { indicator.setEnabled(false); indicator.setVisible(false); indicatorLayout.setVisible(false); } finally { session.unlock(); } } }; singleExecutor.submit(task); }
From source file:annis.gui.resultview.VisualizerPanel.java
License:Apache License
private VisualizerInput createInput() { VisualizerInput input = new VisualizerInput(); input.setAnnisWebServiceURL((String) VaadinSession.getCurrent().getAttribute("AnnisWebService.URL")); input.setContextPath(Helper.getContext()); input.setDotPath((String) VaadinSession.getCurrent().getAttribute("DotPath")); input.setId(resultID);/* ww w . j a va 2 s . c o m*/ input.setMarkableExactMap(markersExact); input.setMarkableMap(markersCovered); input.setMarkedAndCovered(markedAndCovered); input.setResult(result); input.setVisibleTokenAnnos(visibleTokenAnnos); input.setSegmentationName(segmentationName); if (instanceConfig != null && instanceConfig.getFont() != null) { input.setFont(instanceConfig.getFont()); } if (entry != null) { input.setMappings(entry.getMappings()); input.setNamespace(entry.getNamespace()); String template = Helper.getContext() + "/Resource/" + entry.getVisType() + "/%s"; input.setResourcePathTemplate(template); } // getting the whole document, when plugin is using text if (visPlugin != null && visPlugin.isUsingText() && result != null && result.getDocumentGraph().getNodes().size() > 0) { List<String> nodeAnnoFilter = null; if (visPlugin instanceof FilteringVisualizerPlugin) { nodeAnnoFilter = ((FilteringVisualizerPlugin) visPlugin).getFilteredNodeAnnotationNames(corpusName, documentName, input.getMappings()); } SaltProject p = getDocument(result.getGraph().getRoots().get(0).getName(), result.getName(), nodeAnnoFilter); SDocument wholeDocument = p.getCorpusGraphs().get(0).getDocuments().get(0); input.setDocument(wholeDocument); } else { input.setDocument(result); } // getting the raw text, when the visualizer wants to have it if (visPlugin != null && visPlugin.isUsingRawText()) { input.setRawText(Helper.getRawText(corpusName, documentName)); } return input; }
From source file:annis.gui.resultview.VisualizerPanel.java
License:Apache License
private void updateGUIAfterLoadingVisualizer(LoadableVisualizer.Callback callback) { if (callback != null && vis instanceof LoadableVisualizer) { LoadableVisualizer loadableVis = (LoadableVisualizer) vis; if (loadableVis.isLoaded()) { // direct call callback since the visualizer is already ready callback.visualizerLoaded(loadableVis); } else {/*ww w .j a v a2s . c om*/ loadableVis.clearCallbacks(); // add listener when player was fully loaded loadableVis.addOnLoadCallBack(callback); } } progress.setEnabled(false); progress.setVisible(false); if (vis != null) { btEntry.setEnabled(true); vis.setVisible(true); if (vis instanceof PDFViewer) { ((PDFViewer) vis).openPDFPage("-1"); } if (vis instanceof MediaPlayer) { // if this is a media player visualizer, close all other media players // since some browsers (e.g. Chrome) have problems if there are multiple // audio/video elements on one page MediaController mediaController = VaadinSession.getCurrent().getAttribute(MediaController.class); mediaController.closeOtherPlayers((MediaPlayer) vis); } // add if not already added if (getComponentIndex(vis) < 0) { addComponent(vis); } } }