Example usage for java.util Collections list

List of usage examples for java.util Collections list

Introduction

In this page you can find the example usage for java.util Collections list.

Prototype

public static <T> ArrayList<T> list(Enumeration<T> e) 

Source Link

Document

Returns an array list containing the elements returned by the specified enumeration in the order they are returned by the enumeration.

Usage

From source file:com.mirth.connect.client.ui.browsers.message.MessageBrowser.java

/**
 * Sets the properties and adds the listeners for the Message Table. No data is loaded at this
 * point.//from w  ww . j a  va  2s  .c o  m
 */
private void makeMessageTable() {
    messageTreeTable.setDragEnabled(true);
    messageTreeTable.setSortable(false);
    messageTreeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    messageTreeTable.setColumnFactory(new MessageBrowserTableColumnFactory());
    messageTreeTable.setLeafIcon(null);
    messageTreeTable.setOpenIcon(null);
    messageTreeTable.setClosedIcon(null);
    messageTreeTable.setAutoCreateColumnsFromModel(false);
    messageTreeTable.setMirthColumnControlEnabled(true);
    messageTreeTable.setShowGrid(true, true);
    messageTreeTable.setHorizontalScrollEnabled(true);
    messageTreeTable.setPreferredScrollableViewportSize(messageTreeTable.getPreferredSize());
    messageTreeTable.setMirthTransferHandlerEnabled(true);

    tableModel = new MessageBrowserTableModel(columnMap.size());
    // Add a blank column to the column initially, otherwise it return an exception on load
    // Columns will be re-generated when the message browser is viewed
    tableModel.setColumnIdentifiers(Arrays.asList(new String[] { "" }));
    messageTreeTable.setTreeTableModel(tableModel);

    // Sets the alternating highlighter for the table
    if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) {
        Highlighter highlighter = HighlighterFactory.createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR,
                UIConstants.BACKGROUND_COLOR);
        messageTreeTable.setHighlighters(highlighter);
    }

    // Add the listener for when the table selection changes
    messageTreeTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent evt) {
            MessageListSelected(evt);
        }

    });

    // Add the mouse listener
    messageTreeTable.addMouseListener(new java.awt.event.MouseAdapter() {

        public void mousePressed(java.awt.event.MouseEvent evt) {
            checkMessageSelectionAndPopupMenu(evt);
        }

        public void mouseReleased(java.awt.event.MouseEvent evt) {
            checkMessageSelectionAndPopupMenu(evt);
        }

        // Opens the send message dialog when a message is double clicked.
        // If the root message or source connector is selected, select all destination connectors initially
        // If a destination connector is selected, select only that destination connector initially
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            if (evt.getClickCount() >= 2) {
                int row = getSelectedMessageIndex();
                if (row >= 0) {
                    MessageBrowserTableNode messageNode = (MessageBrowserTableNode) messageTreeTable
                            .getPathForRow(row).getLastPathComponent();
                    if (messageNode.isNodeActive()) {
                        Long messageId = messageNode.getMessageId();
                        Integer metaDataId = messageNode.getMetaDataId();

                        Message currentMessage = messageCache.get(messageId);
                        ConnectorMessage connectorMessage = currentMessage.getConnectorMessages()
                                .get(metaDataId);
                        List<Integer> selectedMetaDataIds = new ArrayList<Integer>();

                        Map<String, Object> sourceMap = new HashMap<String, Object>();
                        if (connectorMessage.getSourceMap() != null) {
                            sourceMap.putAll(connectorMessage.getSourceMap());
                            // Remove the destination set if it exists, because that will be determined by the selected metadata IDs
                            sourceMap.remove("destinationSet");
                        }

                        if (metaDataId == 0) {
                            selectedMetaDataIds = null;
                        } else {
                            selectedMetaDataIds.add(metaDataId);
                        }

                        if (connectorMessage.getRaw() != null) {
                            parent.editMessageDialog.setPropertiesAndShow(
                                    connectorMessage.getRaw().getContent(),
                                    connectorMessage.getRaw().getDataType(), channelId,
                                    parent.dashboardPanel.getDestinationConnectorNames(channelId),
                                    selectedMetaDataIds, sourceMap);
                        }
                    }
                }
            }
        }
    });

    // Key Listener trigger for DEL
    messageTreeTable.addKeyListener(new KeyAdapter() {

        public void keyPressed(KeyEvent e) {
            int row = getSelectedMessageIndex();
            if (row >= 0) {
                if (e.getKeyCode() == KeyEvent.VK_DELETE) {
                    MessageBrowserTableNode messageNode = (MessageBrowserTableNode) messageTreeTable
                            .getPathForRow(row).getLastPathComponent();

                    if (messageNode.isNodeActive()) {
                        parent.doRemoveMessage();
                    }

                } else if (descriptionTabbedPane.getTitleAt(descriptionTabbedPane.getSelectedIndex())
                        .equals("Messages")) {
                    if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                        List<AbstractButton> buttons = Collections.list(messagesGroup.getElements());
                        boolean passedSelected = false;
                        for (int i = buttons.size() - 1; i >= 0; i--) {
                            AbstractButton button = buttons.get(i);
                            if (passedSelected && button.isShowing()) {
                                lastUserSelectedMessageType = buttons.get(i).getText();
                                updateMessageRadioGroup();
                                break;
                            } else if (button.isSelected()) {
                                passedSelected = true;
                            }
                        }
                    } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                        List<AbstractButton> buttons = Collections.list(messagesGroup.getElements());
                        boolean passedSelected = false;
                        for (int i = 0; i < buttons.size(); i++) {
                            AbstractButton button = buttons.get(i);
                            if (passedSelected && button.isShowing()) {
                                lastUserSelectedMessageType = buttons.get(i).getText();
                                updateMessageRadioGroup();
                                break;
                            } else if (button.isSelected()) {
                                passedSelected = true;
                            }
                        }
                    }
                }
            }

        }
    });
}

