Example usage for com.google.common.collect BiMap remove

List of usage examples for com.google.common.collect BiMap remove

Introduction

In this page you can find the example usage for com.google.common.collect BiMap remove.

Prototype

V remove(Object key);

Source Link

Document

Removes the mapping for a key from this map if it is present (optional operation).

Usage

From source file:com.opengamma.bbg.util.BloombergDataUtils.java

private static <TKey, TValue> void changeKey(final TKey oldKey, final TKey newKey,
        final BiMap<TKey, TValue> map) {
    //REVIEW simon : is it ok that we discard duplicates here
    final TValue oldValue = map.remove(oldKey);
    map.put(newKey, oldValue);//w  ww  .  j a  v a  2 s . co  m
}

From source file:makeo.gadomancy.common.integration.thaumichorizions.IntegrationThaumicHorizions.java

private void undoSubstitution(String name) {
    Injector registry = new Injector(GameRegistry.Type.ITEM.getRegistry(),
            FMLControlledNamespacedRegistry.class);
    BiMap map = registry.invokeMethod("getPersistentSubstitutions");
    map.remove(name);
}

From source file:additionalpipes.utils.FrequencyMap.java

public void removeFreqName(String username, int freq) {
    checkNotNull(username);/* w  ww. j a va 2s.  com*/
    BiMap<Integer, String> freqMap = userMap.get(username);
    if (freqMap != null) {
        freqMap.remove(freq);
        userMapSorted.remove(username);
    }
}

From source file:br.ufpe.cin.emergo.analysis.ReversedMapLiftedFlowSet.java

public void putAndMerge(FlowSet flowSet, IConfigRep config) {
    boolean containsKey = map.containsKey(flowSet);
    boolean containsVal = map.containsValue(config);
    if (!containsKey && !containsVal) {
        map.put(flowSet, config);/*from   ww  w.  j  av  a  2 s.  co m*/
        return;
    }
    if (containsKey && containsVal) {
        IConfigRep inConfig = map.get(flowSet);
        FlowSet inFlowSet = map.inverse().get(config);
        map.remove(flowSet);
        ArraySparseSet unionFlowSet = new ArraySparseSet();
        inFlowSet.union(flowSet, unionFlowSet);
        putAndMerge(unionFlowSet, inConfig.union(config));
        return;
    }
    if (containsKey) {
        IConfigRep inConfig = map.get(flowSet);
        IConfigRep union = inConfig.union(config);
        map.remove(flowSet);
        putAndMerge(flowSet, union);
        return;
    }
    if (containsVal) {
        BiMap<IConfigRep, FlowSet> inverse = map.inverse();
        FlowSet inFlowSet = inverse.get(config);
        ArraySparseSet unionFlowSet = new ArraySparseSet();
        inFlowSet.union(flowSet, unionFlowSet);
        inverse.remove(config);
        putAndMerge(unionFlowSet, config);
        return;
    }
}

From source file:com.android.mail.ui.ConversationSelectionSet.java

private void removeAll(Collection<Long> ids) {
    synchronized (mLock) {
        final boolean initiallyNotEmpty = !mInternalMap.isEmpty();

        final BiMap<Long, String> inverseMap = mConversationUriToIdMap.inverse();

        for (Long id : ids) {
            mInternalMap.remove(id);/*from w ww . jav  a 2 s  . c  o  m*/
            inverseMap.remove(id);
        }

        ArrayList<ConversationSetObserver> observersCopy = Lists.newArrayList(mObservers);
        dispatchOnChange(observersCopy);
        if (mInternalMap.isEmpty() && initiallyNotEmpty) {
            dispatchOnEmpty(observersCopy);
        }
    }
}

From source file:de.keyle.knbte.Gui.java

