Exemplo n.º 1
0
 private static String getSessionDetails(VaadinSession session) {
   if (session == null) {
     return null;
   } else {
     return session.toString() + " for " + session.getService().getServiceName();
   }
 }
Exemplo n.º 2
0
 @SuppressWarnings("unchecked")
 public GridThreatEvents() {
   groups = (List<UserGroup>) VaadinSession.getCurrent().getAttribute("groups");
   groupsNames = (List<UserGroupName>) VaadinSession.getCurrent().getAttribute("groupNames");
   dateFormat = new SimpleDateFormat("yyyy-MM-dd");
   buildGrid();
 }
Exemplo n.º 3
0
  @Override
  public boolean handleConnectorRequest(VaadinRequest request, VaadinResponse response, String path)
      throws IOException {
    Matcher matcher = Pattern.compile("(\\d+)(/.*)?").matcher(path);
    if (!matcher.matches()) {
      return super.handleConnectorRequest(request, response, path);
    }

    DownloadStream stream;

    VaadinSession session = getSession();
    session.lock();
    try {
      List<URLReference> sources = getState().sources;

      int sourceIndex = Integer.parseInt(matcher.group(1));

      if (sourceIndex < 0 || sourceIndex >= sources.size()) {
        getLogger().log(Level.WARNING, "Requested source index {0} is out of bounds", sourceIndex);
        return false;
      }

      URLReference reference = sources.get(sourceIndex);
      ConnectorResource resource = (ConnectorResource) ResourceReference.getResource(reference);
      stream = resource.getStream();
    } finally {
      session.unlock();
    }

    stream.writeResponse(request, response);
    return true;
  }
Exemplo n.º 4
0
 private static WrappedSession getCurrentHttpSession() {
   VaadinSession s = VaadinSession.getCurrent();
   if (s == null) {
     throw new IllegalStateException("No session found for current thread");
   }
   return s.getSession();
 }
  /**
   * Refresh.
   *
   * @param time the time
   * @param interval the interval
   */
  public void refresh(String time, String interval) {
    this.time = time;
    this.interval = interval;

    //		if (isChartsEditing) {
    //			return;
    //		}
    VaadinSession session = getSession();
    if (session == null) {
      session = VaadinSession.getCurrent();
    }
    boolean isChartsEditing2 = (Boolean) session.getAttribute("isChartsEditing");
    if (isChartsEditing2) {
      return;
    }

    ManagerUI.log("ChartsLayout refresh()");

    Iterator<Component> iter = iterator();
    while (iter.hasNext()) {

      Component component = iter.next();
      if (component instanceof ChartButton) {
        ChartButton chartButton = (ChartButton) component;

        UpdaterThread updaterThread = new UpdaterThread(chartButton);
        updaterThread.start();
      }
    }
  }
 public void localeSetting(Locale locale) {
   try {
     VaadinSession.getCurrent().getLockInstance().lock();
     VaadinSession.getCurrent().setAttribute(CURRENTLOCALE.toString(), locale);
   } finally {
     VaadinSession.getCurrent().getLockInstance().unlock();
   }
 }