From source file:org.andromda.cartridges.gui.metafacades.GuiUseCaseLogicImpl.java

/**
 * Given a root use-case, finds the node in the hierarchy that represent the argument GuiUseCase node.
 *//* w ww . j  av a  2  s .co m*/
private UseCaseNode findNode(final UseCaseNode root, final GuiUseCase useCase) {

    UseCaseNode useCaseNode = null;

    final List nodeList = Collections.list(root.breadthFirstEnumeration());

    for (final Iterator nodeIterator = nodeList.iterator(); nodeIterator.hasNext() && (useCaseNode == null);) {

        final UseCaseNode node = (UseCaseNode) nodeIterator.next();

        if (useCase.equals(node.getUserObject())) {

            useCaseNode = node;

        }

    }

    return useCaseNode;

}

From source file:org.apache.openejb.config.DeploymentLoader.java

private void addBeansXmls(final AppModule appModule) {
    final List<URL> urls = appModule.getAdditionalLibraries();
    final URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[urls.size()]));

    final ArrayList<URL> xmls;
    try {/*w w  w  .  ja va 2 s.  c  om*/
        xmls = Collections.list(loader.getResources("META-INF/beans.xml"));
    } catch (final IOException e) {

        return;
    }

    final CompositeBeans complete = new CompositeBeans();
    for (final URL url : xmls) {
        if (url == null) {
            continue;
        }
        mergeBeansXml(complete, url);
    }

    if (complete.getDiscoveryByUrl().isEmpty()) {
        return;
    }
    complete.removeDuplicates();

    IAnnotationFinder finder;
    try {
        finder = FinderFactory.createFinder(appModule);
    } catch (final Exception e) {
        finder = new FinderFactory.ModuleLimitedFinder(new FinderFactory.OpenEJBAnnotationFinder(
                new WebappAggregatedArchive(appModule.getClassLoader(), appModule.getAltDDs(), xmls)));
    }
    appModule.setEarLibFinder(finder);

    final EjbModule ejbModule = new EjbModule(appModule.getClassLoader(),
            EAR_SCOPED_CDI_BEANS + appModule.getModuleId(), new EjbJar(), new OpenejbJar());
    ejbModule.setBeans(complete);
    ejbModule.setFinder(finder);
    ejbModule.setEjbJar(new EmptyEjbJar());

    appModule.getEjbModules().add(ejbModule);
}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private void handleCopyBlob(HttpServletRequest request, HttpServletResponse response, InputStream is,
        BlobStore blobStore, String destContainerName, String destBlobName) throws IOException, S3Exception {
    String copySourceHeader = request.getHeader("x-amz-copy-source");
    copySourceHeader = URLDecoder.decode(copySourceHeader, "UTF-8");
    if (copySourceHeader.startsWith("/")) {
        // Some clients like boto do not include the leading slash
        copySourceHeader = copySourceHeader.substring(1);
    }//from  w  w w.j  a va  2 s. c  om
    String[] path = copySourceHeader.split("/", 2);
    if (path.length != 2) {
        throw new S3Exception(S3ErrorCode.INVALID_REQUEST);
    }
    String sourceContainerName = path[0];
    String sourceBlobName = path[1];
    boolean replaceMetadata = "REPLACE".equalsIgnoreCase(request.getHeader("x-amz-metadata-directive"));

    if (sourceContainerName.equals(destContainerName) && sourceBlobName.equals(destBlobName)
            && !replaceMetadata) {
        throw new S3Exception(S3ErrorCode.INVALID_REQUEST);
    }

    CopyOptions.Builder options = CopyOptions.builder();

    String ifMatch = request.getHeader("x-amz-copy-source-if-match");
    if (ifMatch != null) {
        options.ifMatch(ifMatch);
    }
    String ifNoneMatch = request.getHeader("x-amz-copy-source-if-none-match");
    if (ifNoneMatch != null) {
        options.ifNoneMatch(ifNoneMatch);
    }
    long ifModifiedSince = request.getDateHeader("x-amz-copy-source-if-modified-since");
    if (ifModifiedSince != -1) {
        options.ifModifiedSince(new Date(ifModifiedSince));
    }
    long ifUnmodifiedSince = request.getDateHeader("x-amz-copy-source-if-unmodified-since");
    if (ifUnmodifiedSince != -1) {
        options.ifUnmodifiedSince(new Date(ifUnmodifiedSince));
    }

    if (replaceMetadata) {
        ContentMetadataBuilder contentMetadata = ContentMetadataBuilder.create();
        ImmutableMap.Builder<String, String> userMetadata = ImmutableMap.builder();
        for (String headerName : Collections.list(request.getHeaderNames())) {
            String headerValue = Strings.nullToEmpty(request.getHeader(headerName));
            if (headerName.equalsIgnoreCase(HttpHeaders.CACHE_CONTROL)) {
                contentMetadata.cacheControl(headerValue);
            } else if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_DISPOSITION)) {
                contentMetadata.contentDisposition(headerValue);
            } else if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_ENCODING)) {
                contentMetadata.contentEncoding(headerValue);
            } else if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LANGUAGE)) {
                contentMetadata.contentLanguage(headerValue);
            } else if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_TYPE)) {
                contentMetadata.contentType(headerValue);
            } else if (startsWithIgnoreCase(headerName, USER_METADATA_PREFIX)) {
                userMetadata.put(headerName.substring(USER_METADATA_PREFIX.length()), headerValue);
            }
            // TODO: Expires
        }
        options.contentMetadata(contentMetadata.build());
        options.userMetadata(userMetadata.build());
    }

    String eTag;
    try {
        eTag = blobStore.copyBlob(sourceContainerName, sourceBlobName, destContainerName, destBlobName,
                options.build());
    } catch (KeyNotFoundException knfe) {
        throw new S3Exception(S3ErrorCode.NO_SUCH_KEY, knfe);
    }

    // TODO: jclouds should include this in CopyOptions
    String cannedAcl = request.getHeader("x-amz-acl");
    if (cannedAcl != null && !cannedAcl.equalsIgnoreCase("private")) {
        handleSetBlobAcl(request, response, is, blobStore, destContainerName, destBlobName);
    }

    BlobMetadata blobMetadata = blobStore.blobMetadata(destContainerName, destBlobName);
    try (Writer writer = response.getWriter()) {
        XMLStreamWriter xml = xmlOutputFactory.createXMLStreamWriter(writer);
        xml.writeStartDocument();
        xml.writeStartElement("CopyObjectResult");
        xml.writeDefaultNamespace(AWS_XMLNS);

        writeSimpleElement(xml, "LastModified", formatDate(blobMetadata.getLastModified()));
        writeSimpleElement(xml, "ETag", maybeQuoteETag(eTag));

        xml.writeEndElement();
        xml.flush();
    } catch (XMLStreamException xse) {
        throw new IOException(xse);
    }
}