public Gui(JFrame skilltreeCreatorFrame, File argFile) {
    if (argFile != null) {
        openFile(argFile);/*from  w w  w .  j a v  a  2s . c om*/
    }

    JMenuBar menuBar = new JMenuBar();

    JMenu menuFile = new JMenu("File");
    menuBar.add(menuFile);

    JMenuItem newMenuItem = new JMenuItem("New", NEW_ICON);
    newMenuItem.setAccelerator(KeyStroke.getKeyStroke('N', KeyEvent.CTRL_DOWN_MASK));
    menuFile.add(newMenuItem);
    JMenuItem openMenuItem = new JMenuItem("Open...", OPEN_ICON);
    openMenuItem.setAccelerator(KeyStroke.getKeyStroke('O', KeyEvent.CTRL_DOWN_MASK));
    menuFile.add(openMenuItem);
    JMenuItem saveMenuItem = new JMenuItem("Save...", SAVE_ICON);
    saveMenuItem.setAccelerator(KeyStroke.getKeyStroke('S', KeyEvent.CTRL_DOWN_MASK));
    menuFile.add(saveMenuItem);
    JMenuItem saveAsMenuItem = new JMenuItem("Save as...", SAVE_AS_ICON);
    saveAsMenuItem
            .setAccelerator(KeyStroke.getKeyStroke('S', KeyEvent.CTRL_DOWN_MASK + KeyEvent.ALT_DOWN_MASK));
    menuFile.add(saveAsMenuItem);
    menuFile.add(new JSeparator());
    JMenuItem exitMenuItem = new JMenuItem("Exit", EXIT_ICON);
    exitMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, KeyEvent.ALT_DOWN_MASK));
    menuFile.add(exitMenuItem);

    skilltreeCreatorFrame.setJMenuBar(menuBar);

    listAddButtonMenu = new JPopupMenu();

    JMenuItem byteMenuItem = new JMenuItem("Byte", BYTE_ICON);
    listAddButtonMenu.add(byteMenuItem);

    JMenuItem shortMenuItem = new JMenuItem("Short", SHORT_ICON);
    listAddButtonMenu.add(shortMenuItem);

    JMenuItem intMenuItem = new JMenuItem("Integer", INT_ICON);
    listAddButtonMenu.add(intMenuItem);

    JMenuItem longMenuItem = new JMenuItem("Long", LONG_ICON);
    listAddButtonMenu.add(longMenuItem);

    JMenuItem floatMenuItem = new JMenuItem("Float", FLOAT_ICON);
    listAddButtonMenu.add(floatMenuItem);

    JMenuItem doubleMenuItem = new JMenuItem("Double", DOUBLE_ICON);
    listAddButtonMenu.add(doubleMenuItem);

    JMenuItem byteArrayMenuItem = new JMenuItem("Byte Array", BYTE_ARRAY_ICON);
    listAddButtonMenu.add(byteArrayMenuItem);

    JMenuItem intArrayMenuItem = new JMenuItem("Integer Array", INT_ARRAY_ICON);
    listAddButtonMenu.add(intArrayMenuItem);

    JMenuItem stringMenuItem = new JMenuItem("String", STRING_ICON);
    listAddButtonMenu.add(stringMenuItem);

    JMenuItem compoundMenuItem = new JMenuItem("Compound", COMPOUND_ICON);
    listAddButtonMenu.add(compoundMenuItem);

    JMenuItem listMenuItem = new JMenuItem("List", LIST_ICON);
    listAddButtonMenu.add(listMenuItem);

    ActionListener saveListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            File fileToSaveTo = null;
            if (openedFile != null) {
                fileToSaveTo = openedFile;
            } else {
                int returnVal = fc.showSaveDialog(openFileButton);

                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    fileToSaveTo = fc.getSelectedFile();
                } else if (returnVal == JFileChooser.CANCEL_OPTION) {
                    return;
                }
            }
            if (fileToSaveTo != null) {
                TagCompound compound = (TagCompound) ((TagCompoundNode) tagTree.getModel().getRoot()).toTag();
                try {
                    TagStream.writeTag(compound, new FileOutputStream(fileToSaveTo), true);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    };
    ActionListener openListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {

            int returnVal = fc.showOpenDialog(openFileButton);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                System.out.println("Opening: " + file.getName());

                openFile(file);
            }
        }
    };
    ActionListener newListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            tagTree.setModel(new DefaultTreeModel(new TagCompoundNode(new TagCompound())));
            openedFile = null;
        }
    };

    listAddButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            listAddButtonMenu.show(listAddButton, listAddButton.getWidth() - listAddButtonMenu.getWidth(),
                    listAddButton.getHeight());
        }
    });
    openFileButton.addActionListener(openListener);
    openMenuItem.addActionListener(openListener);
    saveButton.addActionListener(saveListener);
    saveMenuItem.addActionListener(saveListener);
    newFileButton.addActionListener(newListener);
    newMenuItem.addActionListener(newListener);
    saveAsMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            File fileToSaveTo = null;
            int returnVal = fc.showSaveDialog(openFileButton);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                fileToSaveTo = fc.getSelectedFile();
            } else if (returnVal == JFileChooser.CANCEL_OPTION) {
                return;
            }
            if (fileToSaveTo != null) {
                TagCompound compound = (TagCompound) ((TagCompoundNode) tagTree.getModel().getRoot()).toTag();
                try {
                    TagStream.writeTag(compound, new FileOutputStream(fileToSaveTo), true);
                    openedFile = fileToSaveTo;
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    });
    exitMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            System.exit(0);
        }
    });
    changeNameButton.addActionListener(new ActionListener() {
        @Override
        @SuppressWarnings("unchecked")
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagCompoundNode parent = (TagCompoundNode) node.getParent();
            String key = parent.getKeyByNode(node);
            JTextField textField = new JTextField();
            textField.setText(key);
            int result = JOptionPane.showConfirmDialog(null, textField, "Enter a new Key",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (result == JOptionPane.OK_OPTION) {
                String newKey = textField.getText();
                if (parent.getNodeByKey(newKey) == null) {
                    BiMap<String, TagBaseNode> key2Node = (BiMap<String, TagBaseNode>) parent.getData();
                    key2Node.remove(key);
                    key2Node.put(newKey, node);
                    node.updateUserObject();
                    tagTree.updateUI();
                }
            }
        }
    });
    editValueButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            getSelectedNode().editValue();
            tagTree.updateUI();
        }
    });
    deleteTagButton.addActionListener(new ActionListener() {
        @Override
        @SuppressWarnings("unchecked")
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagBaseNode parent = (TagBaseNode) node.getParent();
            parent.remove(node);
            parent.updateUserObject();
            tagTree.updateUI();
        }
    });
    tagTree.addTreeSelectionListener(new TreeSelectionListener() {
        @Override
        public void valueChanged(TreeSelectionEvent event) {
            TagBaseNode selectedNode = getSelectedNode();
            if (selectedNode != null) {
                deleteTagButton.setEnabled(true);

                if (selectedNode.getParent() != null) {
                    if (selectedNode.getParent() instanceof TagCompoundNode) {
                        changeNameButton.setEnabled(true);
                    } else {
                        changeNameButton.setEnabled(false);
                    }
                } else {
                    changeNameButton.setEnabled(false);
                    deleteTagButton.setEnabled(false);
                }

                if (selectedNode instanceof TagCompoundNode) {
                    editValueButton.setEnabled(false);
                    byteAddButton.setEnabled(true);
                    shortAddButton.setEnabled(true);
                    intAddButton.setEnabled(true);
                    longAddButton.setEnabled(true);
                    floatAddButton.setEnabled(true);
                    doubleAddButton.setEnabled(true);
                    byteArrayAddButton.setEnabled(true);
                    intArrayAddButton.setEnabled(true);
                    stringAddButton.setEnabled(true);
                    compoundAddButton.setEnabled(true);
                    listAddButton.setEnabled(true);
                } else if (selectedNode instanceof TagListNode) {
                    TagType type = ((TagListNode) selectedNode).getListTagType();
                    editValueButton.setEnabled(false);
                    byteAddButton.setEnabled(type == TagType.Byte);
                    shortAddButton.setEnabled(type == TagType.Short);
                    intAddButton.setEnabled(type == TagType.Int);
                    longAddButton.setEnabled(type == TagType.Long);
                    floatAddButton.setEnabled(type == TagType.Float);
                    doubleAddButton.setEnabled(type == TagType.Double);
                    byteArrayAddButton.setEnabled(type == TagType.Byte_Array);
                    intArrayAddButton.setEnabled(type == TagType.Int_Array);
                    stringAddButton.setEnabled(type == TagType.String);
                    compoundAddButton.setEnabled(type == TagType.Compound);
                    listAddButton.setEnabled(type == TagType.List);
                } else {
                    editValueButton.setEnabled(true);
                    byteAddButton.setEnabled(false);
                    shortAddButton.setEnabled(false);
                    intAddButton.setEnabled(false);
                    longAddButton.setEnabled(false);
                    floatAddButton.setEnabled(false);
                    doubleAddButton.setEnabled(false);
                    byteArrayAddButton.setEnabled(false);
                    intArrayAddButton.setEnabled(false);
                    stringAddButton.setEnabled(false);
                    compoundAddButton.setEnabled(false);
                    listAddButton.setEnabled(false);
                }
            } else {
                deleteTagButton.setEnabled(false);
                editValueButton.setEnabled(false);
                changeNameButton.setEnabled(false);
                byteAddButton.setEnabled(false);
                shortAddButton.setEnabled(false);
                intAddButton.setEnabled(false);
                longAddButton.setEnabled(false);
                floatAddButton.setEnabled(false);
                doubleAddButton.setEnabled(false);
                byteArrayAddButton.setEnabled(false);
                intArrayAddButton.setEnabled(false);
                stringAddButton.setEnabled(false);
                compoundAddButton.setEnabled(false);
                listAddButton.setEnabled(false);
            }
        }
    });
    byteAddButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagBaseNode newNode = new TagByteNode(new TagByte(false));
            addToNode(node, newNode);
        }
    });
    shortAddButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagBaseNode newNode = new TagShortNode(new TagShort((short) 0));
            addToNode(node, newNode);
        }
    });
    intAddButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagBaseNode newNode = new TagIntNode(new TagInt(0));
            addToNode(node, newNode);
        }
    });
    longAddButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagBaseNode newNode = new TagLongNode(new TagLong(0L));
            addToNode(node, newNode);
        }
    });
    floatAddButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagBaseNode newNode = new TagFloatNode(new TagFloat(0F));
            addToNode(node, newNode);
        }
    });
    doubleAddButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagBaseNode newNode = new TagDoubleNode(new TagDouble(0D));
            addToNode(node, newNode);
        }
    });
    byteArrayAddButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagBaseNode newNode = new TagByteArrayNode(new TagByteArray(new byte[0]));
            addToNode(node, newNode);
        }
    });
    intArrayAddButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagBaseNode newNode = new TagIntArrayNode(new TagIntArray(new int[0]));
            addToNode(node, newNode);
        }
    });
    stringAddButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagBaseNode newNode = new TagStringNode(new TagString(""));
            addToNode(node, newNode);
        }
    });
    compoundAddButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagBaseNode newNode = new TagCompoundNode(new TagCompound());
            addToNode(node, newNode);
        }
    });
    byteMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagListNode newNode = new TagListNode(new TagList());
            newNode.type = TagType.Byte;
            addToNode(node, newNode);
        }
    });
    shortMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagListNode newNode = new TagListNode(new TagList());
            newNode.type = TagType.Short;
            addToNode(node, newNode);
        }
    });
    intMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagListNode newNode = new TagListNode(new TagList());
            newNode.type = TagType.Int;
            addToNode(node, newNode);
        }
    });
    longMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagListNode newNode = new TagListNode(new TagList());
            newNode.type = TagType.Long;
            addToNode(node, newNode);
        }
    });
    floatMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagListNode newNode = new TagListNode(new TagList());
            newNode.type = TagType.Float;
            addToNode(node, newNode);
        }
    });
    doubleMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagListNode newNode = new TagListNode(new TagList());
            newNode.type = TagType.Double;
            addToNode(node, newNode);
        }
    });
    byteArrayMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagListNode newNode = new TagListNode(new TagList());
            newNode.type = TagType.Byte_Array;
            addToNode(node, newNode);
        }
    });
    byteMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagListNode newNode = new TagListNode(new TagList());
            newNode.type = TagType.Byte;
            addToNode(node, newNode);
        }
    });
    intArrayMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagListNode newNode = new TagListNode(new TagList());
            newNode.type = TagType.Int_Array;
            addToNode(node, newNode);
        }
    });
    stringMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagListNode newNode = new TagListNode(new TagList());
            newNode.type = TagType.String;
            addToNode(node, newNode);
        }
    });
    compoundMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagListNode newNode = new TagListNode(new TagList());
            newNode.type = TagType.Compound;
            addToNode(node, newNode);
        }
    });
    listMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            TagBaseNode node = getSelectedNode();
            TagListNode newNode = new TagListNode(new TagList());
            newNode.type = TagType.List;
            addToNode(node, newNode);
        }
    });
}

