Search in sources :

Example 1 with RcvrImportException

use of edu.cmu.cs.hcii.cogtool.util.RcvrImportException 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 RcvrImportException

use of edu.cmu.cs.hcii.cogtool.util.RcvrImportException in project cogtool by cogtool.

the class BalsamiqButtonAPIConverter method parseBalsamiqFile.

/** Helper function used by importDesign.
	 * This method is used to parse the tags of each .bmml file in the 
	 * directory. The file represents a {@link File} in the directory.
     * 
     * @param  inputFile the specified directory or file
     * @see              the new design in the project window.
     */
public void parseBalsamiqFile(File inputFile) throws IOException {
    String fileName = inputFile.getName();
    int lastIndex = fileName.lastIndexOf(".");
    fileName = (lastIndex == -1) ? fileName : fileName.substring(0, lastIndex);
    /* Check to make sure that this frame has not been created yet. Cycles 
		 * by transitions may exist in the design and these files do not need 
		 * to be parsed more than once. */
    if (!visitedFramesNames.contains(fileName)) {
        visitedFramesNames.add(fileName);
        // Create a Xerces DOM Parser. A DOM Parser can parse an XML file
        // and create a tree representation of it. This same parser method
        // is used in ImportCogTool.java to import from CogTool XML.
        DOMParser parser = new DOMParser();
        InputStream fis = new FileInputStream(inputFile);
        Reader input = new InputStreamReader(fis, "UTF-8");
        // Parse the Document and traverse the DOM
        try {
            parser.parse(new InputSource(input));
        } catch (SAXException e) {
            throw new RcvrImportException("Not a valid XML file to parse.");
        }
        //Traverse the xml tags in the tree beginning at the root, the document
        Document document = parser.getDocument();
        parseFrame(document, fileName);
    }
}
Also used : InputSource(org.xml.sax.InputSource) InputStreamReader(java.io.InputStreamReader) RcvrImportException(edu.cmu.cs.hcii.cogtool.util.RcvrImportException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) DOMParser(com.sun.org.apache.xerces.internal.parsers.DOMParser) Document(org.w3c.dom.Document) FileInputStream(java.io.FileInputStream) SAXException(org.xml.sax.SAXException)

Example 3 with RcvrImportException

use of edu.cmu.cs.hcii.cogtool.util.RcvrImportException in project cogtool by cogtool.

the class BalsamiqButtonAPIConverter method parseFrame.

/** Helper function used by importDesign.
	 * This method is used to parse the tags of each .bmml file and assign the
	 * attributes of the frame to the frame object
     * 
     * @param  document the root of the XML tree
     * @param  fileName the specified directory or file
     * @return              the newly created frame
     */
protected Frame parseFrame(Node document, String fileName) throws IOException {
    // This adds the created frame to the design
    Frame frame = getFrame(fileName);
    if (frame == null) {
        throw new RcvrImportException("Null Frame.");
    }
    //addAttributes(frame, node);
    Frame.setFrameDevices(frame, design.getDeviceTypes());
    NodeList children = document.getChildNodes();
    double frameWidth = 0;
    double frameHeight = 0;
    if (children != null) {
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (child.getNodeName().equalsIgnoreCase(MOCKUP_ELT)) {
                frameWidth = Integer.parseInt(getAttributeValue(child, MEASURED_WIDTH_ATTR));
                frameHeight = Integer.parseInt(getAttributeValue(child, MEASURED_HEIGHT_ATTR));
            }
        }
    }
    //TODO: if it doesnt import anything, a new frame window should still be imported?
    parseWidgets(document, frame);
    return frame;
}
Also used : Frame(edu.cmu.cs.hcii.cogtool.model.Frame) RcvrImportException(edu.cmu.cs.hcii.cogtool.util.RcvrImportException) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node)

Example 4 with RcvrImportException

use of edu.cmu.cs.hcii.cogtool.util.RcvrImportException 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)

Example 5 with RcvrImportException

use of edu.cmu.cs.hcii.cogtool.util.RcvrImportException in project cogtool by cogtool.

the class BalsamiqButtonAPIConverter method importDesign.

/** The new design is created and added to the project window.
     * This method must be implemented by the user.
     * 
     * @param  inputFile the specified directory or file
     * @param  design    The newly created design. The design is passed to 
     *                    the converter file so that frames may be added to it.
     *                    
     * @see              the new design in the project window.
     */
public void importDesign(File inputFile, Design newDesign) {
    this.design = newDesign;
    designName = this.design.getName();
    designPathName = inputFile.getParent();
    try {
        parseBalsamiqFile(inputFile);
        int minFrameWidth = DesignUtil.getFrameMinWidth();
        int minFrameHeight = DesignUtil.getFrameMinHeight();
        double frameScale = DesignUtil.getFrameScaleFactor();
        /*The frame situator spaces out the frames in the design window */
        DesignUtil.IFrameSituator frameSituator = new DesignUtil.ByRowFrameSituator(0.0, 0.0, 16.0, 16.0, minFrameWidth, minFrameHeight, CogToolPrefs.getFramesPerRow(), frameScale);
        //they were inserted is needed in order to keep a consistent behavior
        for (Frame frame : visitedFrames) {
            frameSituator.situateNextFrame(frame);
        }
    } catch (IOException e) {
        throw new RcvrImportException("importDesign() has encountered an exception " + e);
    }
}
Also used : DesignUtil(edu.cmu.cs.hcii.cogtool.model.DesignUtil) Frame(edu.cmu.cs.hcii.cogtool.model.Frame) RcvrImportException(edu.cmu.cs.hcii.cogtool.util.RcvrImportException) IOException(java.io.IOException)

Aggregations

RcvrImportException (edu.cmu.cs.hcii.cogtool.util.RcvrImportException)5 Frame (edu.cmu.cs.hcii.cogtool.model.Frame)2 ImportConverter (edu.cmu.cs.hcii.cogtool.model.ImportConverter)2 File (java.io.File)2 Method (java.lang.reflect.Method)2 DOMParser (com.sun.org.apache.xerces.internal.parsers.DOMParser)1 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 DesignUtil (edu.cmu.cs.hcii.cogtool.model.DesignUtil)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 FileInputStream (java.io.FileInputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1