From source file:org.andromda.cartridges.gui.metafacades.GuiUseCaseLogicImpl.java

@Override
protected Collection handleGetIncludedUseCases() {

    final TreeNode root = this.getApplicationHierarchyRoot();
    final List nodeList = Collections.list(((UseCaseNode) root).breadthFirstEnumeration());
    final List<GuiUseCase> useCasesList = new ArrayList<GuiUseCase>();

    for (final Iterator it = nodeList.iterator(); it.hasNext();) {

        useCasesList.add(((UseCaseNode) it.next()).getUseCase());

    }/* ww  w  .j a v  a2s.  c om*/

    return useCasesList;

}

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

private void validateCertificateKeyInKeyStore(KeyStore keyStore, X509Certificate x509Certificate,
        String secretPassword) throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException,
        InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    String defaultAlias = Collections.list(keyStore.aliases()).get(0);
    X509Certificate secretCertificate = (X509Certificate) keyStore.getCertificate(defaultAlias);
    Assert.assertNotNull(secretCertificate);
    Assert.assertTrue(secretCertificate.getSubjectX500Principal().getName()
            .equals(x509Certificate.getSubjectX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getIssuerX500Principal().getName()
            .equals(x509Certificate.getIssuerX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getSerialNumber().equals(x509Certificate.getSerialNumber()));

    // Validate the key in the KeyStore
    Key secretKey = keyStore.getKey(defaultAlias, secretPassword.toCharArray());
    Assert.assertNotNull(secretKey);//from  ww  w. j a v  a  2s .c  o  m
    Assert.assertTrue(secretKey instanceof PrivateKey);
    PrivateKey secretPrivateKey = (PrivateKey) secretKey;

    // Create a KeyPair with the private key from the KeyStore and public
    // key from the certificate to verify they match
    KeyPair keyPair = new KeyPair(secretCertificate.getPublicKey(), secretPrivateKey);
    Assert.assertNotNull(keyPair);
    verifyRSAKeyPair(keyPair);
}

From source file:edu.ku.brc.af.ui.forms.TableViewObj.java

@SuppressWarnings("unchecked")
public void setDataObj(final Object dataObj) {
    this.dataObj = dataObj;

    if (dataObj instanceof List) {
        origDataSet = null;/*  ww  w  . jav a 2s.c om*/
        if (dataObj instanceof Vector) {
            dataObjList = (Vector<Object>) (List<Object>) dataObj;
        } else {
            dataObjList = new Vector<Object>((List<Object>) dataObj);
        }

        newObjsList.addAll(dataObjList);

    } else {
        if (dataObjList == null) {
            dataObjList = new Vector<Object>();
        } else {
            dataObjList.clear();
        }

        if (dataObj instanceof Set) {
            origDataSet = (Set<Object>) dataObj;
            List newList = Collections.list(Collections.enumeration(origDataSet));
            if (newList.size() > 0) {
                Object firstObj = newList.get(0);
                if (firstObj instanceof Comparable<?>) {
                    Collections.sort(newList);
                }

                if (firstObj instanceof Orderable && isEditing && orderUpBtn == null) {
                    addOrderablePanel();
                }
            }
            dataObjList.addAll(newList);
            newObjsList.addAll(newList);

        } else if (dataObj instanceof RecordSetIFace) {
            //this.dataObj = dataObj;
            /*
            RecordSetIFace recordSet = (RecordSetIFace)dataObj;
                    
            DBTableIdMgr.getInstance().getInClause(recordSet);
            DBTableInfo tableInfo = DBTableIdMgr.getInstance().lookupInfoById(recordSet.getDbTableId());
                    
            DataProviderFactory.getInstance().evict(tableInfo.getClassObj());
                    
            //DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession();
                    
            String sqlStr = DBTableIdMgr.getInstance().getQueryForTable(recordSet);
            if (StringUtils.isNotBlank(sqlStr))
            {
            dataObjList =(List<Object>)session.getDataList(sqlStr);
            }
            */
        } else if (dataObj != null) {
            // single object
            dataObjList.add(dataObj);
            newObjsList.add(dataObj);
        }
    }

    setDataIntoUI();

    if (table != null) {
        table.tableChanged(new TableModelEvent(model));
    }
}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private static void handlePutBlob(HttpServletRequest request, HttpServletResponse response, InputStream is,
        BlobStore blobStore, String containerName, String blobName) throws IOException, S3Exception {
    // Flag headers present since HttpServletResponse.getHeader returns
    // null for empty headers values.
    String contentLengthString = null;
    String decodedContentLengthString = null;
    String contentMD5String = null;
    for (String headerName : Collections.list(request.getHeaderNames())) {
        String headerValue = Strings.nullToEmpty(request.getHeader(headerName));
        if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) {
            contentLengthString = headerValue;
        } else if (headerName.equalsIgnoreCase("x-amz-decoded-content-length")) {
            decodedContentLengthString = headerValue;
        } else if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_MD5)) {
            contentMD5String = headerValue;
        }//w  ww  . j a  v a2 s. c om
    }
    if (decodedContentLengthString != null) {
        contentLengthString = decodedContentLengthString;
    }

    HashCode contentMD5 = null;
    if (contentMD5String != null) {
        try {
            contentMD5 = HashCode.fromBytes(BaseEncoding.base64().decode(contentMD5String));
        } catch (IllegalArgumentException iae) {
            throw new S3Exception(S3ErrorCode.INVALID_DIGEST, iae);
        }
        if (contentMD5.bits() != Hashing.md5().bits()) {
            throw new S3Exception(S3ErrorCode.INVALID_DIGEST);
        }
    }

    if (contentLengthString == null) {
        throw new S3Exception(S3ErrorCode.MISSING_CONTENT_LENGTH);
    }
    long contentLength;
    try {
        contentLength = Long.parseLong(contentLengthString);
    } catch (NumberFormatException nfe) {
        throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT, nfe);
    }
    if (contentLength < 0) {
        throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT);
    }

    BlobAccess access;
    String cannedAcl = request.getHeader("x-amz-acl");
    if (cannedAcl == null || cannedAcl.equalsIgnoreCase("private")) {
        access = BlobAccess.PRIVATE;
    } else if (cannedAcl.equalsIgnoreCase("public-read")) {
        access = BlobAccess.PUBLIC_READ;
    } else if (CANNED_ACLS.contains(cannedAcl)) {
        throw new S3Exception(S3ErrorCode.NOT_IMPLEMENTED);
    } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    PutOptions options = new PutOptions().setBlobAccess(access);

    String blobStoreType = getBlobStoreType(blobStore);
    if (blobStoreType.equals("azureblob") && contentLength > 64 * 1024 * 1024) {
        options.multipart(true);
    }

    String eTag;
    try {
        BlobBuilder.PayloadBlobBuilder builder = blobStore.blobBuilder(blobName).payload(is)
                .contentLength(contentLength);

        addContentMetdataFromHttpRequest(builder, request);
        if (contentMD5 != null) {
            builder = builder.contentMD5(contentMD5);
        }

        eTag = blobStore.putBlob(containerName, builder.build(), options);
    } catch (HttpResponseException hre) {
        HttpResponse hr = hre.getResponse();
        if (hr == null) {
            return;
        }
        int status = hr.getStatusCode();
        switch (status) {
        case HttpServletResponse.SC_BAD_REQUEST:
        case 422: // Swift returns 422 Unprocessable Entity
            throw new S3Exception(S3ErrorCode.BAD_DIGEST);
        default:
            // TODO: emit hre.getContent() ?
            response.sendError(status);
            break;
        }
        return;
    }

    response.addHeader(HttpHeaders.ETAG, maybeQuoteETag(eTag));
}