From source file:com.android.tools.idea.editors.navigation.NavigationView.java

private <K, V extends Component> void removeLeftovers(BiMap<K, V> assoc, Collection<K> a) {
    for (Map.Entry<K, V> e : new ArrayList<Map.Entry<K, V>>(assoc.entrySet())) {
        K k = e.getKey();/*  w w  w.j  a v a2 s.co m*/
        V v = e.getValue();
        if (!a.contains(k)) {
            assoc.remove(k);
            remove(v);
            repaint();
        }
    }
}

From source file:com.android.sdklib.repository.targets.AndroidTargetManager.java

@NonNull
private Map<LocalPackage, IAndroidTarget> getTargetMap(@NonNull ProgressIndicator progress) {
    if (mTargets == null) {
        Map<String, String> newErrors = Maps.newHashMap();
        RepoManager manager = mSdkHandler.getSdkManager(progress);
        Map<AndroidVersion, PlatformTarget> platformTargets = Maps.newHashMap();
        BiMap<IAndroidTarget, LocalPackage> tempTargetToPackage = HashBiMap.create();
        for (LocalPackage p : manager.getPackages().getLocalPackages().values()) {
            TypeDetails details = p.getTypeDetails();
            if (details instanceof DetailsTypes.PlatformDetailsType) {
                try {
                    PlatformTarget target = new PlatformTarget(p, mSdkHandler, mFop, progress);
                    AndroidVersion androidVersion = target.getVersion();
                    // If we've already seen a platform with this version, replace the existing
                    // with this if this is the "real" package (with the expected path).
                    // Otherwise, don't create a duplicate.
                    PlatformTarget existing = platformTargets.get(androidVersion);
                    if (existing == null || p.getPath().equals(DetailsTypes.getPlatformPath(androidVersion))) {
                        if (existing != null) {
                            tempTargetToPackage.remove(existing);
                        }/*from   ww w. j  a va 2 s. co m*/
                        platformTargets.put(androidVersion, target);
                        tempTargetToPackage.put(target, p);
                    }
                } catch (IllegalArgumentException e) {
                    newErrors.put(p.getPath(), e.getMessage());
                }
            }
        }
        for (LocalPackage p : manager.getPackages().getLocalPackages().values()) {
            TypeDetails details = p.getTypeDetails();
            if (details instanceof DetailsTypes.AddonDetailsType) {
                AndroidVersion addonVersion = ((DetailsTypes.AddonDetailsType) details).getAndroidVersion();
                PlatformTarget baseTarget = platformTargets.get(addonVersion);
                if (baseTarget != null) {
                    tempTargetToPackage.put(new AddonTarget(p, baseTarget,
                            mSdkHandler.getSystemImageManager(progress), progress, mFop), p);
                }
            }
        }
        Map<LocalPackage, IAndroidTarget> result = Maps.newTreeMap(TARGET_COMPARATOR);
        result.putAll(tempTargetToPackage.inverse());
        for (LocalPackage p : manager.getPackages()
                .getLocalPackagesForPrefix(SdkConstants.FD_ANDROID_SOURCES)) {
            TypeDetails details = p.getTypeDetails();
            if (details instanceof DetailsTypes.ApiDetailsType) {
                PlatformTarget target = platformTargets
                        .get(((DetailsTypes.ApiDetailsType) details).getAndroidVersion());
                if (target != null) {
                    target.setSources(p.getLocation());
                }
            }
        }
        mTargets = result;
        mLoadErrors = newErrors;
    }
    return mTargets;
}