Exemplo n.º 7
0
  /**
   * Find the UI for the atmosphere resource, lock it and invoke the callback.
   *
   * @param resource the atmosphere resource for the current request
   * @param callback the push callback to call when a UI is found and locked
   */
  private void callWithUi(final AtmosphereResource resource, final PushEventCallback callback) {
    AtmosphereRequest req = resource.getRequest();
    VaadinServletRequest vaadinRequest = new VaadinServletRequest(req, service);
    VaadinSession session = null;

    service.requestStart(vaadinRequest, null);
    try {
      try {
        session = service.findVaadinSession(vaadinRequest);
      } catch (ServiceException e) {
        getLogger().log(Level.SEVERE, "Could not get session. This should never happen", e);
      } catch (SessionExpiredException e) {
        SystemMessages msg =
            service.getSystemMessages(
                ServletPortletHelper.findLocale(null, null, vaadinRequest), vaadinRequest);
        try {
          resource
              .getResponse()
              .getWriter()
              .write(
                  VaadinService.createCriticalNotificationJSON(
                      msg.getSessionExpiredCaption(),
                      msg.getSessionExpiredMessage(),
                      null,
                      msg.getSessionExpiredURL()));
        } catch (IOException e1) {
          getLogger().log(Level.WARNING, "Failed to notify client about unavailable session", e);
        }
        return;
      }

      session.lock();
      try {
        VaadinSession.setCurrent(session);
        // Sets UI.currentInstance
        final UI ui = service.findUI(vaadinRequest);
        if (ui == null) {
          // This a request through an already open push connection to
          // a UI which no longer exists.
          resource
              .getResponse()
              .getWriter()
              .write(UidlRequestHandler.getUINotFoundErrorJSON(service, vaadinRequest));
          // End the connection
          resource.resume();
          return;
        }

        callback.run(resource, ui);
      } catch (IOException e) {
        getLogger().log(Level.INFO, "An error occured while writing a push response", e);
      } finally {
        session.unlock();
      }
    } finally {
      service.requestEnd(vaadinRequest, null, session);
    }
  }
Exemplo n.º 8
0
  @SuppressWarnings("deprecation")
  private void prepAttach() {
    when(request.getParameter("v-loc")).thenReturn(baseUri + "/#home");
    ui.getPage().init(request);
    when(session.createConnectorId(Matchers.any(ClientConnector.class)))
        .thenAnswer(new ConnectorIdAnswer());
    when(session.getLocale()).thenReturn(Locale.FRANCE);

    when(session.hasLock()).thenReturn(true);
    ui.setSession(session);
  }
  public void displayReport(Filter filter, Map<String, Object> parameters) {
    // TODO make the report generation asynchronous and display the first page when it is ready
    // and not after last
    // page is ready
    currentParameters = parameters;

    // Load template
    ReportDefinition rd = (ReportDefinition) getReportSelection().getValue();
    String path = getFullPath(rd);
    jasperReport = reportGenerator.loadTemplate(path);

    // Set parameters
    Map<String, Object> params = JRUtils.createParametersFromFilter(jasperReport, filter);
    params.putAll(currentParameters);
    currentParameters.putAll(params);

    // Set datasource
    jrDataSource = null;
    if (!rd.requiresDatabaseConnection()) {
      if (container instanceof Indexed) {
        jrDataSource = new JRIndexedContainerDataSource((Indexed) container);
      } else {
        jrDataSource = new JRContainerDataSource(container);
      }
    }

    // Generate report
    reportGenerator.setShowMargins(showMargins.getValue());
    String html =
        reportGenerator.executeReportAsHtml(
            jasperReport,
            params,
            jrDataSource,
            ((WrappedHttpSession) VaadinSession.getCurrent().getSession()).getHttpSession(),
            VaadinSession.getCurrent().getLocale());
    if (html == null || "".equals(html) || (container != null && container.size() <= 0)) {
      reportArea.setValue(getMessageService().getMessage(NO_DATA_FOUND_KEY));
      exportPDF.setEnabled(false);
    } else {
      if (rd.requiresExternalScript()) {
        VaadinUtils.loadScript(REPORT_AREA_ID, html, rd.requiresExternalScript(), alreadyLoaded);

        // only load external script for the map
        alreadyLoaded = true;
      } else {
        reportArea.setValue(html);
      }
      exportPDF.setEnabled(true);
    }
  }
  @Override
  protected void init(VaadinRequest request) {
    Messages.setLocale(VaadinSession.getCurrent().getLocale());
    final LoginPanel loginPanel = new LoginPanel();

    setContent(loginPanel);
  }