From source file:com.mirth.connect.client.ui.codetemplate.CodeTemplatePanel.java

private void deleteSelectedNode(boolean codeTemplate) {
    stopTableEditing();//w w w.  j a  va2 s . c o  m
    setSaveEnabled(true);
    TreePath selectedPath = templateTreeTable.getTreeSelectionModel().getSelectionPath();

    if (selectedPath != null) {
        CodeTemplateTreeTableModel model = (CodeTemplateTreeTableModel) templateTreeTable.getTreeTableModel();
        MutableTreeTableNode selectedNode = (MutableTreeTableNode) selectedPath.getLastPathComponent();
        MutableTreeTableNode parent = (MutableTreeTableNode) selectedNode.getParent();
        int selectedNodeIndex = parent.getIndex(selectedNode);
        MutableTreeTableNode newSelectedNode = null;

        if (!codeTemplate && selectedNode.getChildCount() > 0) {
            if (!this.parent.alertOkCancel(this.parent, "The selected library contains "
                    + selectedNode.getChildCount()
                    + " code templates. If you delete the library, the code templates will be deleted as well. Are you sure you wish to continue?")) {
                return;
            }

            for (MutableTreeTableNode codeTemplateNode : Collections.list(selectedNode.children())) {
                model.removeNodeFromParent(codeTemplateNode);

                if (model.getRoot() != fullModel.getRoot()) {
                    AbstractSortableTreeTableNode fullCodeTemplateNode = findFullNode(
                            (AbstractSortableTreeTableNode) codeTemplateNode);
                    fullModel.removeNodeFromParent(fullCodeTemplateNode);
                }
            }
        }

        updateCurrentNode.set(false);
        selectedNode = (MutableTreeTableNode) selectedPath.getLastPathComponent();
        model.removeNodeFromParent(selectedNode);

        if (model.getRoot() != fullModel.getRoot()) {
            fullModel.removeNodeFromParent(findFullNode((AbstractSortableTreeTableNode) selectedNode));
        }

        if (selectedNodeIndex < parent.getChildCount()) {
            newSelectedNode = (MutableTreeTableNode) parent.getChildAt(selectedNodeIndex);
        } else if (parent.getChildCount() > 0) {
            newSelectedNode = (MutableTreeTableNode) parent.getChildAt(parent.getChildCount() - 1);
        } else if (codeTemplate) {
            newSelectedNode = parent;
        }

        if (newSelectedNode != null) {
            final TreePath newSelectedPath = new TreePath(
                    ((CodeTemplateTreeTableModel) templateTreeTable.getTreeTableModel())
                            .getPathToRoot(newSelectedNode));
            selectTemplatePath(newSelectedPath);

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    selectTemplatePath(newSelectedPath);
                    updateCurrentNode.set(true);
                }
            });
        } else {
            switchSplitPaneComponent(blankPanel);
            updateCurrentNode.set(true);
        }

        updateFilterNotification();
    }
}

