Пример #1
0
  private void buildCategoryTree() {
    tree = categoryTree.initialize();
    tree.addItemClickListener(this);
    tree.setSizeUndefined();

    treePanel.addStyleName(Runo.PANEL_LIGHT);
    treePanel.setHeight("100%");
    treePanel.setContent(treeLayout);

    treeLayout.setImmediate(true);
    treeLayout.setMargin(true);
    treeLayout.setSizeUndefined();
    treeLayout.addStyleName(Reindeer.LAYOUT_WHITE);
    treeLayout.addComponent(tree);

    topTreeLayout.setHeight("100%");
    topTreeLayout.setCaption("Categories");
    topTreeLayout.addStyleName(Runo.LAYOUT_DARKER);
    // topTreeLayout.addComponent(lblCategoryCaption);
    topTreeLayout.addComponent(treePanel);

    btnCreate.addClickListener(this);
    btnUpdate.addClickListener(this);
    btnDelete.addClickListener(this);
  }
Пример #2
0
 public void setParent(File file, Folder newParent) {
   tree1.setParent(file, newParent);
   if (sp.getSecondComponent() instanceof FolderView) {
     FolderView view = (FolderView) sp.getSecondComponent();
     view.reload();
   }
 }
Пример #3
0
  /** 1级树初始化 * */
  private void initTree() {
    // 为了保证错误操作 我们不把原有的数据清除 每次删除之后 在重新登录之后才会删除
    leftTree = new Tree();
    List<String> itemNames = this.complainTypeManager.getComplainType();
    for (String itemName : itemNames) {
      leftTree.addItem(itemName);
    }
    // treeItem 单击事件
    leftTree.addItemClickListener(
        new ItemClickEvent.ItemClickListener() {

          @Override
          public void itemClick(ItemClickEvent event) {
            if (event.getButtonName().equals(MouseButton.LEFT.getName())) {
              initContainer(container, event.getItemId().toString());
              rightTable.setContainerDataSource(container);
            }
          }
        });
    conentHSplit.setFirstComponent(leftTree);
  }