Exemplo n.º 11
0
  public TimelineScreen() {

    setMargin(true);

    Label label = new Label(VaadinSession.getCurrent().getAttribute(Principal.class).getName());

    Button button = new Button("Logout");

    button.addClickListener(new LogoutBehavior());

    HorizontalLayout menuBar = new HorizontalLayout(label, button);

    menuBar.setWidth(100, PERCENTAGE);
    menuBar.setComponentAlignment(button, MIDDLE_RIGHT);
    menuBar.setMargin(true);

    addComponent(menuBar);

    TweetRefresherBehavior behavior = TwaattinUI.getCurrent().getTweetRefresherBehavior();

    addComponentAttachListener(behavior);

    VerticalLayout timeline = new VerticalLayout();

    timeline.addStyleName("p-timeline");

    addComponent(timeline);
  }
Exemplo n.º 12
0
        @Override
        public void run(AtmosphereResource resource, UI ui) throws IOException {
          getLogger()
              .log(Level.FINER, "New push connection with transport {0}", resource.transport());
          resource.getResponse().setContentType("text/plain; charset=UTF-8");

          VaadinSession session = ui.getSession();
          if (resource.transport() == TRANSPORT.STREAMING) {
            // IE8 requires a longer padding to work properly if the
            // initial message is small (#11573). Chrome does not work
            // without the original padding...
            WebBrowser browser = session.getBrowser();
            if (browser.isIE() && browser.getBrowserMajorVersion() == 8) {
              resource.padding(LONG_PADDING);
            }

            // Must ensure that the streaming response contains
            // "Connection: close", otherwise iOS 6 will wait for the
            // response to this request before sending another request to
            // the same server (as it will apparently try to reuse the same
            // connection)
            resource.getResponse().addHeader("Connection", "close");
          }

          String requestToken =
              resource.getRequest().getParameter(ApplicationConstants.CSRF_TOKEN_PARAMETER);
          if (!VaadinService.isCsrfTokenValid(session, requestToken)) {
            getLogger()
                .log(
                    Level.WARNING,
                    "Invalid CSRF token in new connection received from {0}",
                    resource.getRequest().getRemoteHost());
            // Refresh on client side, create connection just for
            // sending a message
            sendRefreshAndDisconnect(resource);
            return;
          }

          resource.suspend();

          AtmospherePushConnection connection = new AtmospherePushConnection(ui);
          connection.connect(resource);

          ui.setPushConnection(connection);
        }
  // Generic method that creates necessary VaadinSessin mock environment to be
  // able to test the BeanStoreRetrievalStrategy class.
  // To use it, call this method and write your test logic inside the
  // test method implemented from BeanStoreRetrievalStrategyTest interface.
  private synchronized void beanStoreTest(
      BeanStoreRetrievalStrategyTest test, boolean openVaadinSession) {
    WrappedSession wrappedSession = mock(WrappedSession.class);
    VaadinService vaadinService = mock(VaadinService.class);

    VaadinSession session = mock(VaadinSession.class);
    if (openVaadinSession) {
      when(session.getState()).thenReturn(VaadinSession.State.OPEN);
    } else {
      when(session.getState()).thenReturn(VaadinSession.State.CLOSED);
    }
    when(session.getSession()).thenReturn(wrappedSession);
    when(session.getService()).thenReturn(vaadinService);
    when(session.getSession().getId()).thenReturn(TEST_SESSION_ID);

    UIID uiid = new UIID(TEST_UIID);
    BeanStore beanStore = new BeanStore(TEST_BEAN_NAME);

    UIStore uiStore = mock(UIStore.class);
    when(session.getAttribute(UIStore.class)).thenReturn(uiStore);
    when(uiStore.getBeanStore(uiid)).thenReturn(beanStore);

    try {
      CurrentInstance.set(VaadinSession.class, session);
      CurrentInstance.set(UIID.class, uiid);

      test.test(session, uiStore, uiid);
    } finally {
      CurrentInstance.clearAll();
    }
  }
 // NOTE: the finish() method above is not called if the user
 // doesn't browse back from the OAuth authentication page.
 // That's why we make cleanUpSession public so that others can clean up also.
 public void cleanUpSession(final VaadinSession session) {
   session.access(
       new Runnable() {
         @Override
         public void run() {
           session.removeRequestHandler(AuthCallbackRequestHandler.this);
         }
       });
 }
