Search in sources :

Example 16 with SerializationException

use of org.apache.pivot.serialization.SerializationException in project pivot by apache.

the class BXMLSerializer method logException.

private void logException(Throwable exception) {
    Location streamReaderlocation = xmlStreamReader.getLocation();
    String message = "An error occurred at line number " + streamReaderlocation.getLineNumber();
    if (location != null) {
        message += " in file " + location.getPath();
    }
    message += ":";
    reportException(new SerializationException(message, exception));
}
Also used : SerializationException(org.apache.pivot.serialization.SerializationException) Location(javax.xml.stream.Location)

Example 17 with SerializationException

use of org.apache.pivot.serialization.SerializationException in project pivot by apache.

the class BXMLSerializer method processAttributes.

private void processAttributes() throws SerializationException {
    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    for (int i = 0, n = xmlStreamReader.getAttributeCount(); i < n; i++) {
        String prefix = xmlStreamReader.getAttributePrefix(i);
        String localName = xmlStreamReader.getAttributeLocalName(i);
        String value = xmlStreamReader.getAttributeValue(i);
        if (prefix != null && prefix.equals(BXML_PREFIX)) {
            // The attribute represents an internal value
            if (localName.equals(ID_ATTRIBUTE)) {
                if (value.length() == 0 || value.contains(".")) {
                    throw new IllegalArgumentException("\"" + value + "\" is not a valid ID value.");
                }
                if (namespace.containsKey(value)) {
                    throw new SerializationException("ID " + value + " is already in use.");
                }
                if (element.type != Element.Type.INSTANCE && element.type != Element.Type.INCLUDE) {
                    throw new SerializationException("An ID cannot be assigned to this element.");
                }
                element.id = value;
            } else {
                throw new SerializationException(BXML_PREFIX + ":" + localName + " is not a valid attribute.");
            }
        } else {
            boolean property = false;
            switch(element.type) {
                case INCLUDE:
                    {
                        property = (localName.equals(INCLUDE_SRC_ATTRIBUTE) || localName.equals(INCLUDE_RESOURCES_ATTRIBUTE) || localName.equals(INCLUDE_MIME_TYPE_ATTRIBUTE) || localName.equals(INCLUDE_INLINE_ATTRIBUTE));
                        break;
                    }
                case SCRIPT:
                    {
                        property = (localName.equals(SCRIPT_SRC_ATTRIBUTE));
                        break;
                    }
                case REFERENCE:
                    {
                        property = (localName.equals(REFERENCE_ID_ATTRIBUTE));
                        break;
                    }
                default:
                    {
                        break;
                    }
            }
            if (property) {
                element.properties.put(localName, value);
            } else {
                String name;
                Class<?> propertyClass = null;
                if (Character.isUpperCase(localName.charAt(0))) {
                    // The attribute represents a static property or listener list
                    int j = localName.indexOf('.');
                    name = localName.substring(j + 1);
                    String namespaceURI = xmlStreamReader.getAttributeNamespace(i);
                    if (Utils.isNullOrEmpty(namespaceURI)) {
                        namespaceURI = xmlStreamReader.getNamespaceURI("");
                    }
                    String propertyClassName = namespaceURI + "." + localName.substring(0, j);
                    try {
                        propertyClass = Class.forName(propertyClassName, true, classLoader);
                    } catch (Throwable exception) {
                        throw new SerializationException(exception);
                    }
                } else {
                    // The attribute represents an instance property
                    name = localName;
                }
                if (value.startsWith(NAMESPACE_BINDING_PREFIX) && value.endsWith(NAMESPACE_BINDING_SUFFIX)) {
                    // The attribute represents a namespace binding
                    if (propertyClass != null) {
                        throw new SerializationException("Namespace binding is not supported for static properties.");
                    }
                    namespaceBindingAttributes.add(new Attribute(element, name, propertyClass, value.substring(2, value.length() - 1)));
                } else {
                    // Resolve the attribute value
                    Attribute attribute = new Attribute(element, name, propertyClass, value);
                    if (value.length() > 0) {
                        if (value.charAt(0) == URL_PREFIX) {
                            value = value.substring(1);
                            if (value.length() > 0) {
                                if (value.charAt(0) == URL_PREFIX) {
                                    attribute.value = value;
                                } else {
                                    if (location == null) {
                                        throw new IllegalStateException("Base location is undefined.");
                                    }
                                    try {
                                        attribute.value = new URL(location, value);
                                    } catch (MalformedURLException exception) {
                                        throw new SerializationException(exception);
                                    }
                                }
                            } else {
                                throw new SerializationException("Invalid URL resolution argument.");
                            }
                        } else if (value.charAt(0) == RESOURCE_KEY_PREFIX) {
                            value = value.substring(1);
                            if (value.length() > 0) {
                                if (value.charAt(0) == RESOURCE_KEY_PREFIX) {
                                    attribute.value = value;
                                } else {
                                    if (resources != null && JSON.containsKey(resources, value)) {
                                        attribute.value = JSON.get(resources, value);
                                    } else {
                                        attribute.value = value;
                                    }
                                }
                            } else {
                                throw new SerializationException("Invalid resource resolution argument.");
                            }
                        } else if (value.charAt(0) == OBJECT_REFERENCE_PREFIX) {
                            value = value.substring(1);
                            if (value.length() > 0) {
                                if (value.charAt(0) == OBJECT_REFERENCE_PREFIX) {
                                    attribute.value = value;
                                } else {
                                    if (value.equals(BXML_PREFIX + ":" + null)) {
                                        attribute.value = null;
                                    } else {
                                        if (JSON.containsKey(namespace, value)) {
                                            attribute.value = JSON.get(namespace, value);
                                        } else {
                                            Object nashornGlobal = scriptEngineManager.getBindings().get(NASHORN_GLOBAL);
                                            if (nashornGlobal == null) {
                                                throw new SerializationException("Value \"" + value + "\" is not defined.");
                                            } else {
                                                if (nashornGlobal instanceof Bindings) {
                                                    Bindings bindings = (Bindings) nashornGlobal;
                                                    if (bindings.containsKey(value)) {
                                                        attribute.value = bindings.get(value);
                                                    } else {
                                                        throw new SerializationException("Value \"" + value + "\" is not defined.");
                                                    }
                                                } else {
                                                    throw new SerializationException("Value \"" + value + "\" is not defined.");
                                                }
                                            }
                                        }
                                    }
                                }
                            } else {
                                throw new SerializationException("Invalid object resolution argument.");
                            }
                        }
                    }
                    element.attributes.add(attribute);
                }
            }
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) SerializationException(org.apache.pivot.serialization.SerializationException) Bindings(javax.script.Bindings) SimpleBindings(javax.script.SimpleBindings) URL(java.net.URL)

Example 18 with SerializationException

use of org.apache.pivot.serialization.SerializationException in project pivot by apache.

the class BXMLSerializer method processStartElement.

private void processStartElement() throws IOException, SerializationException {
    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    // Initialize the page language
    if (language == null) {
        language = getDefaultLanguage();
    }
    // Get element properties
    String namespaceURI = xmlStreamReader.getNamespaceURI();
    String prefix = xmlStreamReader.getPrefix();
    // for the default namespace
    if (prefix != null && prefix.length() == 0) {
        prefix = null;
    }
    String localName = xmlStreamReader.getLocalName();
    // Determine the type and value of this element
    Element.Type elementType;
    String name;
    Class<?> propertyClass = null;
    Object value = null;
    if (prefix != null && prefix.equals(BXML_PREFIX)) {
        // The element represents a BXML operation
        if (element == null) {
            throw new SerializationException("Invalid root element.");
        }
        if (localName.equals(INCLUDE_TAG)) {
            elementType = Element.Type.INCLUDE;
        } else if (localName.equals(SCRIPT_TAG)) {
            elementType = Element.Type.SCRIPT;
        } else if (localName.equals(DEFINE_TAG)) {
            elementType = Element.Type.DEFINE;
        } else if (localName.equals(REFERENCE_TAG)) {
            elementType = Element.Type.REFERENCE;
        } else {
            throw new SerializationException("Invalid element.");
        }
        name = "<" + prefix + ":" + localName + ">";
    } else {
        if (Character.isUpperCase(localName.charAt(0))) {
            int i = localName.indexOf('.');
            if (i != -1 && Character.isLowerCase(localName.charAt(i + 1))) {
                // The element represents an attached property
                elementType = Element.Type.WRITABLE_PROPERTY;
                name = localName.substring(i + 1);
                String propertyClassName = namespaceURI + "." + localName.substring(0, i);
                try {
                    propertyClass = Class.forName(propertyClassName, true, classLoader);
                } catch (Throwable exception) {
                    throw new SerializationException(exception);
                }
            } else {
                // The element represents a typed object
                if (namespaceURI == null) {
                    throw new SerializationException("No XML namespace specified for " + localName + " tag.");
                }
                elementType = Element.Type.INSTANCE;
                name = "<" + ((prefix == null) ? "" : prefix + ":") + localName + ">";
                String className = namespaceURI + "." + localName.replace('.', '$');
                try {
                    Class<?> type = Class.forName(className, true, classLoader);
                    value = newTypedObject(type);
                } catch (Throwable exception) {
                    throw new SerializationException("Error creating a new '" + className + "' object", exception);
                }
            }
        } else {
            // The element represents a property
            if (prefix != null) {
                throw new SerializationException("Property elements cannot have a namespace prefix.");
            }
            if (element.value instanceof Dictionary<?, ?>) {
                elementType = Element.Type.WRITABLE_PROPERTY;
            } else {
                BeanAdapter beanAdapter = new BeanAdapter(element.value);
                if (beanAdapter.isReadOnly(localName)) {
                    Class<?> propertyType = beanAdapter.getType(localName);
                    if (propertyType == null) {
                        throw new SerializationException("\"" + localName + "\" is not a valid property of element " + element.name + ".");
                    }
                    if (ListenerList.class.isAssignableFrom(propertyType)) {
                        elementType = Element.Type.LISTENER_LIST_PROPERTY;
                    } else {
                        elementType = Element.Type.READ_ONLY_PROPERTY;
                        value = beanAdapter.get(localName);
                        assert (value != null) : "Read-only properties cannot be null.";
                    }
                } else {
                    elementType = Element.Type.WRITABLE_PROPERTY;
                }
            }
            name = localName;
        }
    }
    // Create the element and process the attributes
    element = new Element(element, elementType, name, propertyClass, value);
    processAttributes();
    if (elementType == Element.Type.INCLUDE) {
        // Load the include
        if (!element.properties.containsKey(INCLUDE_SRC_ATTRIBUTE)) {
            throw new SerializationException(INCLUDE_SRC_ATTRIBUTE + " attribute is required for " + BXML_PREFIX + ":" + INCLUDE_TAG + " tag.");
        }
        String src = element.properties.get(INCLUDE_SRC_ATTRIBUTE);
        if (src.charAt(0) == OBJECT_REFERENCE_PREFIX) {
            src = src.substring(1);
            if (src.length() > 0) {
                if (!JSON.containsKey(namespace, src)) {
                    throw new SerializationException("Value \"" + src + "\" is not defined.");
                }
                String variableValue = JSON.get(namespace, src);
                src = variableValue;
            }
        }
        Resources resourcesLocal = this.resources;
        if (element.properties.containsKey(INCLUDE_RESOURCES_ATTRIBUTE)) {
            resourcesLocal = new Resources(resourcesLocal, element.properties.get(INCLUDE_RESOURCES_ATTRIBUTE));
        }
        String mimeType = null;
        if (element.properties.containsKey(INCLUDE_MIME_TYPE_ATTRIBUTE)) {
            mimeType = element.properties.get(INCLUDE_MIME_TYPE_ATTRIBUTE);
        }
        if (mimeType == null) {
            // Get the file extension
            int i = src.lastIndexOf(".");
            if (i != -1) {
                String extension = src.substring(i + 1);
                mimeType = fileExtensions.get(extension);
            }
        }
        if (mimeType == null) {
            throw new SerializationException("Cannot determine MIME type of include \"" + src + "\".");
        }
        boolean inline = false;
        if (element.properties.containsKey(INCLUDE_INLINE_ATTRIBUTE)) {
            inline = Boolean.parseBoolean(element.properties.get(INCLUDE_INLINE_ATTRIBUTE));
        }
        // Determine an appropriate serializer to use for the include
        Class<? extends Serializer<?>> serializerClass = mimeTypes.get(mimeType);
        if (serializerClass == null) {
            throw new SerializationException("No serializer associated with MIME type " + mimeType + ".");
        }
        Serializer<?> serializer;
        try {
            serializer = newIncludeSerializer(serializerClass);
        } catch (InstantiationException exception) {
            throw new SerializationException(exception);
        } catch (IllegalAccessException exception) {
            throw new SerializationException(exception);
        }
        // Determine location from src attribute
        URL locationLocal;
        if (src.charAt(0) == SLASH_PREFIX) {
            locationLocal = classLoader.getResource(src.substring(1));
        } else {
            locationLocal = new URL(this.location, src);
        }
        // Set optional resolution properties
        if (serializer instanceof Resolvable) {
            Resolvable resolvable = (Resolvable) serializer;
            if (inline) {
                resolvable.setNamespace(namespace);
            }
            resolvable.setLocation(locationLocal);
            resolvable.setResources(resourcesLocal);
        }
        // Read the object
        try (InputStream inputStream = new BufferedInputStream(locationLocal.openStream())) {
            element.value = serializer.readObject(inputStream);
        }
    } else if (element.type == Element.Type.REFERENCE) {
        // Dereference the value
        if (!element.properties.containsKey(REFERENCE_ID_ATTRIBUTE)) {
            throw new SerializationException(REFERENCE_ID_ATTRIBUTE + " attribute is required for " + BXML_PREFIX + ":" + REFERENCE_TAG + " tag.");
        }
        String id = element.properties.get(REFERENCE_ID_ATTRIBUTE);
        if (!namespace.containsKey(id)) {
            throw new SerializationException("A value with ID \"" + id + "\" does not exist.");
        }
        element.value = namespace.get(id);
    }
    // If the element has an ID, add the value to the namespace
    if (element.id != null) {
        namespace.put(element.id, element.value);
        // If the type has an ID property, use it
        Class<?> type = element.value.getClass();
        IDProperty idProperty = type.getAnnotation(IDProperty.class);
        if (idProperty != null) {
            BeanAdapter beanAdapter = new BeanAdapter(element.value);
            beanAdapter.put(idProperty.value(), element.id);
        }
    }
}
Also used : Dictionary(org.apache.pivot.collections.Dictionary) SerializationException(org.apache.pivot.serialization.SerializationException) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) URL(java.net.URL) BufferedInputStream(java.io.BufferedInputStream) Resources(org.apache.pivot.util.Resources)

Example 19 with SerializationException

use of org.apache.pivot.serialization.SerializationException in project pivot by apache.

the class TerraFileBrowserSheetSkin method install.

@Override
public void install(Component component) {
    super.install(component);
    final FileBrowserSheet fileBrowserSheet = (FileBrowserSheet) component;
    fileBrowserSheet.setMinimumWidth(360);
    fileBrowserSheet.setMinimumHeight(180);
    // Load the sheet content
    BXMLSerializer bxmlSerializer = new BXMLSerializer();
    Component content;
    try {
        content = (Component) bxmlSerializer.readObject(TerraFileBrowserSheetSkin.class, "terra_file_browser_sheet_skin.bxml", true);
    } catch (IOException exception) {
        throw new RuntimeException(exception);
    } catch (SerializationException exception) {
        throw new RuntimeException(exception);
    }
    fileBrowserSheet.setContent(content);
    bxmlSerializer.bind(this, TerraFileBrowserSheetSkin.class);
    // set the same rootDirectory to fileBrowser
    fileBrowser.setRootDirectory(fileBrowserSheet.getRootDirectory());
    saveAsTextInput.getTextInputContentListeners().add(new TextInputContentListener() {

        @Override
        public void textChanged(TextInput textInput) {
            Form.clearFlag(saveAsBoxPane);
            updateOKButtonState();
        }
    });
    fileBrowser.getFileBrowserListeners().add(new FileBrowserListener() {

        @Override
        public void rootDirectoryChanged(FileBrowser fileBrowserArgument, File previousRootDirectory) {
            updatingSelection = true;
            fileBrowserSheet.setRootDirectory(fileBrowserArgument.getRootDirectory());
            updatingSelection = false;
            selectedDirectoryCount = 0;
            updateOKButtonState();
        }

        @Override
        public void selectedFileAdded(FileBrowser fileBrowserArgument, File file) {
            if (file.isDirectory()) {
                selectedDirectoryCount++;
            }
            updateOKButtonState();
        }

        @Override
        public void selectedFileRemoved(FileBrowser fileBrowserArgument, File file) {
            if (file.isDirectory()) {
                selectedDirectoryCount--;
            }
            updateOKButtonState();
        }

        @Override
        public void selectedFilesChanged(FileBrowser fileBrowserArgument, Sequence<File> previousSelectedFiles) {
            selectedDirectoryCount = 0;
            Sequence<File> selectedFiles = fileBrowserArgument.getSelectedFiles();
            for (int i = 0, n = selectedFiles.getLength(); i < n; i++) {
                File selectedFile = selectedFiles.get(i);
                if (selectedFile.isDirectory()) {
                    selectedDirectoryCount++;
                }
            }
            if (!fileBrowserArgument.isMultiSelect()) {
                File selectedFile = fileBrowserArgument.getSelectedFile();
                if (selectedFile != null && !selectedFile.isDirectory()) {
                    saveAsTextInput.setText(selectedFile.getName());
                }
            }
            updateOKButtonState();
        }
    });
    fileBrowser.getComponentMouseButtonListeners().add(new ComponentMouseButtonListener() {

        private File file = null;

        @Override
        public boolean mouseClick(Component componentArgument, Mouse.Button button, int x, int y, int count) {
            boolean consumed = false;
            FileBrowserSheet.Mode mode = fileBrowserSheet.getMode();
            if (count == 1) {
                file = fileBrowser.getFileAt(x, y);
            } else if (count == 2) {
                File fileLocal = fileBrowser.getFileAt(x, y);
                if (fileLocal != null && this.file != null && fileLocal.equals(this.file) && fileBrowser.isFileSelected(fileLocal)) {
                    if (mode == FileBrowserSheet.Mode.OPEN || mode == FileBrowserSheet.Mode.OPEN_MULTIPLE) {
                        if (!fileLocal.isDirectory()) {
                            fileBrowserSheet.close(true);
                            consumed = true;
                        }
                    }
                }
            }
            return consumed;
        }
    });
    okButton.getButtonPressListeners().add(new ButtonPressListener() {

        @Override
        public void buttonPressed(Button button) {
            fileBrowserSheet.close(true);
        }
    });
    cancelButton.getButtonPressListeners().add(new ButtonPressListener() {

        @Override
        public void buttonPressed(Button button) {
            fileBrowserSheet.close(false);
        }
    });
    // Add this as a file browser sheet listener
    fileBrowserSheet.getFileBrowserSheetListeners().add(this);
    modeChanged(fileBrowserSheet, null);
    rootDirectoryChanged(fileBrowserSheet, null);
    selectedFilesChanged(fileBrowserSheet, null);
}
Also used : FileBrowserListener(org.apache.pivot.wtk.FileBrowserListener) SerializationException(org.apache.pivot.serialization.SerializationException) FileBrowserSheet(org.apache.pivot.wtk.FileBrowserSheet) IOException(java.io.IOException) Sequence(org.apache.pivot.collections.Sequence) ButtonPressListener(org.apache.pivot.wtk.ButtonPressListener) TextInputContentListener(org.apache.pivot.wtk.TextInputContentListener) Mouse(org.apache.pivot.wtk.Mouse) PushButton(org.apache.pivot.wtk.PushButton) Button(org.apache.pivot.wtk.Button) FileBrowser(org.apache.pivot.wtk.FileBrowser) ComponentMouseButtonListener(org.apache.pivot.wtk.ComponentMouseButtonListener) Component(org.apache.pivot.wtk.Component) TextInput(org.apache.pivot.wtk.TextInput) File(java.io.File) BXMLSerializer(org.apache.pivot.beans.BXMLSerializer)

Example 20 with SerializationException

use of org.apache.pivot.serialization.SerializationException in project pivot by apache.

the class TerraFileBrowserSkin method install.

@Override
public void install(Component component) {
    super.install(component);
    final FileBrowser fileBrowser = (FileBrowser) component;
    BXMLSerializer bxmlSerializer = new BXMLSerializer();
    try {
        content = (Component) bxmlSerializer.readObject(TerraFileBrowserSkin.class, "terra_file_browser_skin.bxml", true);
    } catch (IOException exception) {
        throw new RuntimeException(exception);
    } catch (SerializationException exception) {
        throw new RuntimeException(exception);
    }
    fileBrowser.add(content);
    bxmlSerializer.bind(this, TerraFileBrowserSkin.class);
    driveListButton.getListButtonSelectionListeners().add(new ListButtonSelectionListener() {

        @Override
        public void selectedItemChanged(ListButton listButton, Object previousSelectedItem) {
            if (previousSelectedItem != null) {
                File drive = (File) listButton.getSelectedItem();
                if (drive != null && drive.canRead()) {
                    if (!selectingDriveFromRootDirectory) {
                        fileBrowser.setRootDirectory(drive);
                    }
                } else {
                    refreshRoots = true;
                    listButton.setSelectedItem(previousSelectedItem);
                }
            }
        }
    });
    pathListButton.getListButtonSelectionListeners().add(new ListButtonSelectionListener() {

        @Override
        public void selectedItemChanged(ListButton listButton, Object previousSelectedItem) {
            File ancestorDirectory = (File) listButton.getSelectedItem();
            if (ancestorDirectory != null) {
                fileBrowser.setRootDirectory(ancestorDirectory);
            }
        }
    });
    goUpButton.getButtonPressListeners().add(new ButtonPressListener() {

        @Override
        public void buttonPressed(Button button) {
            File rootDirectory = fileBrowser.getRootDirectory();
            File parentDirectory = rootDirectory.getParentFile();
            fileBrowser.setRootDirectory(parentDirectory);
        }
    });
    newFolderButton.getButtonPressListeners().add(new ButtonPressListener() {

        @Override
        public void buttonPressed(Button button) {
        // TODO
        }
    });
    goHomeButton.getButtonPressListeners().add(new ButtonPressListener() {

        @Override
        public void buttonPressed(Button button) {
            fileBrowser.setRootDirectory(HOME_DIRECTORY);
        }
    });
    /**
     * {@link KeyCode#DOWN DOWN} Transfer focus to the file list and select
     * the first item.<br> {@link KeyCode#ESCAPE ESCAPE} Clear the search
     * field.
     */
    searchTextInput.getComponentKeyListeners().add(new ComponentKeyListener() {

        @Override
        public boolean keyPressed(Component componentArgument, int keyCode, Keyboard.KeyLocation keyLocation) {
            boolean consumed = false;
            if (keyCode == Keyboard.KeyCode.ESCAPE) {
                searchTextInput.setText("");
                consumed = true;
            } else if (keyCode == Keyboard.KeyCode.DOWN) {
                if (fileTableView.getTableData().getLength() > 0) {
                    fileTableView.setSelectedIndex(0);
                    fileTableView.requestFocus();
                }
            }
            return consumed;
        }
    });
    searchTextInput.getTextInputContentListeners().add(new TextInputContentListener() {

        @Override
        public void textChanged(TextInput textInput) {
            refreshFileList();
        }
    });
    fileTableView.getTableViewSelectionListeners().add(new TableViewSelectionListener() {

        @Override
        public void selectedRangeAdded(TableView tableView, int rangeStart, int rangeEnd) {
            if (!updatingSelection) {
                updatingSelection = true;
                for (int i = rangeStart; i <= rangeEnd; i++) {
                    @SuppressWarnings("unchecked") List<File> files = (List<File>) fileTableView.getTableData();
                    File file = files.get(i);
                    fileBrowser.addSelectedFile(file);
                }
                updatingSelection = false;
            }
        }

        @Override
        public void selectedRangeRemoved(TableView tableView, int rangeStart, int rangeEnd) {
            if (!updatingSelection) {
                updatingSelection = true;
                for (int i = rangeStart; i <= rangeEnd; i++) {
                    @SuppressWarnings("unchecked") List<File> files = (List<File>) fileTableView.getTableData();
                    File file = files.get(i);
                    fileBrowser.removeSelectedFile(file);
                }
                updatingSelection = false;
            }
        }

        @Override
        public void selectedRangesChanged(TableView tableView, Sequence<Span> previousSelectedRanges) {
            if (!updatingSelection && previousSelectedRanges != null) {
                updatingSelection = true;
                @SuppressWarnings("unchecked") Sequence<File> files = (Sequence<File>) tableView.getSelectedRows();
                for (int i = 0, n = files.getLength(); i < n; i++) {
                    File file = files.get(i);
                    files.update(i, file);
                }
                fileBrowser.setSelectedFiles(files);
                updatingSelection = false;
            }
        }

        @Override
        public void selectedRowChanged(TableView tableView, Object previousSelectedRow) {
        // No-op
        }
    });
    fileTableView.getTableViewSortListeners().add(new TableViewSortListener() {

        @Override
        public void sortChanged(TableView tableView) {
            TableView.SortDictionary sort = fileTableView.getSort();
            if (!sort.isEmpty()) {
                Dictionary.Pair<String, SortDirection> pair = fileTableView.getSort().get(0);
                @SuppressWarnings("unchecked") List<File> files = (List<File>) fileTableView.getTableData();
                files.setComparator(getFileComparator(pair.key, pair.value));
            }
        }
    });
    fileTableView.getComponentMouseButtonListeners().add(new ComponentMouseButtonListener() {

        private int index = -1;

        @Override
        public boolean mouseClick(Component componentArgument, Mouse.Button button, int x, int y, int count) {
            boolean consumed = false;
            if (count == 1) {
                index = fileTableView.getRowAt(y);
            } else if (count == 2) {
                int indexLocal = fileTableView.getRowAt(y);
                if (indexLocal != -1 && indexLocal == this.index && fileTableView.isRowSelected(indexLocal)) {
                    File file = (File) fileTableView.getTableData().get(indexLocal);
                    if (file.isDirectory()) {
                        fileBrowser.setRootDirectory(file);
                        consumed = true;
                    }
                }
            }
            return consumed;
        }
    });
    fileBrowser.setFocusTraversalPolicy(new IndexFocusTraversalPolicy() {

        @Override
        public Component getNextComponent(Container container, Component componentArgument, FocusTraversalDirection direction) {
            Component nextComponent;
            if (componentArgument == null) {
                nextComponent = fileTableView;
            } else {
                nextComponent = super.getNextComponent(container, componentArgument, direction);
            }
            return nextComponent;
        }
    });
    fileTableView.setSort(TableViewFileRenderer.NAME_KEY, SortDirection.ASCENDING);
    fileTableView.getComponentTooltipListeners().add(new ComponentTooltipListener() {

        @Override
        public void tooltipTriggered(Component comp, int x, int y) {
            // Check that we are on the first column.
            if (fileTableView.getColumnAt(x) != 0) {
                return;
            }
            // Gets the underlying file
            int row = fileTableView.getRowAt(y);
            if (row < 0) {
                return;
            }
            File file = (File) fileTableView.getTableData().get(row);
            // Construct and show the tooltip.
            final Tooltip tooltip = new Tooltip();
            String text = null;
            if (file != null) {
                text = file.getName();
            }
            if (text == null || text.isEmpty()) {
                return;
            }
            TextArea toolTipTextArea = new TextArea();
            toolTipTextArea.setText(text);
            toolTipTextArea.getStyles().put(Style.wrapText, true);
            toolTipTextArea.getStyles().put(Style.backgroundColor, null);
            tooltip.setContent(toolTipTextArea);
            Point location = comp.getDisplay().getMouseLocation();
            x = location.x;
            y = location.y;
            // Ensure that the tooltip stays on screen
            Display display = comp.getDisplay();
            int tooltipHeight = tooltip.getPreferredHeight();
            if (y + tooltipHeight > display.getHeight()) {
                y -= tooltipHeight;
            }
            int tooltipXOffset = 16;
            int padding = 15;
            toolTipTextArea.setMaximumWidth(display.getWidth() - (x + tooltipXOffset + padding));
            tooltip.setLocation(x + tooltipXOffset, y);
            tooltip.open(comp.getWindow());
        }
    });
    rootDirectoryChanged(fileBrowser, null);
    selectedFilesChanged(fileBrowser, null);
}
Also used : FocusTraversalDirection(org.apache.pivot.wtk.FocusTraversalDirection) ComponentTooltipListener(org.apache.pivot.wtk.ComponentTooltipListener) TextArea(org.apache.pivot.wtk.TextArea) ListButtonSelectionListener(org.apache.pivot.wtk.ListButtonSelectionListener) TableViewSortListener(org.apache.pivot.wtk.TableViewSortListener) Span(org.apache.pivot.wtk.Span) ButtonPressListener(org.apache.pivot.wtk.ButtonPressListener) TextInputContentListener(org.apache.pivot.wtk.TextInputContentListener) Container(org.apache.pivot.wtk.Container) PushButton(org.apache.pivot.wtk.PushButton) ListButton(org.apache.pivot.wtk.ListButton) Button(org.apache.pivot.wtk.Button) ArrayList(org.apache.pivot.collections.ArrayList) List(org.apache.pivot.collections.List) Component(org.apache.pivot.wtk.Component) TextInput(org.apache.pivot.wtk.TextInput) TableViewSelectionListener(org.apache.pivot.wtk.TableViewSelectionListener) BXMLSerializer(org.apache.pivot.beans.BXMLSerializer) TableView(org.apache.pivot.wtk.TableView) SerializationException(org.apache.pivot.serialization.SerializationException) Keyboard(org.apache.pivot.wtk.Keyboard) Tooltip(org.apache.pivot.wtk.Tooltip) IOException(java.io.IOException) Sequence(org.apache.pivot.collections.Sequence) Point(org.apache.pivot.wtk.Point) Point(org.apache.pivot.wtk.Point) ListButton(org.apache.pivot.wtk.ListButton) ComponentKeyListener(org.apache.pivot.wtk.ComponentKeyListener) Mouse(org.apache.pivot.wtk.Mouse) FileBrowser(org.apache.pivot.wtk.FileBrowser) ComponentMouseButtonListener(org.apache.pivot.wtk.ComponentMouseButtonListener) File(java.io.File) Display(org.apache.pivot.wtk.Display)

Aggregations

SerializationException (org.apache.pivot.serialization.SerializationException)49 IOException (java.io.IOException)28 BXMLSerializer (org.apache.pivot.beans.BXMLSerializer)14 URL (java.net.URL)9 JSONSerializer (org.apache.pivot.json.JSONSerializer)9 ArrayList (org.apache.pivot.collections.ArrayList)8 Component (org.apache.pivot.wtk.Component)7 File (java.io.File)6 List (org.apache.pivot.collections.List)6 QueryException (org.apache.pivot.web.QueryException)6 ComponentMouseButtonListener (org.apache.pivot.wtk.ComponentMouseButtonListener)6 InputStream (java.io.InputStream)5 Sequence (org.apache.pivot.collections.Sequence)5 Button (org.apache.pivot.wtk.Button)5 ButtonPressListener (org.apache.pivot.wtk.ButtonPressListener)5 Mouse (org.apache.pivot.wtk.Mouse)5 PushButton (org.apache.pivot.wtk.PushButton)5 MalformedURLException (java.net.MalformedURLException)4 ScriptException (javax.script.ScriptException)4 TextInput (org.apache.pivot.wtk.TextInput)4