Пример #4
0
 /*
  * (non-Javadoc)
  *
  * @see
  * com.vaadin.event.dd.acceptCriteria.AcceptCriterion#paintResponse(
  * com.vaadin.server.PaintTarget)
  */
 @Override
 public void paintResponse(PaintTarget target) throws PaintException {
   /*
    * send allowed nodes to client so subsequent requests can be
    * avoided
    */
   Object[] array = allowedItemIds.toArray();
   for (int i = 0; i < array.length; i++) {
     String key = tree.key(array[i]);
     array[i] = key;
   }
   target.addAttribute("allowedIds", array);
 }
  @Override
  protected void setup() {

    Tree tree = new Tree();
    tree.setImmediate(true);

    tree.addContainerProperty("caption", String.class, "");
    for (int i = 1; i <= 10; i++) {
      String item = "Node " + i;
      tree.addItem(item);
      tree.getContainerProperty(item, "caption").setValue("Caption " + i);
      tree.setChildrenAllowed(item, false);
    }
    tree.setItemCaptionMode(Tree.ITEM_CAPTION_MODE_PROPERTY);
    tree.setItemCaptionPropertyId("caption");

    tree.addListener(
        new ItemClickEvent.ItemClickListener() {
          @Override
          public void itemClick(ItemClickEvent event) {
            clickCounter++;
            switch (event.getButton()) {
              case LEFT:
                log.log("Left Click");
                break;
              case RIGHT:
                log.log("Right Click");
                break;
              case MIDDLE:
                log.log("Middle Click");
                break;
            }
          }
        });

    addComponent(tree);
    addComponent(log);
  }
  @Override
  protected Component createRightColumnContent() {

    VerticalLayout layout = new VerticalLayout();

    layout.setMargin(true);
    layout.setSpacing(true);

    VerticalLayout usersLayout = new VerticalLayout();
    layout.addComponent(usersLayout);

    usersLayout.addComponent(new Label("<h2>Správa kategorií</h2>", Label.CONTENT_XHTML));

    usersLayout.addComponent(tree);
    tree.setImmediate(true);
    tree.setDragMode(TreeDragMode.NODE);
    tree.setDropHandler(
        new DropHandler() {

          private static final long serialVersionUID = -5607799513535550687L;

          public AcceptCriterion getAcceptCriterion() {
            return AcceptAll.get();
          }

          public void drop(DragAndDropEvent dropEvent) {

            Transferable data = dropEvent.getTransferable();

            TreeTargetDetails dropData = ((TreeTargetDetails) dropEvent.getTargetDetails());

            Object sourceItemId = ((DataBoundTransferable) data).getItemId();
            Object targetItemId = dropData.getItemIdOver();

            VerticalDropLocation location = dropData.getDropLocation();

            moveNode(sourceItemId, targetItemId, location);
          }

          /** viz. http://demo.vaadin.com/sampler#DragDropTreeSorting */

          /**
           * Move a node within a tree onto, above or below another node depending on the drop
           * location.
           *
           * @param sourceItemId id of the item to move
           * @param targetItemId id of the item onto which the source node should be moved
           * @param location VerticalDropLocation indicating where the source node was dropped
           *     relative to the target node
           */
          private void moveNode(
              final Object sourceItemId, final Object targetItemId, VerticalDropLocation location) {
            final HierarchicalContainer container =
                (HierarchicalContainer) tree.getContainerDataSource();

            // Sorting goes as
            // - If dropped ON a node, we append it as a child
            // - If dropped on the TOP part of a node, we move/add it before
            // the node
            // - If dropped on the BOTTOM part of a node, we move/add it
            // after the node

            final Object parentItemId = container.getParent(targetItemId);

            final NodeDTO parent = parentItemId == null ? null : (NodeDTO) parentItemId;
            final NodeDTO source = (NodeDTO) sourceItemId;
            final NodeDTO target = (NodeDTO) targetItemId;

            switch (location) {
              case MIDDLE:

                // Přesunutí znamená rovnou přesun kategorie - v tom případě
                // je potřeba vyhodit potvrzovací okno
                addWindow(
                    new ConfirmSubwindow(
                        "Opravdu přesunout '"
                            + source.getName()
                            + "' do '"
                            + target.getName()
                            + "' ?") {

                      private static final long serialVersionUID = 414272650677665672L;

                      @Override
                      protected void onConfirm(ClickEvent event) {
                        if (nodeFacade.moveNode(source, target)) {
                          if (container.setParent(sourceItemId, targetItemId)
                              && container.hasChildren(targetItemId)) {
                            // move first in the container
                            container.moveAfterSibling(sourceItemId, null);
                          }
                          CategoriesSettingsWindow.this.showInfo(
                              "Přesun kategorie proběhl úspěšně");
                        } else {
                          CategoriesSettingsWindow.this.showWarning(
                              "Nezdařilo se přesunout kategorii do vybraného místa");
                        }
                      }
                    });

                break;
              case TOP:

                // Přesunutí znamená rovnou přesun kategorie - v tom případě
                // je potřeba vyhodit potvrzovací okno
                addWindow(
                    new ConfirmSubwindow(
                        "Opravdu přesunout '"
                            + source.getName()
                            + "' do "
                            + (parentItemId == null
                                ? "kořene sekce ?"
                                : ("'" + parent.getName() + "' ?"))) {

                      private static final long serialVersionUID = 414272650677665672L;

                      @Override
                      protected void onConfirm(ClickEvent event) {
                        if (nodeFacade.moveNode(source, parent)) {
                          if (container.setParent(sourceItemId, parentItemId)) {
                            // reorder only the two items, moving source
                            // above target
                            container.moveAfterSibling(sourceItemId, targetItemId);
                            container.moveAfterSibling(targetItemId, sourceItemId);
                          }
                          CategoriesSettingsWindow.this.showInfo(
                              "Přesun kategorie proběhl úspěšně");
                        } else {
                          CategoriesSettingsWindow.this.showWarning(
                              "Nezdařilo se přesunout kategorii do vybraného místa");
                        }
                      }
                    });

                break;
              case BOTTOM:

                // Přesunutí znamená rovnou přesun kategorie - v tom případě
                // je potřeba vyhodit potvrzovací okno

                addWindow(
                    new ConfirmSubwindow(
                        "Opravdu přesunout '"
                            + source.getName()
                            + "' do "
                            + (parentItemId == null
                                ? "kořene sekce ?"
                                : ("'" + parent.getName() + "' ?"))) {

                      private static final long serialVersionUID = 414272650677665672L;

                      @Override
                      protected void onConfirm(ClickEvent event) {
                        if (nodeFacade.moveNode(source, parent)) {
                          if (container.setParent(sourceItemId, parentItemId)) {
                            container.moveAfterSibling(sourceItemId, targetItemId);
                          }
                          CategoriesSettingsWindow.this.showInfo(
                              "Přesun kategorie proběhl úspěšně");
                        } else {
                          CategoriesSettingsWindow.this.showWarning(
                              "Nezdařilo se přesunout kategorii do vybraného místa");
                        }
                      }
                    });

                break;
            }
          }
        });
    tree.addListener(
        new Property.ValueChangeListener() {

          private static final long serialVersionUID = 191011037696709486L;

          public void valueChange(ValueChangeEvent event) {
            if (event.getProperty().getValue() != null) {
              // If something is selected from the tree, get it's 'name'
              // and
              // insert it into the textfield
              selectedNode.setValue((NodeDTO) event.getProperty().getValue());
              panel.setCaption(panelCaptionPrefix + selectedNode.getValue().getName());
            } else {
              selectedNode.setValue(null);
              panel.setCaption(panelCaptionPrefix + sectionRootCaption);
            }
          }
        });
    tree.addActionHandler(
        new Action.Handler() {

          private static final long serialVersionUID = -4835306347998186964L;

          public void handleAction(Action action, Object sender, final Object target) {
            final NodeDTO node = (NodeDTO) target;
            if (action == ACTION_DELETE) {

              addWindow(
                  new ConfirmSubwindow("Opravdu smazat kategorii '" + node.getName() + "' ?") {

                    private static final long serialVersionUID = 9193745051559434697L;

                    @Override
                    protected void onConfirm(ClickEvent event) {

                      if (!node.getContentNodes().isEmpty() || !node.getSubNodeIDs().isEmpty()) {
                        CategoriesSettingsWindow.this.showWarning("Kategorie musí být prázdná");
                      } else {
                        if (nodeFacade.deleteNode(node)) {
                          tree.removeItem(target);
                          CategoriesSettingsWindow.this.showInfo("Kategorie byla úspěšně smazána");
                        } else {
                          CategoriesSettingsWindow.this.showWarning(
                              "Nezdařilo se smazat vybranou kategorii");
                        }
                      }
                    }
                  });

            } else if (action == ACTION_RENAME) {
              final Window subwindow = new GrassSubWindow("Přejmenovat");
              subwindow.center();
              addWindow(subwindow);

              GridLayout subWindowlayout = new GridLayout(2, 2);
              subwindow.setContent(subWindowlayout);
              subWindowlayout.setMargin(true);
              subWindowlayout.setSpacing(true);

              final TextField newNameField = new TextField("Nový název:");
              newNameField.setValue(node.getName());
              newNameField.setRequired(true);
              newNameField.setRequiredError("Název kategorie nesmí být prázdný");
              subWindowlayout.addComponent(newNameField, 0, 0, 1, 0);

              Button confirm =
                  new Button(
                      "Přejmenovat",
                      new Button.ClickListener() {

                        private static final long serialVersionUID = 8490964871266821307L;

                        public void buttonClick(ClickEvent event) {
                          if (newNameField.isValid() == false) return;
                          if (nodeFacade.rename(node, (String) newNameField.getValue())) {
                            showInfo("Kategorie byla úspěšně přejmenována");
                            tree.getItem(node)
                                .getItemProperty(TreePropertyID.NÁZEV)
                                .setValue(newNameField.getValue());
                            node.setName((String) newNameField.getValue());
                          } else {
                            showWarning("Přejmenování se nezdařilo.");
                          }

                          (subwindow.getParent()).removeWindow(subwindow);
                        }
                      });

              subWindowlayout.addComponent(confirm, 0, 1);
              subWindowlayout.setComponentAlignment(confirm, Alignment.MIDDLE_CENTER);

              Button close =
                  new Button(
                      "Storno",
                      new Button.ClickListener() {

                        private static final long serialVersionUID = 8490964871266821307L;

                        public void buttonClick(ClickEvent event) {
                          (subwindow.getParent()).removeWindow(subwindow);
                        }
                      });

              subWindowlayout.addComponent(close, 1, 1);
              subWindowlayout.setComponentAlignment(close, Alignment.MIDDLE_CENTER);

              // Zaměř se na nové okno
              subwindow.focus();
            }
          }

          public Action[] getActions(Object target, Object sender) {
            return ACTIONS;
          }
        });

    createNewNodePanel(layout);

    return layout;
  }
 private void refreshTree() {
   tree.setContainerDataSource(getCategoriesContainer());
   tree.setItemCaptionPropertyId(TreePropertyID.NÁZEV);
   tree.setItemIconPropertyId(TreePropertyID.IKONA);
 }
  public void init(final Window main) {
    VerticalLayout mainLayout = new VerticalLayout();
    main.setContent(mainLayout);
    mainLayout.setSizeFull();

    HorizontalLayout titlebar = new HorizontalLayout();
    titlebar.addStyleName("titlebar");
    titlebar.setWidth("100%");
    Label title = new Label("Book of Vaadin Examples");
    title.addStyleName("title");
    titlebar.addComponent(title);
    titlebar.setComponentAlignment(title, Alignment.MIDDLE_RIGHT);
    Embedded logo = new Embedded(null, new ThemeResource("img/vaadin-logo.png"));
    titlebar.addComponent(logo);
    titlebar.setComponentAlignment(logo, Alignment.MIDDLE_RIGHT);
    main.addComponent(titlebar);

    HorizontalLayout hor = new HorizontalLayout();
    hor.setSizeFull();
    main.addComponent(hor);
    mainLayout.setExpandRatio(hor, 1.0f);

    final Panel menupanel = new Panel("Examples");
    menupanel.addStyleName("menupanel");
    menupanel.setWidth(null);
    menupanel.setHeight("100%");
    menupanel.getContent().setWidth(null);
    // menupanel.getContent().setHeight("100%");
    hor.addComponent(menupanel);

    final Tree menu = new Tree();
    menu.setWidth(null);
    // menu.setHeight("100%");
    menu.setImmediate(true);
    menupanel.addComponent(menu);

    final Panel viewpanel = new Panel("Selected Example");
    viewpanel.addStyleName("viewpanel");
    viewpanel.setSizeFull();
    VerticalLayout viewlayout = new VerticalLayout();
    viewlayout.addStyleName("viewlayout");
    viewlayout.setSpacing(true);
    viewlayout.setMargin(true);
    viewpanel.setContent(viewlayout);

    hor.addComponent(viewpanel);
    hor.setExpandRatio(viewpanel, 1.0f);

    WebApplicationContext ctx = (WebApplicationContext) getContext();
    BookExampleLibrary library = BookExampleLibrary.getInstance(ctx.getBaseDirectory());

    AbstractExampleItem[] examples = library.getAllExamples();

    // Collect redirects here
    final HashMap<String, String> redirects = new HashMap<String, String>();

    // Collect examples here
    final HashMap<String, CaptionedExampleItem> exampleitems =
        new HashMap<String, CaptionedExampleItem>();

    // Build the menu and collect redirections
    for (int i = 0; i < examples.length; i++)
      if (examples[i] instanceof BookExample || examples[i] instanceof ExampleCtgr) {
        CaptionedExampleItem example = (CaptionedExampleItem) examples[i];
        exampleitems.put(example.getExampleId(), example);

        String itemid = example.getExampleId();
        menu.addItem(itemid);
        menu.setItemCaption(itemid, example.getShortName());

        if (examples[i].getParentId() != null) menu.setParent(itemid, examples[i].getParentId());
      } else if (examples[i] instanceof RedirctItem) {
        RedirctItem redirect = (RedirctItem) examples[i];
        redirects.put(redirect.getExampleId(), redirect.redirectid);
      }

    // Expand the menu
    for (int i = 0; i < examples.length; i++) {
      if (examples[i].getParentId() == null)
        menu.expandItemsRecursively(examples[i].getExampleId());

      if (examples[i].isCollapsed()) menu.collapseItem(examples[i].getExampleId());

      if (menu.getChildren(examples[i].getExampleId()) == null)
        menu.setChildrenAllowed(examples[i].getExampleId(), false);
    }

    // Set selected example as given in the URI fragment
    final UriFragmentUtility urifu = new UriFragmentUtility();
    urifu.addListener(
        new FragmentChangedListener() {
          private static final long serialVersionUID = -6588416218607827834L;

          public void fragmentChanged(FragmentChangedEvent source) {
            String fragment = source.getUriFragmentUtility().getFragment();
            if (fragment != null) {
              // Handle redirection
              while (redirects.containsKey(fragment)) fragment = redirects.get(fragment);

              menu.setValue(fragment);

              // Open the tree nodes leading to the example
              for (Object parent = menu.getParent(fragment);
                  parent != null;
                  parent = menu.getParent(parent)) menu.expandItem(parent);
            }
          }
        });
    mainLayout.addComponent(urifu);

    // Handle menu selection
    menu.addListener(
        new Property.ValueChangeListener() {
          private static final long serialVersionUID = 8236533959795019956L;

          public void valueChange(ValueChangeEvent event) {
            viewpanel.removeAllComponents();

            String selection = (String) event.getProperty().getValue();

            // Find the example
            CaptionedExampleItem exampleItem = exampleitems.get(selection);
            if (selection != null && exampleItem == null)
              main.showNotification("Invalid item " + selection);
            else if (exampleItem != null) {
              if (exampleItem.getClass().isAssignableFrom(ExampleCtgr.class)) {
                if (menu.hasChildren(exampleItem.getExampleId())) {
                  menu.select((String) menu.getChildren(exampleItem.getExampleId()).toArray()[0]);
                }
              } else { // A leaf
                BookExample example = (BookExample) exampleItem;

                // Load unless already loaded
                WebApplicationContext ctx = (WebApplicationContext) getContext();
                example.loadExample(ctx.getBaseDirectory());

                if (example.getDescription() != null) {
                  Label descLabel = new Label(example.getDescription(), Label.CONTENT_XHTML);
                  descLabel.addStyleName("example-description");
                  viewpanel.addComponent(descLabel);
                }

                // The actual example component
                viewpanel.addComponent(example.createInstance());

                // Java sources on the left, CSS on the right
                HorizontalLayout horizontalOrder = new HorizontalLayout();
                horizontalOrder.addStyleName("sourcecontainer");
                horizontalOrder.setSpacing(true);
                horizontalOrder.setMargin(true);

                Panel bookRefs = null;
                Panel forumLinks = null;
                Panel kbRefs = null;

                List<SourceFragment> fragments = example.getSourceFragments();
                if (fragments != null) {
                  // Java Sources are laid out vertically
                  VerticalLayout verticalListings = new VerticalLayout();
                  verticalListings.setSizeUndefined();
                  verticalListings.setSpacing(true);
                  horizontalOrder.addComponent(verticalListings);

                  // Find the widest source fragment
                  int widestIndex = 0;
                  int widestWidth = 0;
                  for (int fragmentNum = 0; fragmentNum < fragments.size(); fragmentNum++)
                    if (fragments.get(fragmentNum).getSrcWidth() > widestWidth) {
                      widestIndex = fragmentNum;
                      widestWidth = fragments.get(fragmentNum).getSrcWidth();
                    }
                  System.out.println("Widest listing: " + widestIndex + " which is " + widestWidth);

                  for (int fragmentNum = 0; fragmentNum < fragments.size(); fragmentNum++) {
                    SourceFragment fragment = fragments.get(fragmentNum);

                    // Have caption only in the beginning of the listings
                    String listingCaption = fragmentNum == 0 ? "Source Code" : "";

                    String srcurl =
                        "http://dev.vaadin.com/browser/doc/book-examples/trunk/src"
                            + fragment.getSrcName();
                    SourceListing listing = new SourceListing(listingCaption, srcurl, fragment);
                    verticalListings.addComponent(listing);

                    // Use the width of the widest listing for all listings
                    if (fragmentNum == widestIndex) listing.setWidth(Sizeable.SIZE_UNDEFINED, 0);
                    else listing.setWidth("100%");

                    if (!fragment.getBookRefs().isEmpty()) {
                      bookRefs = new Panel("Book References");
                      bookRefs.setSizeUndefined();
                      for (Iterator<String> iter = fragment.getBookRefs().iterator();
                          iter.hasNext(); ) {
                        String ref = iter.next();
                        int hashPos = ref.indexOf('#');
                        String refFragment = "";
                        if (hashPos != -1) {
                          refFragment = "#" + ref.replace('#', '.');
                          ref = ref.substring(0, hashPos);
                        }
                        String bookUrl =
                            "http://vaadin.com/book/-/page/" + ref + ".html" + refFragment;
                        Link link = new Link(bookUrl, new ExternalResource(bookUrl));
                        link.setTargetName("_new");
                        bookRefs.addComponent(link);
                      }
                    }

                    if (!fragment.getForumLinks().isEmpty()) {
                      forumLinks = new Panel("Forum Messages");
                      forumLinks.setSizeUndefined();
                      for (Iterator<String> iter = fragment.getForumLinks().iterator();
                          iter.hasNext(); ) {
                        String url = iter.next();
                        Link link = new Link(url, new ExternalResource(url));
                        link.setTargetName("_new");
                        forumLinks.addComponent(link);
                      }
                    }

                    if (!fragment.getKbRefs().isEmpty()) {
                      kbRefs = new Panel("Pro Account Knowledge Base Articles");
                      kbRefs.setSizeUndefined();
                      for (Iterator<SourceFragment.Ref> iter = fragment.getKbRefs().iterator();
                          iter.hasNext(); ) {
                        SourceFragment.Ref ref = iter.next();
                        String url = "http://vaadin.com/knowledge-base#" + ref.ref;
                        Link link = new Link(ref.caption, new ExternalResource(url));
                        link.setTargetName("_new");
                        forumLinks.addComponent(link);
                      }
                    }
                  }
                }

                // Show associated CSS
                if (example.getCssFragments() != null && example.getCssFragments().size() > 0) {
                  SourceFragment csscode = example.getCssFragments().get(0);
                  String srcurl =
                      "http://dev.vaadin.com/browser/doc/book-examples/trunk/WebContent/VAADIN/themes/book-examples/styles.css";
                  horizontalOrder.addComponent(new SourceListing("CSS Code", srcurl, csscode));
                }

                if (horizontalOrder.getComponentIterator().hasNext())
                  viewpanel.addComponent(horizontalOrder);
                if (bookRefs != null) viewpanel.addComponent(bookRefs);
                if (forumLinks != null) viewpanel.addComponent(forumLinks);
                if (kbRefs != null) viewpanel.addComponent(kbRefs);

                urifu.setFragment(example.getExampleId());
              }
            }
          }
        });

    Tree.ItemStyleGenerator itemStyleGenerator =
        new Tree.ItemStyleGenerator() {
          private static final long serialVersionUID = -3231268865512947125L;

          public String getStyle(Object itemId) {
            // Chapter title items do not contain a period
            if (!((String) itemId).contains(".")) return "chaptertitle";
            return null;
          }
        };
    menu.setItemStyleGenerator(itemStyleGenerator);
  }
  @Override
  protected void setup() {

    HorizontalLayout h = new HorizontalLayout();
    addComponent(h);

    Table table = new Table();
    table.addContainerProperty("Column 1", String.class, "Row");
    table.setDragMode(TableDragMode.ROW);

    table.addItem("Row 1");
    table.addItem("Row 2");
    table.addItem("Row 3");
    table.addItem("Row 4");
    table.addItem("Row 5");
    table.addItem("Row 6");
    table.addItem("Row 7");

    h.addComponent(table);

    final Tree tree = new Tree();
    tree.setDropHandler(
        new DropHandler() {

          public AcceptCriterion getAcceptCriterion() {
            return TargetItemAllowsChildren.get();
          }

          public void drop(DragAndDropEvent dropEvent) {
            // criteria verify that this is safe
            DataBoundTransferable t = (DataBoundTransferable) dropEvent.getTransferable();
            Container sourceContainer = t.getSourceContainer();
            Object sourceItemId = t.getItemId();
            System.out.println(sourceItemId);

            AbstractSelectTargetDetails dropData =
                ((AbstractSelectTargetDetails) dropEvent.getTargetDetails());
            Object targetItemId = dropData.getItemIdOver();

            // move item from table to category'
            tree.addItem(sourceItemId);
            tree.setParent(sourceItemId, targetItemId);
            tree.setChildrenAllowed(sourceItemId, false);
            sourceContainer.removeItem(sourceItemId);
          }
        });

    tree.addItem("Item 1");
    tree.addItem("Item 11");
    tree.setChildrenAllowed("Item 11", false);
    tree.setParent("Item 11", "Item 1");
    tree.addItem("Item 12");
    tree.setChildrenAllowed("Item 12", false);
    tree.setParent("Item 12", "Item 1");
    tree.addItem("Item 13");
    tree.setChildrenAllowed("Item 13", false);
    tree.setParent("Item 13", "Item 1");

    tree.addItem("Item 2");
    tree.addItem("Item 21");
    tree.setChildrenAllowed("Item 21", false);
    tree.setParent("Item 21", "Item 2");
    tree.addItem("Item 22");
    tree.setChildrenAllowed("Item 22", false);
    tree.setParent("Item 22", "Item 2");
    tree.addItem("Item 23");
    tree.setChildrenAllowed("Item 23", false);
    tree.setParent("Item 23", "Item 2");

    tree.addItem("Item 3");
    tree.addItem("Item 31");
    tree.setChildrenAllowed("Item 31", false);
    tree.setParent("Item 31", "Item 3");
    tree.addItem("Item 32");
    tree.setChildrenAllowed("Item 32", false);
    tree.setParent("Item 32", "Item 3");
    tree.addItem("Item 33");
    tree.setChildrenAllowed("Item 33", false);
    tree.setParent("Item 33", "Item 3");

    tree.expandItemsRecursively("Item 1");
    tree.expandItemsRecursively("Item 2");
    tree.expandItemsRecursively("Item 3");

    h.addComponent(tree);
  }