Exemplo n.º 15
0
  public Login() {
    // TODO Auto-generated constructor stub
    VaadinSession.getCurrent().setAttribute("municipaldata", null);
    VaadinSession.getCurrent().setAttribute("barangaydata", null);
    VaadinSession.getCurrent().setAttribute("id", null);
    setSizeFull();
    dialog = new Window("Login");
    dialog.setClosable(false);
    dialog.setResizable(false);
    dialog.center();

    //		new CreateAccount();

    VerticalLayout content = new VerticalLayout();
    content.setSpacing(true);
    content.setMargin(new MarginInfo(false, true, true, true));
    dialog.setContent(content);

    Label title = new Label("Login");
    title.addStyleName(ValoTheme.LABEL_H2);
    title.addStyleName(ValoTheme.LABEL_COLORED);

    HorizontalLayout form = new HorizontalLayout();
    form.setSpacing(true);
    form.addStyleName("wrapping");
    content.addComponent(form);

    username.setIcon(FontAwesome.USER);
    username.focus();
    form.addComponent(username);

    password.setIcon(FontAwesome.LOCK);
    form.addComponent(password);

    Button submit = new Button("Login");
    submit.addStyleName(ValoTheme.BUTTON_ICON_ALIGN_RIGHT);
    submit.addStyleName(ValoTheme.BUTTON_PRIMARY);
    submit.setIcon(FontAwesome.ARROW_RIGHT);
    submit.setWidth("100%");
    submit.addListener(ClickEvent.class, this, "gotoMain");
    content.addComponent(submit);
  }
  private void logout() {
    btnLogin.setVisible(true);
    btnRegistration.setVisible(true);
    btnAdvertReg.setVisible(false);
    btnMyAccout.setVisible(false);
    btnLogout.setVisible(false);
    btnAdminAccount.setVisible(false);

    AccountView.setAvailability(false);
    AdvertRegView.setAvailability(false);
    LetterView.setAvailability(false);
    AdminView.setAvailability(false);

    try {
      VaadinSession.getCurrent().getLockInstance().lock();
      VaadinSession.getCurrent().setAttribute(CURRENTUSER.toString(), null);
    } finally {
      VaadinSession.getCurrent().getLockInstance().unlock();
    }
    userLabel.setValue("");
  }
Exemplo n.º 17
0
  @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;
    }
    VaadinSession session = getSession();

    session.lock();
    AdvancedFileDownloader.this.fireEvent();

    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 {
      session.unlock();
    }
    stream.writeResponse(request, response);
    return true;
  }
 private void updateContent() {
   MlUser user = (MlUser) VaadinSession.getCurrent().getAttribute(MlUser.class.getName());
   if (user != null
   //            && "admin".equals(user.getRole())
   ) {
     setContent(new MainView());
     removeStyleName("loginview");
     getNavigator().navigateTo(getNavigator().getState());
   } else {
     setContent(new LoginView());
     addStyleName("loginview");
   }
 }
  @Before
  public void setup() {
    vaadinSession = new AlwaysLockedVaadinSession(null);
    VaadinSession.setCurrent(vaadinSession);
    ui =
        new UI() {

          @Override
          protected void init(VaadinRequest request) {}
        };
    ui.setSession(vaadinSession);
    UI.setCurrent(ui);
  }
