Example usage for com.vaadin.server VaadinSession unlock

List of usage examples for com.vaadin.server VaadinSession unlock

Introduction

In this page you can find the example usage for com.vaadin.server VaadinSession unlock.

Prototype

public void unlock() 

Source Link

Document

Unlocks this session.

Usage

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.j a v 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.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  2  s  .  co m
            .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:com.haulmont.cuba.web.toolkit.ui.CubaFileDownloader.java

License:Apache License

@Override
public boolean handleConnectorRequest(VaadinRequest request, VaadinResponse response, String path)
        throws IOException {
    if (path == null) {
        return false;
    }//  w  w w.  jav  a  2s .c  o  m

    String targetResourceKey;
    DownloadStream stream;

    VaadinSession session = getSession();
    session.lock();
    try {
        String[] parts = path.split("/", 2);
        targetResourceKey = parts[0];
        if (targetResourceKey.isEmpty()) {
            return false;
        }

        Resource resource = getResource(targetResourceKey);
        if (resource == null) {
            return false;
        }

        boolean isViewDocumentRequest = targetResourceKey.startsWith(VIEW_RESOURCE_PREFIX);

        stream = ((ConnectorResource) resource).getStream();

        String contentDisposition = stream.getParameter(DownloadStream.CONTENT_DISPOSITION);
        if (contentDisposition == null) {
            // Content-Disposition: attachment generally forces download
            contentDisposition = (isViewDocumentRequest ? "inline" : "attachment") + "; "
                    + DownloadStream.getContentDispositionFilename(stream.getFileName());
        }

        stream.setParameter(DownloadStream.CONTENT_DISPOSITION, contentDisposition);

        // Content-Type to block eager browser plug-ins from hijacking the file
        if (isOverrideContentType() && !isViewDocumentRequest) {
            stream.setContentType("application/octet-stream;charset=UTF-8");
        } else {
            if (StringUtils.isNotEmpty(stream.getContentType())) {
                stream.setContentType(stream.getContentType() + ";charset=UTF-8\"");
            } else {
                stream.setContentType(";charset=UTF-8\"");
            }
        }
    } finally {
        session.unlock();
    }

    stream.writeResponse(request, response);
    return true;
}

From source file:com.haulmont.cuba.web.widgets.CubaFileDownloader.java

License:Apache License

@Override
public boolean handleConnectorRequest(VaadinRequest request, VaadinResponse response, String path)
        throws IOException {
    if (path == null) {
        return false;
    }//from  w  w  w  . j  ava 2s . c  o m

    String targetResourceKey;
    DownloadStream stream;

    VaadinSession session = getSession();
    session.lock();
    try {
        String[] parts = path.split("/", 2);
        targetResourceKey = parts[0];
        if (targetResourceKey.isEmpty()) {
            return false;
        }

        Resource resource = getResource(targetResourceKey);
        if (resource == null) {
            return false;
        }

        boolean isViewDocumentRequest = targetResourceKey.startsWith(VIEW_RESOURCE_PREFIX);

        stream = ((ConnectorResource) resource).getStream();

        String contentDisposition = stream.getParameter(DownloadStream.CONTENT_DISPOSITION);
        if (contentDisposition == null) {
            // Content-Disposition: attachment generally forces download
            contentDisposition = (isViewDocumentRequest ? "inline" : "attachment") + "; "
                    + DownloadStream.getContentDispositionFilename(stream.getFileName());
        }

        stream.setParameter(DownloadStream.CONTENT_DISPOSITION, contentDisposition);

        // Content-Type to block eager browser plug-ins from hijacking the file
        if (isOverrideContentType() && !isViewDocumentRequest && !isSafariOrIOS()) {
            stream.setContentType("application/octet-stream;charset=UTF-8");
        } else {
            if (StringUtils.isNotEmpty(stream.getContentType())) {
                stream.setContentType(stream.getContentType() + ";charset=UTF-8\"");
            } else {
                stream.setContentType(";charset=UTF-8\"");
            }
        }
    } finally {
        session.unlock();
    }

    stream.writeResponse(request, response);
    return true;
}

