Search in sources :

Example 1 with ImportConverter

use of edu.cmu.cs.hcii.cogtool.model.ImportConverter in project cogtool by cogtool.

the class ProjectController method createNewDesignForImport.

// createNewDesignAction
// Action for NewDesign2, createNewDesignForImport
protected IListenerAction createNewDesignForImport() {
    return new IListenerAction() {

        public Class<?> getParameterClass() {
            return DesignSelectionState.class;
        // return Class.class;
        }

        public boolean performAction(Object prms) {
            //call convert on the converter file
            Class<ImportConverter> translatorClass = CogToolLID.NewDesignFromImport.getClassAttribute();
            //CogToolLID.NewDesignFromImport.setClassAttribute(null);
            Object converter = null;
            try {
                converter = translatorClass.newInstance();
            } catch (InstantiationException e) {
                throw new RcvrImportException("Translator class cannot be instantiated.");
            } catch (IllegalAccessException e) {
                throw new RcvrImportException("The translator class is not accessible.");
            }
            Design design = null;
            Method isInputFileDirectory = null;
            try {
                isInputFileDirectory = translatorClass.getMethod("isInputFileDirectory", new Class[0]);
            } catch (SecurityException e) {
                throw new RcvrImportException("The security manager does not allow access to this method.");
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                throw new RcvrImportException("isInputFileDirectory does not exist in the converter file.");
            }
            boolean reqDir = false;
            try {
                reqDir = (Boolean) isInputFileDirectory.invoke(converter);
            } catch (IllegalArgumentException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            } catch (IllegalAccessException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            } catch (InvocationTargetException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }
            //parameters needed to be passed to importDesign. A file and design are passed.
            Class<?>[] parameters = new Class<?>[2];
            parameters[0] = File.class;
            parameters[1] = Design.class;
            Method importDesignMethod = null;
            try {
                importDesignMethod = translatorClass.getMethod("importDesign", parameters);
            } catch (SecurityException e) {
                throw new RcvrImportException("The security manager does not allow access to this method.");
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String designName = "";
            /*Instead of a inputFile, a directory was specified. Every file in the directory
                  needs to be parsed */
            Method allowedExtsMethod = null;
            try {
                allowedExtsMethod = translatorClass.getMethod("allowedExtensions", new Class[0]);
            } catch (SecurityException e) {
                throw new RcvrImportException("The security manager does not allow access to this method.");
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String[] extensions = null;
            try {
                extensions = (String[]) allowedExtsMethod.invoke(converter);
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (reqDir) {
                /*TODO: Need to confirm that directory name is guaranteed to only accept a directory*/
                String directoryName = interaction.askUserForDirectory("Choose a directory of files", "This directory contains the files that you wish to import.");
                if (directoryName != null) {
                    File directory = new File(directoryName);
                    if (directory != null) {
                        //TODO: What to do about importing it twice, designName [2];
                        designName = directory.getName();
                        Set<DeviceType> deviceTypeSet = new HashSet<DeviceType>();
                        Method selectedDevicesMethod = null;
                        try {
                            selectedDevicesMethod = translatorClass.getMethod("selectedDevices", new Class[0]);
                        } catch (SecurityException e) {
                            throw new RcvrImportException("The security manager does not allow access to this method.");
                        } catch (NoSuchMethodException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                        try {
                            deviceTypeSet = (Set<DeviceType>) selectedDevicesMethod.invoke(converter);
                        } catch (IllegalArgumentException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        } catch (IllegalAccessException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        } catch (InvocationTargetException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                        ProjectInteraction.DesignRequestData requestData = new ProjectInteraction.DesignRequestData();
                        requestData.designName = designName;
                        requestData.deviceTypes = deviceTypeSet;
                        //TODO: may need to keep checking the value that this returns
                        interaction.requestNewDesignName(requestData, false, project, false);
                        design = new Design(requestData.designName, requestData.deviceTypes);
                        makeDesignNameUnique(design);
                        // Collection<DeviceType> deviceTypes = (Collection<DeviceType>)
                        // designLoader.createCollection(design, Design.deviceTypesVAR, 1);
                        // Collection<?> frames =
                        //designLoader.createCollection(design, Design.framesVAR, 1);
                        File[] directoryContents = directory.listFiles();
                        for (File file : directoryContents) {
                            String fileName = file.getName();
                            //If there is no extension then null is the file extension
                            String fileExt = (fileName.lastIndexOf(".") == -1) ? null : fileName.substring(fileName.lastIndexOf('.'));
                            //Example: ".txt" will now be "txt" and . will now be ""
                            if (fileExt != null) {
                                fileExt = (fileExt.length()) > 1 ? fileExt = fileExt.substring(1) : "";
                            }
                            for (String extension : extensions) {
                                if (extension == null || extension.equalsIgnoreCase(fileExt)) {
                                    try {
                                        importDesignMethod.invoke(converter, file, design);
                                        break;
                                    /* Break is needed if the converter author placed the same
                                             * extension in the array twice then this conversion will
                                             * not occur more than once. */
                                    } catch (IllegalArgumentException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    } catch (IllegalAccessException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    } catch (InvocationTargetException e) {
                                        //throw new RcvrImportXmlException("Not a valid XML file to parse.");
                                        //ignore
                                        System.out.println("fileName " + fileName);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                File importFile = interaction.selectFile(true, null, extensions);
                try {
                    designName = importFile.getName();
                    //TODO: ask user for design name since it can be different from the filename
                    Set<DeviceType> deviceTypeSet = new HashSet<DeviceType>();
                    design = new Design(designName, deviceTypeSet);
                    makeDesignNameUnique(design);
                    //Collection<DeviceType> deviceTypes = (Collection<DeviceType>)
                    //designLoader.createCollection(design, Design.deviceTypesVAR, 1);
                    //Collection<?> frames =
                    // designLoader.createCollection(design, Design.framesVAR, 1);
                    System.out.println("design " + design.getName());
                    importDesignMethod.invoke(converter, importFile, design);
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            //change inputfile to the specific file
            }
            if (design != null) {
                ProjectCmd.addNewDesign(project, design, ((DesignSelectionState) prms).getSelectedDesign(), NEW_DESIGN, undoMgr);
            }
            return true;
        }
    };
}
Also used : ImportConverter(edu.cmu.cs.hcii.cogtool.model.ImportConverter) ProjectInteraction(edu.cmu.cs.hcii.cogtool.ui.ProjectInteraction) Design(edu.cmu.cs.hcii.cogtool.model.Design) ITaskDesign(edu.cmu.cs.hcii.cogtool.model.Project.ITaskDesign) IListenerAction(edu.cmu.cs.hcii.cogtool.util.IListenerAction) DesignSelectionState(edu.cmu.cs.hcii.cogtool.ui.DesignSelectionState) HashSet(java.util.HashSet) RcvrImportException(edu.cmu.cs.hcii.cogtool.util.RcvrImportException) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) DeviceType(edu.cmu.cs.hcii.cogtool.model.DeviceType) File(java.io.File)

Example 2 with ImportConverter

use of edu.cmu.cs.hcii.cogtool.model.ImportConverter in project cogtool by cogtool.

the class MenuFactory method buildMenu.

// addWindowMenu
public static void buildMenu(MenuType[] neededMenus, Shell viewShell, final Listener selectionListener, ListenerIdentifierMap lIDMap, IWindowMenuData<?> menuData) {
    int windowMenuIndex = -1;
    int fileMenuIndex = -1;
    MenuUtil.CascadingMenuItemDefinition[] defn = new MenuUtil.CascadingMenuItemDefinition[neededMenus.length];
    for (int i = 0; i < neededMenus.length; i++) {
        defn[i] = menuDefns[neededMenus[i].getOrdering()];
        if (neededMenus[i] == MenuFactory.MenuType.FileMenu) {
            fileMenuIndex = i;
        } else if (neededMenus[i] == MenuFactory.MenuType.WindowMenu) {
            windowMenuIndex = i;
            defn[i].menuItems = menuData.getWindowMenuLeadItems();
        }
    }
    Menu newMenuBar = MenuUtil.createMenu(viewShell, SWT.BAR | SWT.LEFT_TO_RIGHT, defn, ListenerIdentifierMap.NORMAL, selectionListener, lIDMap);
    if (fileMenuIndex != -1) {
        final Menu fileMenu = newMenuBar.getItem(fileMenuIndex).getMenu();
        fileMenu.addMenuListener(new MenuAdapter() {

            @Override
            public void menuShown(MenuEvent evt) {
                for (MenuItem item : fileMenu.getItems()) {
                    //This menu item corresponds to the Open Recent submenu
                    if (item.getData() == RECENT_FLAG) {
                        Menu cascade = item.getMenu();
                        for (MenuItem subItem : cascade.getItems()) {
                            subItem.dispose();
                        }
                        char recentIndex = '0';
                        for (String pathName : CogToolPref.getRecent()) {
                            if (!(MenuFactory.UNSET_FILE.equals(pathName))) {
                                if (recentIndex != 0) {
                                    if (recentIndex != '9') {
                                        recentIndex++;
                                    } else {
                                        recentIndex = ' ';
                                    }
                                }
                                String safePathName = "&" + recentIndex + " " + pathName.replaceAll("&", "&&");
                                MenuItem mi = MenuUtil.addMenuItem(cascade, safePathName, SWT.PUSH);
                                CogToolLID lid = new CogToolLID.OpenRecentLID("OpenRecent", pathName);
                                mi.addListener(SWT.Selection, selectionListener);
                                mi.setData(lid);
                            }
                        }
                        boolean hasRecent = CogToolPref.hasRecent();
                        if (hasRecent) {
                            MenuUtil.addMenuItem(cascade, "", SWT.SEPARATOR);
                        }
                        MenuItem clearItem = MenuUtil.addMenuItem(cascade, L10N.get("MI.ClearItems", "Clear items"), SWT.PUSH);
                        clearItem.addListener(SWT.Selection, selectionListener);
                        clearItem.setData(CogToolLID.ClearRecent);
                        clearItem.setEnabled(hasRecent);
                    //break;
                    } else // TODO this is a mess and needs to be tidied up
                    if (item.getData() == IMPORT_OTHER_FLAG) {
                        Menu cascade = item.getMenu();
                        for (MenuItem subItem : cascade.getItems()) {
                            subItem.dispose();
                        }
                        File directory = null;
                        String directoryName = CogToolPref.CONVERTER_DIRECTORY.getString();
                        boolean researchMode = CogToolPref.RESEARCH.getBoolean();
                        if (directoryName != null && !directoryName.equals("")) {
                            directory = new File(directoryName);
                            URL[] urls = null;
                            try {
                                // TODO: fix this deprecated method
                                URL url = directory.toURL();
                                urls = new URL[] { url };
                            } catch (MalformedURLException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                            }
                            if (directory.exists()) {
                                URLClassLoader classLoader = new URLClassLoader(urls);
                                String[] children = directory.list();
                                boolean firstMenuItem = true;
                                for (String resource : children) {
                                    System.out.println("Resource " + resource);
                                    resource = (resource.lastIndexOf(".") == -1) ? resource : resource.substring(0, resource.lastIndexOf('.'));
                                    try {
                                        Class<ImportConverter> translatorClass = (Class<ImportConverter>) classLoader.loadClass(resource);
                                        try {
                                            Object converter = null;
                                            try {
                                                converter = translatorClass.newInstance();
                                                Class[] nameMethodParameters = new Class[0];
                                                Method method = translatorClass.getMethod("name", nameMethodParameters);
                                                String name = (String) method.invoke(converter);
                                                if (!name.endsWith("...")) {
                                                    name = name + "...";
                                                }
                                                if (firstMenuItem) {
                                                    MenuUtil.addMenuItem(cascade, "", SWT.SEPARATOR);
                                                    firstMenuItem = false;
                                                }
                                                String menuItemName = "Import Designs from " + name;
                                                MenuItem mi = MenuUtil.addMenuItem(cascade, menuItemName, SWT.PUSH);
                                                CogToolLID lid = new CogToolLID.ConverterFilesLID("NewDesignFromImport");
                                                ((ConverterFilesLID) lid).setClassAttribute(translatorClass);
                                                mi.setData(lid);
                                                mi.addListener(SWT.Selection, selectionListener);
                                            } catch (Exception ex) {
                                                throw new RcvrImportException("The file " + resource + " can not be loaded as a class.");
                                            }//Interact with the user and display the message.
                                             catch (Error er) {
                                                System.out.println("Error was thrown!");
                                            //TODO: How to throw this recoverable exception but move on?
                                            //throw new RcvrImportException("The file " + resource + " can not be loaded as a class.");
                                            }
                                        } catch (Exception ex) {
                                            throw new RcvrImportException("The file " + resource + " is not a valid converter file.");
                                        } catch (Error er) {
                                            System.out.println("Error was thrown2!");
                                        //TODO: How to throw this recoverable exception but move on?
                                        //throw new RcvrImportException("The file " + resource + " can not be loaded as a class.");
                                        }
                                    } catch (Exception ex) {
                                        throw new RcvrImportException("The file " + resource + " cannot be loaded as a class.");
                                    } catch (Error er) {
                                        System.out.println("Error was thrown3!");
                                    //TODO: How to throw this recoverable exception but move on?
                                    //throw new RcvrImportException("The file " + resource + " can not be loaded as a class.");
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
            }
        });
    }
    if (windowMenuIndex != -1) {
        // reset!
        defn[windowMenuIndex].menuItems = null;
        addWindowMenu(newMenuBar.getItem(windowMenuIndex).getMenu(), menuData);
    }
    viewShell.setMenuBar(newMenuBar);
}
Also used : MalformedURLException(java.net.MalformedURLException) ImportConverter(edu.cmu.cs.hcii.cogtool.model.ImportConverter) URL(java.net.URL) ConverterFilesLID(edu.cmu.cs.hcii.cogtool.CogToolLID.ConverterFilesLID) Menu(org.eclipse.swt.widgets.Menu) MenuEvent(org.eclipse.swt.events.MenuEvent) RcvrImportException(edu.cmu.cs.hcii.cogtool.util.RcvrImportException) MenuAdapter(org.eclipse.swt.events.MenuAdapter) MenuItem(org.eclipse.swt.widgets.MenuItem) Method(java.lang.reflect.Method) RcvrUIException(edu.cmu.cs.hcii.cogtool.util.RcvrUIException) MalformedURLException(java.net.MalformedURLException) RcvrImportException(edu.cmu.cs.hcii.cogtool.util.RcvrImportException) CascadingMenuItemDefinition(edu.cmu.cs.hcii.cogtool.util.MenuUtil.CascadingMenuItemDefinition) CogToolLID(edu.cmu.cs.hcii.cogtool.CogToolLID) URLClassLoader(java.net.URLClassLoader) File(java.io.File)

Aggregations

ImportConverter (edu.cmu.cs.hcii.cogtool.model.ImportConverter)2 RcvrImportException (edu.cmu.cs.hcii.cogtool.util.RcvrImportException)2 File (java.io.File)2 Method (java.lang.reflect.Method)2 CogToolLID (edu.cmu.cs.hcii.cogtool.CogToolLID)1 ConverterFilesLID (edu.cmu.cs.hcii.cogtool.CogToolLID.ConverterFilesLID)1 Design (edu.cmu.cs.hcii.cogtool.model.Design)1 DeviceType (edu.cmu.cs.hcii.cogtool.model.DeviceType)1 ITaskDesign (edu.cmu.cs.hcii.cogtool.model.Project.ITaskDesign)1 DesignSelectionState (edu.cmu.cs.hcii.cogtool.ui.DesignSelectionState)1 ProjectInteraction (edu.cmu.cs.hcii.cogtool.ui.ProjectInteraction)1 IListenerAction (edu.cmu.cs.hcii.cogtool.util.IListenerAction)1 CascadingMenuItemDefinition (edu.cmu.cs.hcii.cogtool.util.MenuUtil.CascadingMenuItemDefinition)1 RcvrUIException (edu.cmu.cs.hcii.cogtool.util.RcvrUIException)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 URLClassLoader (java.net.URLClassLoader)1 HashSet (java.util.HashSet)1 MenuAdapter (org.eclipse.swt.events.MenuAdapter)1