Bookmark Organizer : Tree « SWT JFace Eclipse « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Class
8. Collections Data Structure
9. Data Type
10. Database SQL JDBC
11. Design Pattern
12. Development Class
13. EJB3
14. Email
15. Event
16. File Input Output
17. Game
18. Generics
19. GWT
20. Hibernate
21. I18N
22. J2EE
23. J2ME
24. JDK 6
25. JNDI LDAP
26. JPA
27. JSP
28. JSTL
29. Language Basics
30. Network Protocol
31. PDF RTF
32. Reflection
33. Regular Expressions
34. Scripting
35. Security
36. Servlets
37. Spring
38. Swing Components
39. Swing JFC
40. SWT JFace Eclipse
41. Threads
42. Tiny Application
43. Velocity
44. Web Services SOA
45. XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java » SWT JFace Eclipse » TreeScreenshots 
Bookmark Organizer
Bookmark Organizer


/*******************************************************************************
 * All Right Reserved. Copyright (c) 1998, 2004 Jackwind Li Guojie
 
 * Created on 2004-4-27 16:53:36 by JACK $Id$
 *  
 ******************************************************************************/



import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.ByteArrayTransfer;
import org.eclipse.swt.dnd.TransferData;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceAdapter;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;


/**
 * Represents a bookmark.
 *
 */
class Bookmark {
  public String name;
  public String href;
  public String addDate;
  public String lastVisited;
  public String lastModified;
}

public class BookmarkOrganizer {
  private static String folderLinePrefix = "<DT><H3 FOLDED";
  private static String urlLinePrefix = "<DT><A HREF";
  private static Pattern folderPattern = Pattern.compile("\"(\\d+)\">(.*)<");
  private static Pattern urlPattern =
    Pattern.compile("\"(.*)\".*\"(.*)\".*\"(.*)\".*\"(.*)\">(.*)<");

  private static String KEY_ADD_DATE = "ADD_DATE";
  private static String KEY_HREF = "HREF";
  private static String KEY_LAST_VISITED = "LAST_VISITED";
  private static String KEY_LAST_MODIFIED = "LAST_MODIFIED";

  Display display = new Display();
  Shell shell = new Shell(display);

  Tree tree;
  Label label;

  TreeItem rootItem;

  Image iconRoot = new Image(display, "java2s.gif");
  Image iconFolder = new Image(display, "java2s.gif");
  Image iconURL = new Image(display, "java2s.gif");

  TreeItem dragSourceItem;