From source file:com.peergreen.webconsole.core.vaadin7.BaseUI.java

License:Open Source License

@Override
public void accessSynchronously(Runnable runnable) {
    Map<Class<?>, CurrentInstance> old = null;

    VaadinSession session = getSession();

    if (session == null) {
        throw new UIDetachedException();
    }//from ww  w  .ja  v a 2  s.com

    // TODO PGWK-7 - hack to avoid exception when another session had lock
    //VaadinService.verifyNoOtherSessionLocked(session);

    session.lock();
    try {
        if (getSession() == null) {
            // UI was detached after fetching the session but before we
            // acquired the lock.
            throw new UIDetachedException();
        }
        old = CurrentInstance.setCurrent(this);
        runnable.run();
    } finally {
        session.unlock();
        if (old != null) {
            CurrentInstance.restoreInstances(old);
        }
    }
}

From source file:com.skysql.manager.ui.components.NodesLayout.java

License:Open Source License

/**
 * Refresh./*from  www. j  a  v a  2 s . c  om*/
 *
 * @param updaterThread the updater thread
 * @param parentSystemRecord the parent system record
 */
public synchronized void refresh(final OverviewPanel.UpdaterThread updaterThread,
        final SystemRecord parentSystemRecord) {

    VaadinSession session = getSession();
    if (session == null) {
        session = VaadinSession.getCurrent();
    }
    if (session == null) {
        return;
    }
    ManagerUI managerUI = session.getAttribute(ManagerUI.class);
    SystemInfo systemInfo = session.getAttribute(SystemInfo.class);
    OverviewPanel overviewPanel = session.getAttribute(OverviewPanel.class);

    if (parentSystemRecord == null) {
        systemID = null;
        placeholderLayout("Systems");
        return;
    } else if (parentSystemRecord.getNodes().length == 0) {
        placeholderLayout("Components");
        return;
    } else {
        if (placeholderLayout != null) {
            removeComponent(placeholderLayout);
            placeholderLayout = null;

            addStyleName("network");
        }
    }

    String[] newComponents = parentSystemRecord.getNodes();
    if (!parentSystemRecord.getID().equals(systemID)
            || (newComponents != null && !Arrays.equals(newComponents, components))) {
        systemID = parentSystemRecord.getID();
        components = newComponents;

        ManagerUI.log("Reload Components");

        String currentSelectedID = null;
        CCType currentSelectedType = null;
        ClusterComponent currentClusterComponent = session.getAttribute(ClusterComponent.class);
        if (currentClusterComponent != null) {
            currentSelectedID = currentClusterComponent.getID();
            currentSelectedType = currentClusterComponent.getType();
        }

        session.lock();
        try {

            // Here the UI is locked and can be updated
            ManagerUI.log("NodesLayout access run() removeall");
            removeAllComponents();

            ArrayList<ComponentButton> newButtons = new ArrayList<ComponentButton>();
            for (String componentID : parentSystemRecord.getNodes()) {

                final ClusterComponent clusterComponent;
                if (parentSystemRecord.getParentID() == null) {
                    // this is the ROOT record, where "nodes" is really the flat list of systems
                    clusterComponent = systemInfo.getSystemRecord(componentID);
                } else {
                    // this is a normal System record
                    clusterComponent = new NodeInfo(parentSystemRecord.getID(),
                            parentSystemRecord.getSystemType());
                    clusterComponent.setID(componentID);
                }

                //               if (updaterThread.flagged) {
                //                  ManagerUI.log("NodesLayout - flagged is set while adding nodes");
                //                  return;
                //               }

                ComponentButton button = clusterComponent.getButton();
                if (button == null) {
                    ManagerUI.log("NodesLayout access run() button not in component");
                    button = findButton(clusterComponent);
                }
                if (button == null) {
                    ManagerUI.log("NodesLayout access run() button not found");
                    button = new ComponentButton(clusterComponent);
                }
                addComponent(button);
                setComponentAlignment(button, Alignment.MIDDLE_CENTER);
                button.setEditable(isEditable);
                if (clusterComponent.getID().equals(currentSelectedID)
                        && clusterComponent.getType().equals(currentSelectedType) && !button.isSelected()) {
                    overviewPanel.clickLayout(button, true);
                }
                newButtons.add(button);
            }
            buttons = newButtons;
        } finally {
            session.unlock();
        }

    }

    //      if (updaterThread.flagged) {
    //         ManagerUI.log("NodesLayout - flagged is set after removeall");
    //         return;
    //      }

    ManagerUI.log("NodesLayout - before for loop - buttons: " + buttons.size());

    for (final ComponentButton button : buttons) {
        final ClusterComponent currentComponent = (ClusterComponent) button.getData();

        final ClusterComponent newComponent;

        switch (currentComponent.getType()) {
        case system:
            newComponent = systemInfo.updateSystem(currentComponent.getID());
            break;

        case node:
            NodeInfo nodeInfo = (NodeInfo) currentComponent;
            newComponent = new NodeInfo(nodeInfo.getParentID(), nodeInfo.getSystemType(), nodeInfo.getID());
            break;

        default:
            continue;
        }

        //         if (updaterThread.flagged) {
        //            ManagerUI.log("NodesLayout - flagged is set before run() ");
        //            return;
        //         }

        managerUI.access(new Runnable() {
            @Override
            public void run() {
                // Here the UI is locked and can be updated

                ManagerUI.log("NodesLayout access run() button " + newComponent.getName());

                String newName = newComponent.getName();
                if (newName != null && !newName.equals(currentComponent.getName())) {
                    button.setName(newName);
                    currentComponent.setName(newName);
                }

                String newState = newComponent.getState();
                currentComponent.setState(newState);

                String toolTip = null;
                switch (newComponent.getType()) {
                case system:
                    toolTip = ((SystemRecord) newComponent).ToolTip();
                    break;
                case node:
                    MonitorLatest monitorLatest = newComponent.getMonitorLatest();
                    String newCapacity = monitorLatest.getData().get(MonitorNames.capacity.name());
                    button.setIcon(currentComponent.getType().toString(), newState, newCapacity);

                    NodeInfo nodeInfo = (NodeInfo) newComponent;
                    toolTip = nodeInfo.ToolTip();
                    // carry over RunningTask(s)
                    nodeInfo.setCommandTask(((NodeInfo) currentComponent).getCommandTask());
                    button.setCommandLabel(nodeInfo.getTask());
                    break;
                default:
                    toolTip = "Unknown component type";
                    ManagerUI.error(toolTip);
                    break;
                }
                button.setDescription(toolTip);
                button.setData(newComponent);
                if (button.isSelected()) {
                    getSession().setAttribute(ClusterComponent.class, newComponent);
                }
            }
        });

    } // for all nodes

}