Пример #10
0
  @Override
  protected void setup() {
    instance = this; // Note, test only works with single app per server if
    // get()
    // not converted to thread local

    sp = new HorizontalSplitPanel();
    sp.setSplitPosition(20);
    CssLayout l = new CssLayout();
    sp.setFirstComponent(l);

    tree1 = new Tree("Volume 1");
    tree1.setImmediate(true);

    fs1 = new BeanItemContainer<File>(File.class);
    tree1.setContainerDataSource(fs1);
    for (int i = 0; i < files.length; i++) {
      fs1.addBean(files[i]);
      if (files[i] instanceof Folder) {
        tree1.setChildrenAllowed(files[i], true);
      } else {
        tree1.setChildrenAllowed(files[i], false);
      }
      if (i >= files.length / 2) {
        tree1.setParent(files[i], files[i - files.length / 2]);
      }
    }
    tree1.setItemCaptionPropertyId("name");
    tree1.setItemIconPropertyId("icon");

    tree1.setDragMode(TreeDragMode.NODE);

    DropHandler dropHandler =
        new DropHandler() {
          @Override
          public AcceptCriterion getAcceptCriterion() {
            return AcceptAll.get();
          }

          @Override
          public void drop(DragAndDropEvent dropEvent) {
            File file = null;
            Folder folder = null;
            TreeTargetDetails dropTargetData = (TreeTargetDetails) dropEvent.getTargetDetails();
            folder = (Folder) dropTargetData.getItemIdInto();
            if (dropEvent.getTransferable() instanceof DataBoundTransferable) {
              DataBoundTransferable transferable =
                  (DataBoundTransferable) dropEvent.getTransferable();
              file = (File) transferable.getItemId();
            } else if (dropEvent.getTransferable().getSourceComponent() instanceof FileIcon) {
              FileIcon draggedIcon = (FileIcon) dropEvent.getTransferable().getSourceComponent();
              file = draggedIcon.file;
            }
            setParent(file, folder);
          }
        };

    tree1.setDropHandler(dropHandler);

    Handler actionHandler =
        new Handler() {

          private Action[] actions = new Action[] {new Action("Remove")};

          @Override
          public void handleAction(Action action, Object sender, Object target) {
            ContainerHierarchicalWrapper containerDataSource =
                (ContainerHierarchicalWrapper) tree1.getContainerDataSource();
            containerDataSource.removeItemRecursively(target);
          }

          @Override
          public Action[] getActions(Object target, Object sender) {
            return actions;
          }
        };
    tree1.addActionHandler(actionHandler);

    tree1.addListener(
        new Property.ValueChangeListener() {
          @Override
          public void valueChange(ValueChangeEvent event) {
            Object value = event.getProperty().getValue();
            if (value != null && !(value instanceof Folder)) {
              value = tree1.getParent(value);
            }
            FolderView folderView = FolderView.get((Folder) value);
            sp.setSecondComponent(folderView);
            folderView.reload();
          }
        });

    l.addComponent(tree1);

    sp.setSecondComponent(FolderView.get(null));

    getLayout().setSizeFull();
    getLayout().addComponent(sp);
    TestUtils.injectCSS(
        getLayout().getUI(),
        ""
            + ".v-tree .v-icon {height:16px;} "
            + ".v-tree-node-caption-drag-top {/*border-top: none;*/} "
            + ".v-tree-node-caption-drag-bottom {border-bottom: none ;} "
            + ".v-tree-node-caption-drag-center {background-color: transparent;}"
            + ".v-tree-node-caption-dragfolder { background-color: cyan;} ");
  }
