Example usage for javax.enterprise.deploy.spi.status ProgressObject getResultTargetModuleIDs

List of usage examples for javax.enterprise.deploy.spi.status ProgressObject getResultTargetModuleIDs

Introduction

In this page you can find the example usage for javax.enterprise.deploy.spi.status ProgressObject getResultTargetModuleIDs.

Prototype

public TargetModuleID[] getResultTargetModuleIDs();

Source Link

Document

Retrieve the list of TargetModuleIDs successfully processed or created by the associated DeploymentManager operation.

Usage

From source file:org.apache.geronimo.console.configmanager.DeploymentPortlet.java

public void processAction(ActionRequest actionRequest, ActionResponse actionResponse)
        throws PortletException, IOException {
    if (!PortletFileUpload.isMultipartContent(actionRequest)) {
        throw new PortletException("Expected file upload");
    }//from  ww w.  j  ava2s .c om

    File rootDir = new File(System.getProperty("java.io.tmpdir"));
    PortletFileUpload uploader = new PortletFileUpload(new DiskFileItemFactory(10240, rootDir));
    File moduleFile = null;
    File planFile = null;
    String startApp = null;
    String redeploy = null;
    try {
        List items = uploader.parseRequest(actionRequest);
        for (Iterator i = items.iterator(); i.hasNext();) {
            FileItem item = (FileItem) i.next();
            if (!item.isFormField()) {
                String fieldName = item.getFieldName();
                String name = item.getName().trim();
                File file;
                if (name.length() == 0) {
                    file = null;
                } else {
                    // Firefox sends basename, IE sends full path
                    int index = name.lastIndexOf('\\');
                    if (index != -1) {
                        name = name.substring(index + 1);
                    }
                    file = new File(rootDir, name);
                }
                if ("module".equals(fieldName)) {
                    moduleFile = file;
                } else if ("plan".equals(fieldName)) {
                    planFile = file;
                }
                if (file != null) {
                    try {
                        item.write(file);
                    } catch (Exception e) {
                        throw new PortletException(e);
                    }
                }
            } else {
                // retrieve 'startApp' form field value
                if ("startApp".equalsIgnoreCase(item.getFieldName())) {
                    startApp = item.getString();
                } else if ("redeploy".equalsIgnoreCase(item.getFieldName())) {
                    redeploy = item.getString();
                }
            }
        }
    } catch (FileUploadException e) {
        throw new PortletException(e);
    }
    DeploymentFactoryManager dfm = DeploymentFactoryManager.getInstance();
    FileInputStream fis = null;
    try {
        DeploymentManager mgr = dfm.getDeploymentManager("deployer:geronimo:inVM", null, null);
        try {
            boolean isRedeploy = redeploy != null && !redeploy.equals("");
            if (mgr instanceof JMXDeploymentManager) {
                ((JMXDeploymentManager) mgr).setLogConfiguration(false, true);
            }
            Target[] all = mgr.getTargets();
            if (null == all) {
                throw new IllegalStateException("No target to distribute to");
            }

            ProgressObject progress;
            if (isRedeploy) {
                TargetModuleID[] targets = identifyTargets(moduleFile, planFile,
                        mgr.getAvailableModules(null, all));
                if (targets.length == 0) {
                    addErrorMessage(actionRequest, getLocalizedString(actionRequest, "plugin.errorMsg04"),
                            null);
                    log.error(getLocalizedString(actionRequest, "plugin.errorMsg04"));
                    return;
                }
                progress = mgr.redeploy(targets, moduleFile, planFile);
            } else {
                progress = mgr.distribute(new Target[] { all[0] }, moduleFile, planFile);
            }
            while (progress.getDeploymentStatus().isRunning()) {
                Thread.sleep(100);
            }

            String abbrStatusMessage;
            String fullStatusMessage = null;
            if (progress.getDeploymentStatus().isCompleted()) {
                abbrStatusMessage = getLocalizedString(actionRequest,
                        !isRedeploy ? "plugin.infoMsg01" : "plugin.infoMsg02");
                addInfoMessage(actionRequest, abbrStatusMessage);
                // start installed app/s
                if (!isRedeploy && startApp != null && !startApp.equals("")) {
                    progress = mgr.start(progress.getResultTargetModuleIDs());
                    while (progress.getDeploymentStatus().isRunning()) {
                        Thread.sleep(100);
                    }
                    if (progress.getDeploymentStatus().isCompleted()) {
                        abbrStatusMessage = getLocalizedString(actionRequest, "plugin.infoMsg03");
                        addInfoMessage(actionRequest, abbrStatusMessage);
                    } else {
                        abbrStatusMessage = getLocalizedString(actionRequest, "plugin.errorMsg02");
                        fullStatusMessage = progress.getDeploymentStatus().getMessage();
                        addErrorMessage(actionRequest, abbrStatusMessage, fullStatusMessage);
                        log.error(abbrStatusMessage + "\n" + fullStatusMessage);
                    }
                }
            } else {
                fullStatusMessage = progress.getDeploymentStatus().getMessage();
                // for the abbreviated status message clip off everything
                // after the first line, which in most cases means the gnarly stacktrace
                abbrStatusMessage = getLocalizedString(actionRequest, "plugin.errorMsg01");
                addErrorMessage(actionRequest, abbrStatusMessage, fullStatusMessage);
                log.error(abbrStatusMessage + "\n" + fullStatusMessage);
            }
        } finally {
            mgr.release();
            if (fis != null)
                fis.close();
            if (moduleFile != null && moduleFile.exists()) {
                if (!moduleFile.delete()) {
                    log.debug("Unable to delete temporary file " + moduleFile);
                    moduleFile.deleteOnExit();
                }
            }
            if (planFile != null && planFile.exists()) {
                if (!planFile.delete()) {
                    log.debug("Unable to delete temporary file " + planFile);
                    planFile.deleteOnExit();
                }
            }
        }
    } catch (Exception e) {
        throw new PortletException(e);
    }
}