Exemplo n.º 20
0
  /* (non-Javadoc)
   * @see com.mapping.configuration.ui.action.Action#exectuteAction()
   */
  @Override
  public void exectuteAction() {
    IkasanAuthentication ikasanAuthentication =
        (IkasanAuthentication)
            VaadinService.getCurrentRequest()
                .getWrappedSession()
                .getAttribute(DashboardSessionValueConstants.USER);

    VaadinService.getCurrentRequest()
        .getWrappedSession()
        .setAttribute(DashboardSessionValueConstants.USER, null);
    this.visibilityGroup.setVisible();
    this.editableGroup.setEditable(false);

    layout.removeComponent(this.logOutButton);
    layout.addComponent(this.loginButton, 2, 0);
    layout.addComponent(this.setupButton, 3, 0);
    layout.setComponentAlignment(this.setupButton, Alignment.MIDDLE_RIGHT);
    layout.setComponentAlignment(this.loginButton, Alignment.MIDDLE_RIGHT);
    this.layout.removeComponent(userLabel);

    VaadinSession vSession = VaadinSession.getCurrent();
    WrappedSession httpSession = vSession.getSession();

    this.navigationPanel.reset();

    // Invalidate HttpSession
    httpSession.invalidate();
    vSession.close();

    systemEventService.logSystemEvent(
        SystemEventConstants.DASHBOARD_LOGOUT_CONSTANTS,
        "User logging out: " + ikasanAuthentication.getName(),
        ikasanAuthentication.getName());

    // Redirect the user to the login/default Page
    Page.getCurrent().setLocation("/ikasan-dashboard");
  }
Exemplo n.º 21
0
  @Override
  public Component createComponent(final VisualizerInput vis, VisualizationToggle visToggle) {

    VaadinSession session = VaadinSession.getCurrent();
    if (session.getAttribute(IFrameResourceMap.class) == null) {
      session.setAttribute(IFrameResourceMap.class, new IFrameResourceMap());
    }

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    writeOutput(vis, outStream);

    IFrameResource res = new IFrameResource();
    res.setData(outStream.toByteArray());
    res.setMimeType(getContentType());

    UUID uuid = UUID.randomUUID();
    session.getAttribute(IFrameResourceMap.class).put(uuid, res);

    URI base = UI.getCurrent().getPage().getLocation();
    AutoHeightIFrame iframe =
        new AutoHeightIFrame(base.resolve("vis-iframe-res/" + uuid.toString()));
    return iframe;
  }
  /**
   * Sets the editable.
   *
   * @param editable the new editable
   */
  public void setEditable(boolean editable) {
    isChartsEditing = editable;
    VaadinSession.getCurrent().setAttribute("isChartsEditing", isChartsEditing);

    Iterator<Component> iter = iterator();
    while (iter.hasNext()) {
      ChartButton chartButton = (ChartButton) iter.next();
      chartButton.setEditable(editable);
    }

    // when getting out of editable mode, save mappings
    if (editable == false) {
      saveChartsToProperties();
    }
  }