Пример #11
0
  private void sortAddToTree(Object sid) {
    //        // sort session elements
    //		List<TestSession> caseSessions = parentCase.getSessions();
    //		List<Integer> sortedids = new ArrayList<Integer>();
    //		for (TestSession s : caseSessions){
    //			sortedids.add(s.getId());
    //			// remove tree items
    //			tree.removeItem(s.getId());
    //		}
    //		Collections.sort(sortedids);
    //		Collections.reverse(sortedids);
    //		System.out.println("SORTED ID's: " + sortedids);

    List<Object> sortedids = new ArrayList<Object>();
    for (Object child : tree.getChildren(parentcase.getId())) {
      sortedids.add(child);
    }

    for (Object s : sortedids) {
      // remove tree items
      tree.removeItem(s);
    }

    // add new item and then re-add old items
    tree.addItem(sid);
    tree.setParent(sid, parentcase.getId());
    tree.setChildrenAllowed(sid, false);
    tree.setItemCaption(sid, sessions.getItem(sid).getEntity().getTitle()); // newsession.getTitle()
    tree.expandItem(parentcase.getId());
    tree.select(sid);

    for (Object id : sortedids) { // testcase.getSessions()	matchingsessions
      Object sessionid = sessions.getItem(id).getEntity().getId();
      tree.addItem(sessionid);
      tree.setItemCaption(sessionid, sessions.getItem(id).getEntity().getTitle());
      tree.setParent(sessionid, parentcase.getId());
      tree.setChildrenAllowed(sessionid, false);
    }
  }