From source file:com.skysql.manager.ui.components.SystemLayout.java

License:Open Source License

/**
 * Refresh./*from  w  w w  . jav a 2 s.  c  om*/
 *
 * @param updaterThread the updater thread
 * @param systemRecord the system record
 */
public void refresh(final OverviewPanel.UpdaterThread updaterThread, SystemRecord systemRecord) {

    VaadinSession session = getSession();

    if (session != null) {
        session.lock();
    }
    try {

        if (systemRecord == null || systemRecord.getID() == null
                || systemRecord.getID().equals(SystemInfo.SYSTEM_ROOT)) {
            setVisible(false);
            systemID = null;
            return;
        }

        if (!systemRecord.getID().equals(systemID)) {
            systemID = systemRecord.getID();

            systemSlot.removeAllComponents();

            systemButton = new ComponentButton(systemRecord);
            systemButton.addLayoutClickListener(componentListener);
            systemButton.setSelected(systemButton.isSelected());
            systemButton.setDescription(systemRecord.ToolTip());
            systemSlot.addComponent(systemButton);

            setEditable(isEditable);

            setVisible(systemRecord.getParentID() == null ? false : true);
        }

        systemButton.setData(systemRecord);
        if (systemButton.isSelected()) {
            getSession().setAttribute(ClusterComponent.class, systemRecord);
        }
    } finally {
        if (session != null) {
            session.unlock();
        }
    }

}