From source file:org.apache.geronimo.console.databasemanager.wizard.DatabasePoolPortlet.java

private static String save(PortletRequest request, ActionResponse response, PoolData data, boolean planOnly) {
    ImportStatus status = getImportStatus(request);
    if (data.abstractName == null || data.abstractName.equals("")) { // we're creating a new pool
        data.name = data.name.replaceAll("\\s", "");
        DeploymentManager mgr = ManagementHelper.getManagementHelper(request).getDeploymentManager();
        try {//w w w  .  java2  s .  c  o  m
            String rarPath = data.getRarPath();
            File rarFile = getRAR(request, rarPath);
            //URI uri = getRAR(request, data.getRarPath()).toURI();
            ConnectorDeployable deployable = new ConnectorDeployable(
                    PortletManager.getRepositoryEntryBundle(request, rarPath));
            DeploymentConfiguration config = mgr.createConfiguration(deployable);
            final DDBeanRoot ddBeanRoot = deployable.getDDBeanRoot();
            Connector15DCBRoot root = (Connector15DCBRoot) config.getDConfigBeanRoot(ddBeanRoot);
            ConnectorDCB connector = (ConnectorDCB) root
                    .getDConfigBean(ddBeanRoot.getChildBean(root.getXpaths()[0])[0]);

            EnvironmentData environment = new EnvironmentData();
            connector.setEnvironment(environment);
            org.apache.geronimo.deployment.service.jsr88.Artifact configId = new org.apache.geronimo.deployment.service.jsr88.Artifact();
            environment.setConfigId(configId);
            configId.setGroupId("console.dbpool");
            configId.setVersion("1.0");
            configId.setType("car");

            String artifactId = data.name;
            // simply replace / with _ if / exists within the artifactId
            // this is needed because we don't allow / within the artifactId
            artifactId = artifactId.replace('/', '_');

            // Let's check whether the artifact exists
            ConfigurationManager configurationManager = ConfigurationUtil
                    .getConfigurationManager(PortletManager.getKernel());
            if (configurationManager.isInstalled(new Artifact(configId.getGroupId(), artifactId,
                    configId.getVersion(), configId.getType()))) {
                artifactId = artifactId + "_" + new Random(System.currentTimeMillis()).nextInt(99);
            }

            configId.setArtifactId(artifactId);

            String[] jars = data.getJars();
            int length = jars[jars.length - 1].length() == 0 ? jars.length - 1 : jars.length;
            org.apache.geronimo.deployment.service.jsr88.Artifact[] dependencies = new org.apache.geronimo.deployment.service.jsr88.Artifact[length];
            for (int i = 0; i < dependencies.length; i++) {
                dependencies[i] = new org.apache.geronimo.deployment.service.jsr88.Artifact();
            }
            environment.setDependencies(dependencies);
            for (int i = 0; i < dependencies.length; i++) {
                Artifact tmp = Artifact.create(jars[i]);
                dependencies[i].setGroupId(tmp.getGroupId());
                dependencies[i].setArtifactId(tmp.getArtifactId());
                dependencies[i].setVersion(tmp.getVersion().toString());
                dependencies[i].setType(tmp.getType());
            }

            ResourceAdapter adapter = connector.getResourceAdapter()[0];
            ConnectionDefinition definition = new ConnectionDefinition();
            adapter.setConnectionDefinition(new ConnectionDefinition[] { definition });
            definition.setConnectionFactoryInterface("javax.sql.DataSource");
            ConnectionDefinitionInstance instance = new ConnectionDefinitionInstance();
            definition.setConnectionInstance(new ConnectionDefinitionInstance[] { instance });
            instance.setName(data.getName());
            ConfigPropertySetting[] settings = instance.getConfigPropertySetting();
            if (data.isGeneric()) { // it's a generic TranQL JDBC pool
                for (ConfigPropertySetting setting : settings) {
                    if (setting.getName().equals("UserName")) {
                        setting.setValue(data.user);
                    } else if (setting.getName().equals("Password")) {
                        setting.setValue(data.password);
                    } else if (setting.getName().equals("ConnectionURL")) {
                        setting.setValue(data.url);
                    } else if (setting.getName().equals("Driver")) {
                        setting.setValue(data.driverClass);
                    }
                }
            } else { // it's an XA driver or non-TranQL RA
                for (ConfigPropertySetting setting : settings) {
                    String value = data.properties.get("property-" + setting.getName());
                    setting.setValue(value == null ? "" : value);
                }
            }
            ConnectionManager manager = instance.getConnectionManager();
            if (XA.equals(data.transactionType)) {
                manager.setTransactionXA(true);
            } else if (NONE.equals(data.transactionType)) {
                manager.setTransactionNone(true);
            } else {
                manager.setTransactionLocal(true);
            }

            SinglePool pool = new SinglePool();
            manager.setPoolSingle(pool);
            pool.setMatchOne(true);
            // Max Size needs to be set before the minimum.  This is because
            // the connection manager will constrain the minimum based on the
            // current maximum value in the pool.  We might consider adding a
            // setPoolConstraints method to allow specifying both at the same time.
            if (data.maxSize != null && !data.maxSize.equals("")) {
                pool.setMaxSize(new Integer(data.maxSize));
            }
            if (data.minSize != null && !data.minSize.equals("")) {
                pool.setMinSize(new Integer(data.minSize));
            }
            if (data.blockingTimeout != null && !data.blockingTimeout.equals("")) {
                pool.setBlockingTimeoutMillis(new Integer(data.blockingTimeout));
            }
            if (data.idleTimeout != null && !data.idleTimeout.equals("")) {
                pool.setIdleTimeoutMinutes(new Integer(data.idleTimeout));
            }

            if (planOnly) {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                config.save(out);
                out.close();
                return new String(out.toByteArray(), "US-ASCII");
            } else {
                File tempFile = File.createTempFile("console-deployment", ".xml");
                tempFile.deleteOnExit();
                log.debug("Writing database pool deployment plan to " + tempFile.getAbsolutePath());
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile));
                config.save(out);
                out.flush();
                out.close();
                Target[] targets = mgr.getTargets();
                if (null == targets) {
                    throw new IllegalStateException("No target to distribute to");
                }
                targets = new Target[] { targets[0] };

                ProgressObject po = mgr.distribute(targets, rarFile, tempFile);
                waitForProgress(po);
                if (po.getDeploymentStatus().isCompleted()) {
                    TargetModuleID[] ids = po.getResultTargetModuleIDs();
                    po = mgr.start(ids);
                    waitForProgress(po);
                    if (po.getDeploymentStatus().isCompleted()) {
                        ids = po.getResultTargetModuleIDs();
                        if (status != null) {
                            status.getCurrentPool().setName(data.getName());
                            status.getCurrentPool().setConfigurationName(ids[0].getModuleID());
                            status.getCurrentPool().setFinished(true);
                            response.setRenderParameter(MODE_KEY, IMPORT_STATUS_MODE);
                        }

                        log.info("Deployment completed successfully!");
                    }
                } else if (po.getDeploymentStatus().isFailed()) {
                    data.deployError = "Unable to deploy: " + data.name;
                    response.setRenderParameter(MODE_KEY, EDIT_MODE);
                    log.info("Deployment Failed!");
                }
            }
        } catch (Exception e) {
            log.error("Unable to save connection pool", e);
        } finally {
            if (mgr != null)
                mgr.release();
        }
    } else { // We're saving updates to an existing pool
        if (planOnly) {
            throw new UnsupportedOperationException("Can't update a plan for an existing deployment");
        }
        try {
            JCAManagedConnectionFactory factory = (JCAManagedConnectionFactory) PortletManager
                    .getManagedBean(request, new AbstractName(URI.create(data.getAbstractName())));
            if (data.isGeneric()) {
                factory.setConfigProperty("ConnectionURL", data.getUrl());
                factory.setConfigProperty("UserName", data.getUser());
                factory.setConfigProperty("Password", data.getPassword());
            } else {
                for (Map.Entry<String, String> entry : data.getProperties().entrySet()) {
                    factory.setConfigProperty(entry.getKey().substring("property-".length()), entry.getValue());
                }
            }
            /*Make pool setting effective after server restart*/
            Jsr77Naming naming = new Jsr77Naming();
            AbstractName connectionManagerName = naming.createChildName(
                    new AbstractName(URI.create(data.getAbstractName())), data.getName(),
                    NameFactory.JCA_CONNECTION_MANAGER);
            PoolingAttributes pool = (PoolingAttributes) PortletManager.getManagedBean(request,
                    connectionManagerName);

            pool.setPartitionMinSize(
                    data.minSize == null || data.minSize.equals("") ? 0 : Integer.parseInt(data.minSize));
            pool.setPartitionMaxSize(
                    data.maxSize == null || data.maxSize.equals("") ? 10 : Integer.parseInt(data.maxSize));
            pool.setBlockingTimeoutMilliseconds(
                    data.blockingTimeout == null || data.blockingTimeout.equals("") ? 5000
                            : Integer.parseInt(data.blockingTimeout));
            pool.setIdleTimeoutMinutes(data.idleTimeout == null || data.idleTimeout.equals("") ? 15
                    : Integer.parseInt(data.idleTimeout));

        } catch (Exception e) {
            log.error("Unable to save connection pool", e);
        }
    }
    return null;
}