  public BookmarkOrganizer() {
    shell.setText("Bookmark organizer");
    shell.setLayout(new GridLayout(1true));

    ToolBar toolBar = new ToolBar(shell, SWT.FLAT);
    ToolItem itemOpen = new ToolItem(toolBar, SWT.PUSH);
    itemOpen.setText("Load");
    itemOpen.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        FileDialog dialog = new FileDialog(shell, SWT.OPEN);
        String file = dialog.open();
        if (file != null) {
          // removes existing items.
          TreeItem[] items = rootItem.getItems();
          for (int i = 0; i < items.length; i++)
            items[i].dispose();

          loadBookmark(new File(file), rootItem);
          setStatus("Bookmarks loaded successfully");
        }
      }
    });

    ToolItem itemSave = new ToolItem(toolBar, SWT.PUSH);
    itemSave.setText("Save as");
    itemSave.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        FileDialog dialog = new FileDialog(shell, SWT.SAVE);
        String file = dialog.open();
        if (file != null) {
          try {
            BufferedWriter writer =
              new BufferedWriter(new FileWriter(file));
            saveBookmark(writer, rootItem);
            writer.close();
            setStatus(
              "Bookmarks saved successfully to file: " + file);
          catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    });

    tree = new Tree(shell, SWT.BORDER);
    tree.setLayoutData(new GridData(GridData.FILL_BOTH));
    rootItem = new TreeItem(tree, SWT.NULL);
    rootItem.setText("BOOKMARKS");
    rootItem.setImage(iconRoot);

    label = new Label(shell, SWT.BORDER);
    label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    final DragSource dragSource =
      new DragSource(tree, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK);
    dragSource.setTransfer(
      new Transfer[] { BookmarkTransfer.getInstance()});

    dragSource.addDragListener(new DragSourceAdapter() {
      public void dragStart(DragSourceEvent event) {
        TreeItem[] selection = tree.getSelection();
        // Only a URL bookmark can be dragged.
        if (selection.length > && selection[0].getData() != null) {
          event.doit = true;
          dragSourceItem = selection[0];
        else {
          event.doit = false;
        }
      };

      public void dragSetData(DragSourceEvent event) {
        if (BookmarkTransfer
          .getInstance()
          .isSupportedType(event.dataType))
          event.data = dragSourceItem.getData();
      }

      public void dragFinished(DragSourceEvent event) {
        if (event.detail == DND.DROP_MOVE)
          dragSourceItem.dispose();
        dragSourceItem = null;
      }

    });

    final DropTarget dropTarget =
      new DropTarget(tree, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK);
    dropTarget.setTransfer(
      new Transfer[] { BookmarkTransfer.getInstance()});
    dropTarget.addDropListener(new DropTargetAdapter() {
      public void dragOver(DropTargetEvent event) {
        event.feedback =
          DND.FEEDBACK_EXPAND
            | DND.FEEDBACK_SCROLL
            | DND.FEEDBACK_SELECT;
      }

      public void dropAccept(DropTargetEvent event) {
        // can only drops into to a folder
        if (event.item == null
          || ((TreeItemevent.item).getData() != null)
          event.detail = DND.DROP_NONE;
      }

      public void drop(DropTargetEvent event) {
        try {
          if (event.data == null) {
            event.detail = DND.DROP_NONE;
            return;
          }

          TreeItem item =
            new TreeItem((TreeItemevent.item, SWT.NULL);
          Bookmark bookmark = (Bookmarkevent.data;
          item.setText(bookmark.name);
          item.setImage(iconURL);
          item.setData(bookmark);
        catch (RuntimeException e) {
          e.printStackTrace();
        }
      }
    });

    tree.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent e) {
        TreeItem item = (TreeIteme.item;
        Bookmark bookmark = (Bookmarkitem.getData();
        if (bookmark != null) {
          setStatus(bookmark.href);
        else if (item.getData(KEY_ADD_DATE!= null) { // folder.
          setStatus("Folder: " + item.getText());
        }
      }
    });

    shell.setSize(400300);
    shell.open();
    //textUser.forceFocus();

    loadBookmark(new File("icons/mybookmark.htm"), rootItem);

    // Set up the event loop.
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        // If no more entries in event queue
        display.sleep();
      }
    }

    display.dispose();
  }

  /**
   * Writes the bookmark(s) into the given buffered writer. 
   @param writer
   @param item
   @throws IOException
   */
  private void saveBookmark(BufferedWriter writer, TreeItem item)
    throws IOException {
    if (item.getData() == null
      && item.getData(KEY_ADD_DATE== null) { // root item.
      writer.write(
        "<!DOCTYPE NETSCAPE-Bookmark-file-1>\n"
          "<!-- This is an automatically generated file.\n"
          "It will be read and overwritten.\n"
          "Do Not Edit! -->\n"
          "<TITLE>Bookmarks</TITLE>\n"
          "<H1>Bookmarks</H1>\n"
          "<DL><p>\n");

      TreeItem[] items = item.getItems();
      for (int i = 0; i < items.length; i++)
        saveBookmark(writer, items[i]);

      writer.write("</DL><p>\n");
    else if (item.getData() == null) { // folder
      writer.write(
        "\t<DT><H3 FOLDED ADD_DATE=\""
          + item.getData(KEY_ADD_DATE)
          "\">"
          + item.getText()
          "</H3>\n");
      writer.write("\t<DL><p>\n");

      TreeItem[] items = item.getItems();
      for (int i = 0; i < items.length; i++)
        saveBookmark(writer, items[i]);

      writer.write("\t</DL><p>\n");

    else // url.
      Bookmark bookmark = (Bookmarkitem.getData();
      writer.write(
        "\t\t<DT><A HREF=\""
          + bookmark.href
          "\" ADD_DATE=\""
          + bookmark.addDate
          "\" LAST_VISIT=\""
          + bookmark.lastVisited
          "\" LAST_MODIFIED=\" +"
          + bookmark.lastModified
          "\">"
          + bookmark.name
          "</A>\n");
    }
  }

  /**
   * Loads the bookmarks from the specified file. 
   @param file
   @param rootItem
   */
  private void loadBookmark(File file, TreeItem rootItem) {
    TreeItem parent = rootItem;

    try {
      BufferedReader reader = new BufferedReader(new FileReader(file));
      String line = null;
      while ((line = reader.readLine()) != null) {
        line = line.trim();
        if (line.startsWith(folderLinePrefix)) { // a folder.
          Matcher matcher = folderPattern.matcher(line);
          if (matcher.find()) {
            String addDate = matcher.group(1);
            String name = matcher.group(2);

            TreeItem item = new TreeItem(parent, SWT.NULL);
            item.setText(name);
            item.setData(KEY_ADD_DATE, addDate);
            item.setImage(iconFolder);
            parent = item;
          }
        else if (line.startsWith(urlLinePrefix)) { // a url
          Matcher matcher = urlPattern.matcher(line);
          if (matcher.find()) {
            Bookmark bookmark = new Bookmark();
            bookmark.href = matcher.group(1);
            bookmark.addDate = matcher.group(2);
            bookmark.lastVisited = matcher.group(3);
            bookmark.lastModified = matcher.group(4);
            bookmark.name = matcher.group(5);

            TreeItem item = new TreeItem(parent, SWT.NULL);
            item.setText(bookmark.name);
            item.setData(bookmark);
            item.setImage(iconURL);

          }
        else if (line.equals("</DL><p>")) { // folder boundry.
          parent = parent.getParentItem();
        }
      }
    catch (FileNotFoundException e) {
      e.printStackTrace();
    catch (IOException e) {
      e.printStackTrace();
    }
  }

  private void setStatus(String message) {
    label.setText(message);
  }

  public static void main(String[] args) {
    new BookmarkOrganizer();
  }
}

class BookmarkTransfer extends ByteArrayTransfer {
  private static final String BOOKMARK_TRANSFER_NAME = "BOOKMARK";
  private static final int BOOKMARK_TRANSFER_ID =
    registerType(BOOKMARK_TRANSFER_NAME);
  private static final BookmarkTransfer instance = new BookmarkTransfer();

  public static BookmarkTransfer getInstance() {
    return instance;
  }

  /*
   * (non-Javadoc)
   
   * @see org.eclipse.swt.dnd.Transfer#getTypeIds()
   */
  protected int[] getTypeIds() {
    return new int[] { BOOKMARK_TRANSFER_ID };
  }

  /*
   * (non-Javadoc)
   
   * @see org.eclipse.swt.dnd.Transfer#getTypeNames()
   */
  protected String[] getTypeNames() {
    return new String[] { BOOKMARK_TRANSFER_NAME };
  }

  /*
   * (non-Javadoc)
   
   * @see org.eclipse.swt.dnd.Transfer#javaToNative(java.lang.Object,
   *      org.eclipse.swt.dnd.TransferData)
   */
  protected void javaToNative(Object object, TransferData transferData) {
    if (object == null || !(object instanceof Bookmark))
      return;

    Bookmark bookmark = (Bookmarkobject;

    if (isSupportedType(transferData)) {
      try {
        // Writes data to a byte array.
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream(stream);
        out.writeUTF(bookmark.name);
        out.writeUTF(bookmark.href);
        out.writeUTF(bookmark.addDate);
        out.writeUTF(bookmark.lastVisited);
        out.writeUTF(bookmark.lastModified);
        out.close();

        super.javaToNative(stream.toByteArray(), transferData);
      catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  /*
   * (non-Javadoc)
   
   * @see org.eclipse.swt.dnd.Transfer#nativeToJava(org.eclipse.swt.dnd.TransferData)
   */
  protected Object nativeToJava(TransferData transferData) {
    if (isSupportedType(transferData)) {
      byte[] raw = (byte[]) super.nativeToJava(transferData);
      if (raw == null)
        return null;
      Bookmark bookmark = new Bookmark();

      try {
        ByteArrayInputStream stream = new ByteArrayInputStream(raw);
        DataInputStream in = new DataInputStream(stream);
        bookmark.name = in.readUTF();
        bookmark.href = in.readUTF();
        bookmark.addDate = in.readUTF();
        bookmark.lastVisited = in.readUTF();
        bookmark.lastModified = in.readUTF();
        in.close();
      catch (IOException e) {
        e.printStackTrace();
        return null;
      }

      return bookmark;
    else {
      return null;
    }
  }

}
           
       
Related examples in the same category
1. SWT Tree With Multi columnsSWT Tree With Multi columns
2. Detect Mouse Down In SWT Tree ItemDetect Mouse Down In SWT Tree Item
3. Limit selection to items that match a pattern in SWT TreeLimit selection to items that match a pattern in SWT Tree
4. SWT Tree Simple DemoSWT Tree Simple Demo
5. Category Tree
6. Simple TreeSimple Tree
7. Displays a single-selection tree, a multi-selection tree, and a checkbox treeDisplays a single-selection tree, a multi-selection tree, and a checkbox tree
8. Demonstrates TableTreeDemonstrates TableTree
9. Demonstrates TreeEditorDemonstrates TreeEditor
10. Tree ExampleTree Example
11. Tree Example 2
12. Demonstrates CheckboxTreeViewer
13. Demonstrates TreeViewerDemonstrates TreeViewer
14. SWT Tree SWT Tree
15. SWT Tree Composite
16. Print selected items in a SWT treePrint selected items in a SWT tree
17. Insert a SWT tree item (at an index)Insert a SWT tree item (at an index)
18. Detect a selection or check event in a tree (SWT.CHECK)Detect a selection or check event in a tree (SWT.CHECK)
19. Create a SWT tree (lazy)Create a SWT tree (lazy)
20. Create a treeCreate a tree
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.