From source file:net.minecraftforge.gradle.patcher.PatcherPlugin.java

/**
 * Sorts the project into the list of patches on each other.
 * Throws GradleConfigurationException if the projects cannot be fitted into the list.
 * Doesnt support potential patching loops, but the clean project cant patch anything, so its unlikely to happen.
 * @return list of sorted projects/* www . ja  va  2  s  . c om*/
 */
private List<PatcherProject> sortByPatching(NamedDomainObjectContainer<PatcherProject> projects) {
    // patcher->patched
    BiMap<PatcherProject, PatcherProject> tempMap = HashBiMap.create();

    for (PatcherProject project : projects) {
        String patchAfter = project.getPatchAfter();
        PatcherProject toPut;

        if (patchAfter.equals("clean")) {
            toPut = null;
        } else {
            toPut = projects.findByName(patchAfter);

            if (toPut == null)
                throw new GradleConfigurationException(
                        "Project " + patchAfter + " does not exist! You cannot patch after it!");

            if (toPut.isApplyMcpPatches() && !project.isApplyMcpPatches()) {
                // its trying to apply SRG patches after a project that does MCP patches??
                // IMPOSSIBRU!
                throw new GradleConfigurationException("Project " + patchAfter
                        + " applies SRG named patches, and is attempting to patch after a project that uses MCP named patches! THATS IMPOSSIBRU!");
            }
        }

        try {
            tempMap.put(project, toPut);
        } catch (IllegalArgumentException e) {
            // must exist already.. thus a duplicate value..
            throw new GradleConfigurationException(
                    "2 projects cannot patch after the same project '" + toPut == null ? "clean"
                            : toPut.getName() + "'!");
        }
    }

    // now  patched->patcher
    tempMap = tempMap.inverse();

    ArrayList<PatcherProject> list = new ArrayList<PatcherProject>(projects.size());
    PatcherProject key = tempMap.remove(null); // null is clean
    while (key != null) {
        list.add(key);
        key = tempMap.remove(key);
    }

    return list;
}