Пример #12
0
  public void buttonClick(ClickEvent event) {
    if (event.getButton() == createButton) {

      TestSession queriedSession = null;
      String wrongTitle = "";

      try {
        //						form.enableValidationMessages();
        //					title.setValidationVisible(true);

        // commit the fieldgroup
        binder.commit();

        // check SESSION title doesnt exist for THIS SESSION
        int id = 0;
        boolean titleOK = true;
        id = newSessionItem.getBean().getId(); // testsession.getId();
        // System.out.println("parentCase.getSessions() : " + parentcase.getSessions());
        for (TestSession s : parentcase.getSessions()) { // sessions.getItemIds()
          // System.out.println("Existing title -> new title : " + s.getTitle() + "->" +
          // testsession.getTitle());
          // System.out.println("Existing id -> new id : " + s.getId() + "->" + id);
          if (s.getTitle().equals(testsession.getTitle()) && !(s.getId() == id)) {
            testsession.setTitle(prevTitle);
            if (clonemode != true && editmode == true) {
              sessions.addEntity(testsession);
            }
            wrongTitle = s.getTitle();

            titleOK = false;
            break;
          }
        }

        if (titleOK == true) {
          // System.out.println("TITLE WAS FINE. EDITING");

          // add NEW bean object to db through jpa container
          if (editmode == false && (clonemode == false)) {

            // add to container
            sessions.addEntity(newSessionItem.getBean()); // jpa container

            // add created item to tree (after retrieving db generated id)
            EntityManager em =
                Persistence.createEntityManagerFactory("mbpet").createEntityManager();
            Query query =
                em.createQuery(
                    "SELECT OBJECT(t) FROM TestSession t WHERE t.title = :title AND t.parentcase = :parentcase");
            //		            query.setParameter("title", newsession.getTitle());
            query.setParameter("title", testsession.getTitle());
            query.setParameter("parentcase", testsession.getParentcase()); // MainView.sessionUser
            queriedSession = (TestSession) query.getSingleResult();
            //				            queriedSession = (TestSession) query.setParameter("title",
            // testsession.getTitle()).getSingleResult();
            // System.out.println("the generated id is: " + queriedSession.getId());
            id = queriedSession.getId(); // here is the id we need for tree

            // create session directory for test and reports
            new FileSystemUtils()
                .createSessionTestDir(
                    testsession.getParentcase().getOwner().getUsername(),
                    testsession.getParentcase().getTitle(),
                    testsession.getTitle());

            // create default parameters object
            new ParametersEditor(sessions.getItem(id).getEntity());

            // create empty adapter object
            new AdapterEditor(sessions.getItem(id).getEntity());

            // create empty adapterXML object
            new AdapterXMLEditor(sessions.getItem(id).getEntity());

            // create default models
            ModelUtils modelUtils = new ModelUtils();
            modelUtils.createDefaultModel(
                "user_types", sessions.getItem(id).getEntity()); // currmodel.getParentsession(),
            modelUtils.createDefaultModel(
                "normal_user", sessions.getItem(id).getEntity()); // currmodel.getParentsession(),

            // add to tree in right order
            if (tree.hasChildren(parentcase.getId())) {
              sortAddToTree(id);
            } else {
              tree.addItem(id);
              tree.setParent(id, parentcase.getId());
              tree.setChildrenAllowed(id, false);
              tree.setItemCaption(
                  id, sessions.getItem(id).getEntity().getTitle()); // newsession.getTitle()
              tree.expandItem(parentcase.getId());
              tree.select(id);
            }

            // update parent Case to add Session to testCase List<Session> sessions
            parentcase.addSession(queriedSession);
            testcases.addEntity(parentcase);
            //              	  	List<TestSession> listofsessions = parentCase.getSessions();
            //              	  	listofsessions.add(queriedSession);
            //	//sessions.getItem(id).getEntity()
            //              	  	parentCase.setSessions(listofsessions);

            //									System.out.println("WHAT IS NEW LIST OF SESSIONS: "
            //													+ parentcase.getSessions()); // testing purposes
            //									for (TestSession s : parentcase.getSessions()) {
            //										System.out.println(s.getId() + " - "
            //												+ s.getTitle()); // testing purposes
            //									}

          } else if (editmode == true) {
            // EDIT existing object

            //								// commit the fieldgroup
            //								binder.commit();

            // 1 UPDATE parentcase reference
            parentcase.updateSessionData(sessions.getItem(testsession.getId()).getEntity());

            // System.out.println("Test session is now: " + testsession.getTitle());

            // 2 UPDATE container
            sessions.addEntity(newSessionItem.getBean());
            // System.out.println("Entity is now: " +
            // sessions.getItem(testsession.getId()).getEntity().getTitle());

            // 3 UPDATE tree title
            tree.setItemCaption(
                testsession.getId(), sessions.getItem(testsession.getId()).getEntity().getTitle());

            // 4. UPDATE models (maybe not necessary)
            //
            //	ModelEditorTable.modelsTable.setContainerDataSource(ModelEditorTable.modelsTable.getContainerDataSource());
            //			              	  	for (Model m : testsession.getModels()) {
            //
            //	m.setParentsession(sessions.getItem(testsession.getId()).getEntity());
            //			              	  		System.out.println("Sessions' model's session title: " +
            // m.getParentsession().getTitle());
            ////
            //	m.updateSessionData(sessions.getItem(testsession.getId()).getEntity());
            //			              	  	}

            // edit session directory for test and reports
            if (!prevTitle.equals(testsession.getTitle())) {
              new FileSystemUtils()
                  .renameSessionDir(
                      testsession.getParentcase().getOwner().getUsername(),
                      testsession.getParentcase().getTitle(),
                      prevTitle,
                      testsession.getTitle());
            }

            //			              	  	// update parameters and adapter ?
            // System.out.println("Sessions' params's session title: " +
            // testsession.getParameters().getOwnersession().getTitle());
            // System.out.println("Sessions' adapter session title: " +
            // testsession.getAdapter().getOwnersession().getTitle());
            // System.out.println("Sessions' adapterXML session title: " +
            // testsession.getAdapterXML().getOwnersession().getTitle());

            id = testsession.getId();

          } else if (clonemode == true) {
            // CLONE
            // System.out.println("\n\nWE ARE IN CLONE MODE!!!!!!!!!\n\n");

            //							TestSession clone = newSessionItem.getBean();
            //								// 1 commit the fieldgroup
            //								binder.commit();

            // 2 add to container
            sessions.addEntity(newSessionItem.getBean()); // jpa container

            // 3 retrieving db generated id
            EntityManager em =
                Persistence.createEntityManagerFactory("mbpet").createEntityManager();
            Query query =
                em.createQuery("SELECT OBJECT(t) FROM TestSession t WHERE t.title = :title");
            //		            query.setParameter("title", newsession.getTitle());
            queriedSession =
                (TestSession) query.setParameter("title", testsession.getTitle()).getSingleResult();
            // System.out.println("the generated id is: " + queriedSession.getId());
            id = queriedSession.getId(); // here is the id we need for tree

            // 4 clone models
            EntityManager em2 =
                Persistence.createEntityManagerFactory("mbpet").createEntityManager();
            Query query2 =
                em2.createQuery(
                    "SELECT OBJECT(m) FROM Model m WHERE m.title = :title AND m.parentsession = :parentsession");
            for (Model m : subject.getModels()) {
              // copy over model values
              Model newmodel =
                  new Model(m.getTitle(), queriedSession, m.getParentsut()); // "(clone) " +
              newmodel.setDotschema(m.getDotschema());

              // add to container
              models.addEntity(newmodel); // jpa container

              // retrieve generated id from db
              query2.setParameter("title", newmodel.getTitle());
              query2.setParameter("parentsession", queriedSession);
              Model queriedModel = (Model) query2.getSingleResult();
              // System.out.println("the generated MODEL id is: " + queriedModel.getId() + " of
              // session ->" + queriedSession.getId());

              // update parent Case to add Session to testCase List<Session> sessions
              parentcase.addModel(queriedModel);
              queriedSession.addModel(queriedModel);

              //						            //write model to disk
              //						            FileSystemUtils fileUtils = new FileSystemUtils();
              //						            fileUtils.writeModelToDisk(
              //						            		parentcase.getOwner().getUsername(),
              //						            		parentcase.getTitle(),
              //						            		queriedSession.getTitle(),
              //						            		queriedSession.getParameters().getModels_folder(),
              //						            		queriedModel);
            }
            sessions.addEntity(queriedSession);

            // 5 clone parameters
            String cloneParams =
                "Fill in parameters for Test Session '" + queriedSession.getTitle() + "'";
            if (!(subject.getParameters().getSettings_file()
                == null)) { // || !(testsession.getParameters().getSettings_file().equals(""))
              cloneParams = subject.getParameters().getSettings_file();
            }
            //					            System.out.println("\n\n the cloned parameters are:\n" +
            //					            		cloneParams + "\n\n");
            new ParametersEditor(queriedSession, cloneParams);

            // 6 clone adapter.py
            String cloneAdapter =
                "Fill in adapter for Test Session '" + queriedSession.getTitle() + "'";
            if (!(subject.getAdapter().getAdapter_file() == null)
                || !(subject
                    .getAdapter()
                    .getAdapter_file()
                    .equals(
                        ""))) { // || !(testsession.getParameters().getSettings_file().equals(""))
              cloneAdapter = subject.getAdapter().getAdapter_file();
            }
            //					            System.out.println("\n\n the cloned adapter is:\n" +
            //					            		cloneAdapter + "\n\n");
            new AdapterEditor(queriedSession, cloneAdapter);

            // 7 clone adapter.xml
            String cloneAdapterXML =
                "Fill in adapterXML for Test Session '" + queriedSession.getTitle() + "'";
            if (!(subject.getAdapterXML().getAdapterXML_file() == null)
                || !(subject
                    .getAdapterXML()
                    .getAdapterXML_file()
                    .equals(
                        ""))) { // || !(testsession.getParameters().getSettings_file().equals(""))
              cloneAdapterXML = subject.getAdapterXML().getAdapterXML_file();
            }
            //					            System.out.println("\n\n the cloned adapterXML is:\n" +
            //					            		cloneAdapterXML + "\n\n");
            new AdapterXMLEditor(queriedSession, cloneAdapterXML);

            // 8 write models to disk
            FileSystemUtils fileUtils = new FileSystemUtils();
            fileUtils.writeModelsToDisk(
                parentcase.getOwner().getUsername(),
                parentcase.getTitle(),
                queriedSession.getTitle(),
                queriedSession.getParameters().getModels_folder(),
                subject.getModels());

            // 9 add to tree in right order
            if (tree.hasChildren(parentcase.getId())) {
              sortAddToTree(id);
            } else {
              tree.addItem(id);
              tree.setParent(id, parentcase.getId());
              tree.setChildrenAllowed(id, false);
              tree.setItemCaption(
                  id, sessions.getItem(id).getEntity().getTitle()); // newsession.getTitle()
              tree.expandItem(parentcase.getId());
              tree.select(id);
            }

            // 10 update parent Case to add Session to testCase List<Session> sessions
            parentcase.addSession(queriedSession);
            //              	  	List<TestSession> listofsessions = parentCase.getSessions();
            //              	  	listofsessions.add(queriedSession);
            //	//sessions.getItem(id).getEntity()
            //              	  	parentCase.setSessions(listofsessions);

            // 9 create session directory for test and reports
            new FileSystemUtils()
                .createSessionTestDir(
                    queriedSession.getParentcase().getOwner().getUsername(),
                    queriedSession.getParentcase().getTitle(),
                    queriedSession.getTitle());

            //				            	System.out.println("WHAT IS NEW LIST OF SESSIONS: " +
            // parentCase.getSessions()); // testing purposes
            //				            	for (TestSession s : parentCase.getSessions()) {
            //					            	System.out.println(s.getId() + " - " + s.getTitle()); // testing
            // purposes
            //				            	}
          }

          //			            	System.out.println("WHAT IS NEW LIST OF SESSIONS: " +
          // parentCase.getSessions()); // testing purposes
          //			            	for (TestSession s : parentCase.getSessions()) {
          //				            	System.out.println(s.getId() + " - " + s.getTitle()); // testing
          // purposes
          //			            	}

          if (clonemode == true && navToCasePage == true) {
            confirmNotification(queriedSession.getTitle(), "was created");
            close();

          } else if (clonemode == true && navToCasePage == false) {
            confirmNotification(queriedSession.getTitle(), "was CLONED");
            getUI()
                .getNavigator()
                .navigateTo(
                    MainView.NAME
                        + "/"
                        + parentcase.getTitle()
                        + "/"
                        + queriedSession.getTitle()
                        + "id="
                        + queriedSession
                            .getId()); // sessions.getItem(id).getEntity()
            close();

          } else if (navToCasePage == true && editmode == false) {
            // 4 UPDATE table title
            table.select(newSessionItem.getBean().getId()); // (testsession.getId());
            confirmNotification(testsession.getTitle(), "was created");
            close();

            //		            		getUI().getNavigator()
            //		            			.navigateTo(MainView.NAME + "/" +
            //		            				parentCase.getTitle());		//sessions.getItem(id).getEntity()

          } else if (navToCasePage == true && editmode == true) {
            getUI()
                .getNavigator()
                .navigateTo(
                    MainView.NAME
                        + "/"
                        + parentcase.getTitle()
                        + "-sut="
                        + parentcase.getId()); // sessions.getItem(id).getEntity()		            	
            confirmNotification(testsession.getTitle(), "was edited");
            close();

          } else if (editmode == true && navToCasePage == false) {
            getUI()
                .getNavigator()
                .navigateTo(
                    MainView.NAME
                        + "/"
                        + parentcase.getTitle()
                        + "/"
                        + newSessionItem.getBean().getTitle()
                        + "id="
                        + newSessionItem
                            .getBean()
                            .getId()); // testsession.getTitle() sessions.getItem(id).getEntity()
          } else {
            getUI()
                .getNavigator()
                .navigateTo(
                    MainView.NAME
                        + "/"
                        + parentcase.getTitle()
                        + "/"
                        + queriedSession.getTitle()
                        + "id="
                        + queriedSession
                            .getId()); // testsession.getTitle() sessions.getItem(id).getEntity()
          }

          // title already existed
        } else {
          // System.out.println("title was NOT fine.");
          //							testsession = sessions.getItem(id).getEntity();
          //							System.out.println("db session is: " + testsession.getId() + " " +
          // testsession.getTitle());

          if (editmode == false && clonemode == false) {
            binder.discard();
            Notification.show(
                "The title '"
                    + wrongTitle
                    + "' already exists for this SUT. Please rename this session.",
                Type.ERROR_MESSAGE); // testsession.getTitle()
            UI.getCurrent().addWindow(new TestSessionEditor(tree, table, parentcase, true));
          } else if (editmode == true) {
            binder.discard();
            Notification.show(
                "The title '"
                    + wrongTitle
                    + "' already exists for this SUT. Please rename this session.",
                Type.ERROR_MESSAGE);
            if (navToCasePage == true) {
              UI.getCurrent()
                  .addWindow(
                      new TestSessionEditor(
                          tree,
                          id,
                          parentcase,
                          table)); // sessions.getItem(testsession.getId()).getEntity().getId()
            } else {
              UI.getCurrent().addWindow(new TestSessionEditor(tree, id, parentcase));
            }

          } else if (clonemode == true) {
            binder.discard();
            Notification.show(
                "The title '"
                    + wrongTitle
                    + "' already exists for this SUT. Please rename this session.",
                Type.ERROR_MESSAGE);
            UI.getCurrent()
                .addWindow(
                    new TestSessionEditor(
                        tree,
                        subject.getId(), // testsession sessions.getItem(
                        parentcase,
                        table,
                        true));
          }
        }

      } catch (CommitException e) {
        binder.discard();
        Notification.show("'Title' cannot be Empty. Please try again.", Type.WARNING_MESSAGE);
        UI.getCurrent().addWindow(new TestSessionEditor(tree, parentcase, true));
      } catch (NonUniqueResultException e) {
        e.printStackTrace();
        binder.discard();
        Notification.show(
            "The title '"
                + testsession.getTitle()
                + "' already exists for this SUT. Please rename this session.",
            Type.ERROR_MESSAGE);
        UI.getCurrent().addWindow(new TestSessionEditor(tree, parentcase, true));
      }
      //					catch (NonUniqueResultException e) {
      //						binder.discard();
      //						Notification.show("'Title' must be a unique name.\n'" +
      //											queriedSession.getTitle() +
      //											"' already exists.\n\nPlease try again.", Type.WARNING_MESSAGE);
      //						UI.getCurrent().addWindow(new TestSessionEditor(tree, parentCase));
      //					}

    } else if (event.getButton() == cancelButton) {
      binder.discard();
    }
    //	        binder.clear();
    //	        form.disableValidationMessages();
    //	        setTreeItemsExpanded();

    close(); // Close the sub-window
  }