Exemplo n.º 23
0
  protected LogEvent prepareLogEvent(LogEvent.Types eventType) {
    LogEvent logEvent = new LogEvent();
    logEvent.setType(eventType);
    User user = (User) VaadinSession.getCurrent().getAttribute(User.class.getName());
    logEvent.setUserName(user.getName());
    user = null;
    logEvent.setIp(UI.getCurrent().getPage().getWebBrowser().getAddress());
    logEvent.setResult(this.getClass().getName());
    logEvent.setAction(this.getClass().getName());
    logEvent.setViewName(view.getName());
    logEvent.setCreateDate(new Date());
    logEvent.setEntity(null);

    return logEvent;
  }
 private void saveUser(String oauthId, String name, String email, String picUrl) {
   User user =
       UserBean.builder()
           .oauthIdentifier(oauthId)
           .firstName(name)
           .picUrl(picUrl)
           .lastName("")
           .email(email)
           .role("user")
           .build();
   try {
     UserVertex userVertex = (UserVertex) new UserVertex(user).saveOrUpdateInNewTX();
     user = userVertex.model();
     VaadinSession.getCurrent().setAttribute(User.class.getName(), user);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 25
0
 public MainScreen() {
   Label loginLabel =
       new Label("Welcome " + VaadinSession.getCurrent().getAttribute(String.class));
   HorizontalLayout menuBar = new HorizontalLayout(loginLabel);
   MessageTable table = new MessageTable();
   TextArea messageArea = new TextArea();
   messageArea.setWidth(100, PERCENTAGE);
   Button sendButton = new Button("Send");
   sendButton.addClickListener(new SendMessageClickListener(table, messageArea));
   HorizontalLayout lowerBar = new HorizontalLayout(messageArea, sendButton);
   lowerBar.setWidth(100, PERCENTAGE);
   lowerBar.setSpacing(true);
   VerticalLayout mainLayout = new VerticalLayout(menuBar, table, lowerBar);
   mainLayout.setSpacing(true);
   mainLayout.setMargin(true);
   mainLayout.setSizeFull();
   setCompositionRoot(mainLayout);
 }
  /**
   * Asynch refresh.
   *
   * @param updaterThread the updater thread
   */
  private void asynchRefresh(UpdaterThread updaterThread) {

    VaadinSession.getCurrent().setAttribute("ChartsRefresh", true);
    refreshCode(updaterThread.chartButton, updaterThread);
    VaadinSession.getCurrent().setAttribute("ChartsRefresh", false);
  }
Exemplo n.º 27
0
 private List<ActivitiesSummary> getActivities() {
   Athlete athlete = (Athlete) VaadinSession.getCurrent().getAttribute(Athlete.class.getName());
   return MyVaadinUI.getActivityService().getActivitiesSummary(athlete.getToken());
 }
  /**
   * Refresh code.
   *
   * @param chartButton the chart button
   * @param updaterThread the updater thread
   */
  public void refreshCode(ChartButton chartButton, UpdaterThread updaterThread) {
    String systemID, nodeID;

    VaadinSession session = getSession();
    if (session == null) {
      session = VaadinSession.getCurrent();
    }
    ManagerUI managerUI = session.getAttribute(ManagerUI.class);
    ClusterComponent componentInfo = session.getAttribute(ClusterComponent.class);

    switch (componentInfo.getType()) {
      case system:
        systemID = componentInfo.getID();
        nodeID = SystemInfo.SYSTEM_NODEID;
        break;

      case node:
        systemID = componentInfo.getParentID();
        nodeID = componentInfo.getID();
        break;

      default:
        return;
    }

    final UserChart userChart = (UserChart) chartButton.getData();
    final Chart chart = chartButton.getChart();
    boolean needsRedraw = false;
    String[] timeStamps = null;
    final Configuration configuration = chart.getConfiguration();

    for (String monitorID : userChart.getMonitorIDs()) {

      if (updaterThread != null && updaterThread.flagged) {
        ManagerUI.log(this.getClass().getName() + " - flagged is set before API call");
        return;
      }

      ManagerUI.log("ChartsLayout - redraw loop MonitorID: " + monitorID);
      final MonitorRecord monitor = Monitors.getMonitor(monitorID);
      if (monitor == null) {
        // monitor was removed from the system: skip
        ManagerUI.log("monitor was removed from the system");
        continue;
      }

      MonitorData monitorData = (MonitorData) userChart.getMonitorData(monitor.getID());
      if (monitorData == null) {
        String method;
        if (UserChart.ChartType.LineChart.name().equals(userChart.getType())) {
          method = MonitorData.METHOD_AVG;
        } else if (UserChart.ChartType.AreaChart.name().equals(userChart.getType())) {
          method = MonitorData.METHOD_MINMAX;
        } else {
          continue; // unknown chart type, skip
        }
        monitorData =
            new MonitorData(
                monitor, systemID, nodeID, time, interval, userChart.getPoints(), method);
        needsRedraw = true;
      } else if (monitorData.update(systemID, nodeID, time, interval, userChart.getPoints())
          == true) {
        // data in chart needs to be updated
        needsRedraw = true;
      } else {
        continue; // no update needed
      }

      if (timeStamps == null) {
        DateConversion dateConversion = session.getAttribute(DateConversion.class);

        ArrayList<Long> unixTimes = monitorData.getTimeStamps();
        if (unixTimes != null) {
          timeStamps = new String[unixTimes.size()];
          int timeSpacer = unixTimes.size() / 15;
          for (int x = 0; x < unixTimes.size(); x++) {
            timeStamps[x] =
                (x % timeSpacer != 0) ? "\u00A0" : dateConversion.stampToString(unixTimes.get(x));
          }
        }
      }

      if (updaterThread != null && updaterThread.flagged) {
        ManagerUI.log("ChartsLayout - flagged is set before UI redraw");
        return;
      }

      final MonitorData finalMonitorData = monitorData;
      final String finalMonitorID = monitorID;

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

              ManagerUI.log("ChartsLayout access run() monitorID: " + finalMonitorID);

              if (UserChart.ChartType.LineChart.name().equals(userChart.getType())) {

                ListSeries ls = null, testLS;
                List<Series> lsList = configuration.getSeries();
                Iterator seriesIter = lsList.iterator();
                while (seriesIter.hasNext()) {
                  testLS = (ListSeries) seriesIter.next();
                  if (testLS.getName().equals(monitor.getName())) {
                    ls = testLS;
                    break;
                  }
                }
                if (ls == null) {
                  ls = new ListSeries(monitor.getName());
                  configuration.addSeries(ls);
                }

                userChart.setMonitorData(monitor.getID(), finalMonitorData);

                ArrayList<Number> avgList = finalMonitorData.getAvgPoints();
                ls.setData(avgList);

              } else if (UserChart.ChartType.AreaChart.name().equals(userChart.getType())) {

                RangeSeries rs = null, testRS;
                List<Series> lsList = configuration.getSeries();
                Iterator seriesIter = lsList.iterator();
                while (seriesIter.hasNext()) {
                  testRS = (RangeSeries) seriesIter.next();
                  if (testRS.getName().equals(monitor.getName())) {
                    rs = testRS;
                    break;
                  }
                }
                if (rs == null) {
                  rs = new RangeSeries(monitor.getName());
                  configuration.addSeries(rs);
                }

                userChart.setMonitorData(monitor.getID(), finalMonitorData);

                ArrayList<Number> minList = finalMonitorData.getMinPoints();
                ArrayList<Number> maxList = finalMonitorData.getMaxPoints();

                if (minList != null
                    && maxList != null
                    && minList.size() > 0
                    && maxList.size() > 0
                    && minList.size() == maxList.size()) {
                  Object[] minArray = finalMonitorData.getMinPoints().toArray();
                  Object[] maxArray = finalMonitorData.getMaxPoints().toArray();

                  Number[][] dataList = new Number[minList.size()][2];
                  for (int x = 0; x < minList.size(); x++) {
                    dataList[x][0] = (Number) minArray[x];
                    dataList[x][1] = (Number) maxArray[x];
                  }

                  rs.setRangeData(dataList);
                } else {
                  rs.setRangeData(new Number[0][0]);
                }
              }
            }
          });
    } // for

    final boolean finalNeedsRedraw = needsRedraw;
    final String[] finalTimeStamps = timeStamps;
    final ChartButton finalChartButton = chartButton;

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

            if (finalNeedsRedraw) {
              ManagerUI.log("ChartsLayout needsRedraw");

              if (finalTimeStamps != null) {
                XAxis xAxis = configuration.getxAxis();
                Labels labels = new Labels();
                labels.setRotation(-45);
                labels.setAlign(HorizontalAlign.RIGHT);
                xAxis.setLabels(labels);
                xAxis.setCategories(finalTimeStamps);
              }

              chart.drawChart(configuration);
              finalChartButton.setVisible(true);
            }
          }
        });
  }
 private static void setUserLabel() {
   Advertiser a = (Advertiser) VaadinSession.getCurrent().getAttribute(CURRENTUSER.toString());
   userLabel.setValue(loggedIn + a.getEmail());
 }
Exemplo n.º 30
0
 public void sessionInit(SessionInitEvent event) throws ServiceException {
   event.getService();
   final VaadinSession session = event.getSession();
   session.addUIProvider(applicationProvider.get());
 }