From source file:com.moz.fiji.schema.layout.FijiTableLayout.java

/**
 * Constructs a FijiTableLayout from an Avro descriptor and an optional reference layout.
 *
 * @param desc Avro layout descriptor (relative to the reference layout).
 * @param reference Optional reference layout, or null.
 * @throws InvalidLayoutException if the descriptor is invalid or inconsistent wrt reference.
 *//*from   w ww .  j a  v a2  s.  c o  m*/
private FijiTableLayout(TableLayoutDesc desc, FijiTableLayout reference) throws InvalidLayoutException {
    // Deep-copy the descriptor to prevent mutating a parameter:
    mDesc = TableLayoutDesc.newBuilder(Preconditions.checkNotNull(desc)).build();

    // Ensure the array of locality groups is mutable:
    mDesc.setLocalityGroups(Lists.newArrayList(mDesc.getLocalityGroups()));

    // Check that the version specified in the layout matches the features used.
    // Any compatibility checks belong in this section.
    mLayoutVersion = computeLayoutVersion(mDesc.getVersion());

    if (!Objects.equal(LAYOUT_PROTOCOL_NAME, mLayoutVersion.getProtocolName())) {
        final String exceptionMessage;
        if (Objects.equal(Versions.LAYOUT_FIJI_1_0_0_DEPRECATED.getProtocolName(),
                mLayoutVersion.getProtocolName())) {
            // Warn the user if they tried a version number like 'fiji-0.9' or 'fiji-1.1'.
            exceptionMessage = String.format(
                    "Deprecated layout version protocol '%s' only valid for version '%s',"
                            + " but received version '%s'. You should specify a layout version protocol"
                            + " as '%s-x.y', not '%s-x.y'.",
                    Versions.LAYOUT_FIJI_1_0_0_DEPRECATED.getProtocolName(),
                    Versions.LAYOUT_FIJI_1_0_0_DEPRECATED, mLayoutVersion, LAYOUT_PROTOCOL_NAME,
                    Versions.LAYOUT_FIJI_1_0_0_DEPRECATED.getProtocolName());
        } else {
            exceptionMessage = String.format("Invalid version protocol: '%s'. Expected '%s'.",
                    mLayoutVersion.getProtocolName(), LAYOUT_PROTOCOL_NAME);
        }
        throw new InvalidLayoutException(exceptionMessage);
    }

    if (Versions.MAX_LAYOUT_VERSION.compareTo(mLayoutVersion) < 0) {
        throw new InvalidLayoutException("The maximum layout version we support is "
                + Versions.MAX_LAYOUT_VERSION + "; this layout requires " + mLayoutVersion);
    } else if (Versions.MIN_LAYOUT_VERSION.compareTo(mLayoutVersion) > 0) {
        throw new InvalidLayoutException("The minimum layout version we support is "
                + Versions.MIN_LAYOUT_VERSION + "; this layout requires " + mLayoutVersion);
    }

    // max_filesize and memstore_flushsize were introduced in version 1.2.
    if (Versions.BLOCK_SIZE_LAYOUT_VERSION.compareTo(mLayoutVersion) > 0) {
        if (mDesc.getMaxFilesize() != null) {
            // Cannot use max_filesize if this is the case.
            throw new InvalidLayoutException("Support for specifying max_filesize begins with layout version "
                    + Versions.BLOCK_SIZE_LAYOUT_VERSION.toString());
        }

        if (mDesc.getMemstoreFlushsize() != null) {
            // Cannot use memstore_flushsize if this is the case.
            throw new InvalidLayoutException(
                    "Support for specifying memstore_flushsize begins with layout version "
                            + Versions.BLOCK_SIZE_LAYOUT_VERSION);
        }
    } else {
        if (mDesc.getMaxFilesize() != null && mDesc.getMaxFilesize() <= 0) {
            throw new InvalidLayoutException("max_filesize must be greater than 0");
        }

        if (mDesc.getMemstoreFlushsize() != null && mDesc.getMemstoreFlushsize() <= 0) {
            throw new InvalidLayoutException("memstore_flushsize must be greater than 0");
        }
    }

    // Ability to configure column name translation was introduced in version 1.5
    if (Versions.CONFIGURE_COLUMN_NAME_TRANSLATION_VERSION.compareTo(mLayoutVersion) > 0) {
        if (mDesc.getColumnNameTranslator() != ColumnNameTranslator.SHORT) {
            throw new InvalidLayoutException(
                    "Support for specifiying non-short column name translators begins with layout version "
                            + Versions.CONFIGURE_COLUMN_NAME_TRANSLATION_VERSION);
        }
    }

    // Composite keys and RowKeyFormat2 was introduced in version 1.1.
    if (Versions.RKF2_LAYOUT_VERSION.compareTo(mLayoutVersion) > 0
            && mDesc.getKeysFormat() instanceof RowKeyFormat2) {
        // Cannot use RowKeyFormat2 if this is the case.
        throw new InvalidLayoutException(
                "Support for specifying keys_format as a RowKeyFormat2 begins with layout version "
                        + Versions.RKF2_LAYOUT_VERSION);
    }

    if (!isValidName(getName())) {
        throw new InvalidLayoutException(String.format("Invalid table name: '%s'.", getName()));
    }

    if (reference != null) {
        if (!getName().equals(reference.getName())) {
            throw new InvalidLayoutException(String.format(
                    "Invalid layout update: layout name '%s' does not match reference layout name '%s'.",
                    getName(), reference.getName()));
        }

        if (!mDesc.getKeysFormat().equals(reference.getDesc().getKeysFormat())) {
            throw new InvalidLayoutException(String.format(
                    "Invalid layout update from reference row keys format '%s' to row keys format '%s'.",
                    reference.getDesc().getKeysFormat(), mDesc.getKeysFormat()));
        }
    }

    // Layout ID:
    if (mDesc.getLayoutId() == null) {
        try {
            final long refLayoutId = (reference == null) ? 0
                    : Long.parseLong(reference.getDesc().getLayoutId());
            final long layoutId = refLayoutId + 1;
            mDesc.setLayoutId(Long.toString(layoutId));
        } catch (NumberFormatException nfe) {
            throw new InvalidLayoutException(
                    String.format("Reference layout for table '%s' has an invalid layout ID: '%s'", getName(),
                            reference.getDesc().getLayoutId()));
        }
    }

    if (mDesc.getKeysFormat() instanceof RowKeyFormat) {
        isValidRowKeyFormat1((RowKeyFormat) mDesc.getKeysFormat());
    } else if (mDesc.getKeysFormat() instanceof RowKeyFormat2) {
        // Check validity of row key format.
        isValidRowKeyFormat2((RowKeyFormat2) mDesc.getKeysFormat());
    }

    // Build localities:

    /**
     * Reference map from locality group name to locality group ID.
     * Entries are removed as we process locality group descriptors in the new layout.
     * At the end of the process, this map must be empty.
     */
    final BiMap<String, ColumnId> refLGIdMap = (reference == null) ? HashBiMap.<String, ColumnId>create()
            : HashBiMap.create(reference.mLocalityGroupIdNameMap.inverse());

    /** Map of locality groups in the new layout. */
    final List<LocalityGroupLayout> localityGroups = Lists.newArrayList();
    final Map<String, LocalityGroupLayout> lgMap = Maps.newHashMap();
    final BiMap<ColumnId, String> idMap = HashBiMap.create();

    /** Locality group with no ID assigned yet. */
    final List<LocalityGroupLayout> unassigned = Lists.newArrayList();

    /** All the families in the table. */
    final List<FamilyLayout> families = Lists.newArrayList();

    /** Map from family name or alias to family layout. */
    final Map<String, FamilyLayout> familyMap = Maps.newHashMap();

    /** All primary column names (including map-type families). */
    final Set<FijiColumnName> columnNames = Sets.newTreeSet();

    final Map<FijiColumnName, ColumnLayout> columnMap = Maps.newHashMap();

    final Iterator<LocalityGroupDesc> itLGDesc = mDesc.getLocalityGroups().iterator();
    while (itLGDesc.hasNext()) {
        final LocalityGroupDesc lgDesc = itLGDesc.next();
        final boolean isRename = (lgDesc.getRenamedFrom() != null);
        final String refLGName = isRename ? lgDesc.getRenamedFrom() : lgDesc.getName();
        lgDesc.setRenamedFrom(null);
        if (isRename && (reference == null)) {
            throw new InvalidLayoutException(String
                    .format("Invalid rename: no reference table layout for locality group '%s'.", refLGName));
        }
        final LocalityGroupLayout refLGLayout = (reference != null) ? reference.mLocalityGroupMap.get(refLGName)
                : null;
        if (isRename && (refLGLayout == null)) {
            throw new InvalidLayoutException(
                    String.format("Invalid rename: cannot find reference locality group '%s'.", refLGName));
        }

        final ColumnId refLGId = refLGIdMap.remove(refLGName);

        if (lgDesc.getDelete()) {
            // This locality group is deleted:
            if (refLGId == null) {
                throw new InvalidLayoutException(String.format(
                        "Attempting to delete locality group '%s' unknown in reference layout.", refLGName));
            }
            itLGDesc.remove();
            continue;
        }

        // BloomType, block_size were introduced in version 1.2.
        if (Versions.BLOCK_SIZE_LAYOUT_VERSION.compareTo(mLayoutVersion) > 0) {
            if (lgDesc.getBlockSize() != null) {
                // Cannot use max_filesize if this is the case.
                throw new InvalidLayoutException("Support for specifying block_size begins with layout version "
                        + Versions.BLOCK_SIZE_LAYOUT_VERSION);
            }
            if (lgDesc.getBloomType() != null) {
                // Cannot use bloom_type if this is the case.
                throw new InvalidLayoutException("Support for specifying bloom_type begins with layout version "
                        + Versions.BLOCK_SIZE_LAYOUT_VERSION);
            }
        } else {
            if (lgDesc.getBlockSize() != null && lgDesc.getBlockSize() <= 0) {
                throw new InvalidLayoutException("block_size must be greater than 0");
            }
        }

        final LocalityGroupLayout lgLayout = new LocalityGroupLayout(lgDesc, refLGLayout);
        localityGroups.add(lgLayout);
        for (String lgName : lgLayout.getNames()) {
            Preconditions.checkState(lgMap.put(lgName, lgLayout) == null,
                    "Duplicate locality group name: " + lgName);
        }

        if (lgLayout.getId() != null) {
            final String previous = idMap.put(lgLayout.getId(), lgLayout.getName());
            Preconditions.checkState(previous == null,
                    String.format("Duplicate locality group ID '%s' associated to '%s' and '%s'.",
                            lgLayout.getId(), lgLayout.getName(), previous));
        } else {
            unassigned.add(lgLayout);
        }

        families.addAll(lgLayout.getFamilies());
        for (FamilyLayout familyLayout : lgLayout.getFamilies()) {
            for (String familyName : familyLayout.getNames()) {
                if (null != familyMap.put(familyName, familyLayout)) {
                    throw new InvalidLayoutException(
                            String.format("Layout for table '%s' contains duplicate family name '%s'.",
                                    getName(), familyName));
                }
            }

            if (familyLayout.isMapType()) {
                Preconditions.checkState(columnNames.add(FijiColumnName.create(familyLayout.getName(), null)));
            }

            for (ColumnLayout columnLayout : familyLayout.getColumns()) {
                for (String columnName : columnLayout.getNames()) {
                    final FijiColumnName column = FijiColumnName.create(familyLayout.getName(), columnName);
                    if (null != columnMap.put(column, columnLayout)) {
                        throw new InvalidLayoutException(String.format(
                                "Layout for table '%s' contains duplicate column '%s'.", getName(), column));
                    }
                }
                Preconditions.checkState(
                        columnNames.add(FijiColumnName.create(familyLayout.getName(), columnLayout.getName())));
            }
        }
    }

    if (!refLGIdMap.isEmpty()) {
        throw new InvalidLayoutException(String.format("Missing descriptor(s) for locality group(s): %s.",
                Joiner.on(",").join(refLGIdMap.keySet())));
    }

    mLocalityGroups = ImmutableList.copyOf(localityGroups);
    mLocalityGroupMap = ImmutableMap.copyOf(lgMap);

    mFamilies = ImmutableList.copyOf(families);
    mFamilyMap = ImmutableMap.copyOf(familyMap);

    mColumnNames = ImmutableSet.copyOf(columnNames);

    // Assign IDs to locality groups:
    int nextColumnId = 1;
    for (LocalityGroupLayout localityGroup : unassigned) {
        Preconditions.checkState(localityGroup.getId() == null);
        while (true) {
            final ColumnId columnId = new ColumnId(nextColumnId);
            nextColumnId += 1;
            if (!idMap.containsKey(columnId)) {
                localityGroup.setId(columnId);
                idMap.put(columnId, localityGroup.getName());
                break;
            }
        }
    }

    mLocalityGroupIdNameMap = ImmutableBiMap.copyOf(idMap);
}