From source file:fi.semantum.strategia.custom.OnDemandFileDownloader.java

License:Open Source License

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

    session.lock();/*ww  w  .  ja v  a  2  s  .c  o  m*/
    try {
        onDemandStreamSource.onRequest();
        getResource().setFilename(onDemandStreamSource.getFileName());
    } finally {
        session.unlock();
    }
    return super.handleConnectorRequest(request, response, path);
}

From source file:org.hip.vif.admin.admin.print.FileDownloaderExtension.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*  w w  w  .  ja  va  2  s .com*/
public boolean handleConnectorRequest(final VaadinRequest inRequest, final VaadinResponse inResponse,
        final String inPath) throws IOException {
    if (!inPath.matches("dl(/.*)?")) {
        // Ignore if it isn't for us
        return false;
    }

    final VaadinSession lSession = getSession();
    lSession.lock();

    DownloadStream lDownloadStream = null;
    try {
        final Collection<GroupWrapper> lSelected = (Collection<GroupWrapper>) groupSelect.getValue();
        Collection<GroupExtent> lGroups = new ArrayList<GroupExtent>();
        for (final GroupWrapper lGroup : lSelected) {
            final Long lGroupID = lGroup.getGroupID();
            if (lGroupID.equals(0l)) {
                lGroups = printTask.getAllGroups();
                break;
            } else {
                lGroups.add(new GroupExtent(lGroup.getGroupID()));
            }
        }

        final DownloadFile lDownloadFile = new DownloadFile(lGroups, VaadinSession.getCurrent().getLocale());
        lDownloadStream = lDownloadFile.getStream();
    } catch (final Exception exc) {
        LOG.error("Error encountered while printing the discussion groups!", exc); //$NON-NLS-1$
    } finally {
        lSession.unlock();
    }
    if (lDownloadStream != null) {
        lDownloadStream.writeResponse(inRequest, inResponse);
    }
    groupSelect.clear();
    return true;
}

From source file:org.vaadin.gridfiledownloader.GridFileDownloader.java

License:Apache License

@Override
public boolean handleConnectorRequest(VaadinRequest request, VaadinResponse response, String path)
        throws IOException {

    if (!path.matches("dl(/.*)?")) {
        // Ignore if it isn't for us
        return false;
    }//  w  w  w .ja v a 2s  .  c  om

    boolean markedProcessed = false;
    try {
        if (!waitForRPC()) {
            handleRPCTimeout();
            return false;
        }
        getResource().setFilename(gridStreamResource.getFilename());

        VaadinSession session = getSession();

        session.lock();
        DownloadStream stream;

        try {
            Resource resource = getFileDownloadResource();
            if (!(resource instanceof ConnectorResource)) {
                return false;
            }
            stream = ((ConnectorResource) resource).getStream();

            if (stream.getParameter("Content-Disposition") == null) {
                // Content-Disposition: attachment generally forces download
                stream.setParameter("Content-Disposition",
                        "attachment; filename=\"" + stream.getFileName() + "\"");
            }

            // Content-Type to block eager browser plug-ins from hijacking
            // the file
            if (isOverrideContentType()) {
                stream.setContentType("application/octet-stream;charset=UTF-8");
            }
        } finally {
            try {
                markProcessed();
                markedProcessed = true;
            } finally {
                session.unlock();
            }
        }
        try {
            stream.writeResponse(request, response);
        } catch (Exception e) {
            handleWriteResponseException(e);
        }
        return true;
    } finally {
        // ensure the download request always gets marked processed
        if (!markedProcessed) {
            markProcessed();
        }
    }
}