From source file:org.jvnet.hudson.test.JenkinsRule.java

/**
 * If this test harness is launched for a Jenkins plugin, locate the <tt>target/test-classes/the.jpl</tt>
 * and add a recipe to install that to the new Jenkins.
 *
 * <p>//  ww w. j  a va2  s .c  o  m
 * This file is created by <tt>maven-hpi-plugin</tt> at the testCompile phase when the current
 * packaging is <tt>jpi</tt>.
 */
public void recipeLoadCurrentPlugin() throws Exception {
    final Enumeration<URL> jpls = getClass().getClassLoader().getResources("the.jpl");
    final Enumeration<URL> hpls = getClass().getClassLoader().getResources("the.hpl");

    final List<URL> all = Collections.list(jpls);
    all.addAll(Collections.list(hpls));

    if (all.isEmpty())
        return; // nope

    recipes.add(new JenkinsRecipe.Runner() {
        private File home;
        private final List<Jpl> jpls = new ArrayList<Jpl>();

        @Override
        public void decorateHome(JenkinsRule testCase, File home) throws Exception {
            this.home = home;
            this.jpls.clear();

            for (URL hpl : all) {
                Jpl jpl = new Jpl(hpl);
                jpl.loadManifest();
                jpls.add(jpl);
            }

            for (Jpl jpl : jpls) {
                jpl.resolveDependencies();
            }
        }

        class Jpl {
            final URL jpl;
            Manifest m;
            private String shortName;

            Jpl(URL jpl) {
                this.jpl = jpl;
            }

            void loadManifest() throws IOException {
                m = new Manifest(jpl.openStream());
                shortName = m.getMainAttributes().getValue("Short-Name");
                if (shortName == null)
                    throw new Error(jpl + " doesn't have the Short-Name attribute");
                FileUtils.copyURLToFile(jpl, new File(home, "plugins/" + shortName + ".jpl"));
            }

            void resolveDependencies() throws Exception {
                // make dependency plugins available
                // TODO: probably better to read POM, but where to read from?
                // TODO: this doesn't handle transitive dependencies

                // Tom: plugins are now searched on the classpath first. They should be available on
                // the compile or test classpath. As a backup, we do a best-effort lookup in the Maven repository
                // For transitive dependencies, we could evaluate Plugin-Dependencies transitively.
                String dependencies = m.getMainAttributes().getValue("Plugin-Dependencies");
                if (dependencies != null) {
                    DEPENDENCY: for (String dep : dependencies.split(",")) {
                        String suffix = ";resolution:=optional";
                        boolean optional = dep.endsWith(suffix);
                        if (optional) {
                            dep = dep.substring(0, dep.length() - suffix.length());
                        }
                        String[] tokens = dep.split(":");
                        String artifactId = tokens[0];
                        String version = tokens[1];

                        for (Jpl other : jpls) {
                            if (other.shortName.equals(artifactId))
                                continue DEPENDENCY; // resolved from another JPL file
                        }

                        File dependencyJar = resolveDependencyJar(artifactId, version);
                        if (dependencyJar == null) {
                            if (optional) {
                                System.err.println("cannot resolve optional dependency " + dep + " of "
                                        + shortName + "; skipping");
                                continue;
                            }
                            throw new IOException("Could not resolve " + dep + " in "
                                    + System.getProperty("java.class.path"));
                        }

                        File dst = new File(home, "plugins/" + artifactId + ".jpi");
                        if (!dst.exists() || dst.lastModified() != dependencyJar.lastModified()) {
                            try {
                                FileUtils.copyFile(dependencyJar, dst);
                            } catch (ClosedByInterruptException x) {
                                throw new AssumptionViolatedException("copying dependencies was interrupted",
                                        x);
                            }
                        }
                    }
                }
            }
        }

        /**
         * Lazily created embedder.
         */
        private MavenEmbedder embedder;

        private MavenEmbedder getMavenEmbedder() throws MavenEmbedderException, IOException {
            if (embedder == null)
                embedder = MavenUtil.createEmbedder(
                        new StreamTaskListener(System.out, Charset.defaultCharset()), (File) null, null);
            return embedder;
        }

        private @CheckForNull File resolveDependencyJar(String artifactId, String version) throws Exception {
            // try to locate it from manifest
            Enumeration<URL> manifests = getClass().getClassLoader().getResources("META-INF/MANIFEST.MF");
            while (manifests.hasMoreElements()) {
                URL manifest = manifests.nextElement();
                InputStream is = manifest.openStream();
                Manifest m = new Manifest(is);
                is.close();

                if (artifactId.equals(m.getMainAttributes().getValue("Short-Name")))
                    return Which.jarFile(manifest);
            }

            // For snapshot plugin dependencies, an IDE may have replaced ~/.m2/repository//${artifactId}.hpi with /${artifactId}-plugin/target/classes/
            // which unfortunately lacks META-INF/MANIFEST.MF so try to find index.jelly (which every plugin should include) and thus the ${artifactId}.hpi:
            Enumeration<URL> jellies = getClass().getClassLoader().getResources("index.jelly");
            while (jellies.hasMoreElements()) {
                URL jellyU = jellies.nextElement();
                if (jellyU.getProtocol().equals("file")) {
                    File jellyF = new File(jellyU.toURI());
                    File classes = jellyF.getParentFile();
                    if (classes.getName().equals("classes")) {
                        File target = classes.getParentFile();
                        if (target.getName().equals("target")) {
                            File hpi = new File(target, artifactId + ".hpi");
                            if (hpi.isFile()) {
                                return hpi;
                            }
                        }
                    }
                }
            }

            // need to search multiple group IDs
            // TODO: extend manifest to include groupID:artifactID:version
            Exception resolutionError = null;
            for (String groupId : PLUGIN_GROUPIDS) {

                // first try to find it on the classpath.
                // this takes advantage of Maven POM located in POM
                URL dependencyPomResource = getClass()
                        .getResource("/META-INF/maven/" + groupId + "/" + artifactId + "/pom.xml");
                if (dependencyPomResource != null) {
                    // found it
                    return Which.jarFile(dependencyPomResource);
                } else {

                    try {
                        // currently the most of the plugins are still hpi
                        return resolvePluginFile(artifactId, version, groupId, "hpi");
                    } catch (AbstractArtifactResolutionException x) {
                        try {
                            // but also try with the new jpi
                            return resolvePluginFile(artifactId, version, groupId, "jpi");
                        } catch (AbstractArtifactResolutionException x2) {
                            // could be a wrong groupId
                            resolutionError = x;
                        }
                    }

                }
            }

            throw new Exception("Failed to resolve plugin: " + artifactId + " version " + version,
                    resolutionError);
        }

        private @CheckForNull File resolvePluginFile(String artifactId, String version, String groupId,
                String type) throws Exception {
            final Artifact jpi = getMavenEmbedder().createArtifact(groupId, artifactId, version,
                    "compile"/*doesn't matter*/, type);
            getMavenEmbedder().resolve(jpi,
                    Arrays.asList(getMavenEmbedder()
                            .createRepository("http://maven.glassfish.org/content/groups/public/", "repo")),
                    embedder.getLocalRepository());
            return jpi.getFile();

        }
    });
}