TODO thread-safety issues: if multiple concurrent calls, may break (e.g. deployment_wars being reset)
511469
public void deployInitialApplications() {
        initDeployAppAttributeIfIsNull();

        String gitRepoUrl = getConfig(GIT_URL);
        String tarballResourceUrl = getConfig(TARBALL_URL);
        
        if (gitRepoUrl != null) {
            String targetName = inferCorrectAppGitName();
            deployGitResource(gitRepoUrl, targetName);
        } else if (tarballResourceUrl != null) {
            String targetName = inferCorrectAppTarballName();
            deployTarballResource(tarballResourceUrl, targetName);
        }
        
    }
1333720
private void failOnOverlapOfClearedPropagatedUnchanged(Set<String> cleared, Set<String> propagated, Set<String> unchanged) {
        HashSet<String> overlap = new HashSet<String>(cleared);
        overlap.retainAll(propagated);
        HashSet<String> s = new HashSet<String>(cleared);
        s.retainAll(unchanged);
        overlap.addAll(s);
        s = new HashSet<String>(propagated);
        s.retainAll(unchanged);
        overlap.addAll(s);
        if (overlap.isEmpty()) // only possible if builder is concurrently modified during build
            throw new ConcurrentModificationException();
        throw new IllegalStateException(Tr.formatMessage(tc, "CWWKC1152.context.lists.overlap", overlap));
    }
382006
@Override
  public void updateDeployment(final String host, final Deployment deployment, final String token)
      throws HostNotFoundException, JobNotDeployedException, TokenVerificationException {
    log.info("updating deployment {}: {}", deployment, host);

    final ZooKeeperClient client = provider.get("updateDeployment");

    final JobId jobId = deployment.getJobId();
    final Job job = getJob(client, jobId);
    final Deployment existingDeployment = getDeployment(host, jobId);

    if (job == null) {
      throw new JobNotDeployedException(host, jobId);
    }
    verifyToken(token, job);

    assertHostExists(client, host);
    assertTaskExists(client, host, deployment.getJobId());

    final String path = Paths.configHostJob(host, jobId);
    final Task task = new Task(job, deployment.getGoal(),
        existingDeployment.getDeployerUser(),
        existingDeployment.getDeployerMaster(),
        existingDeployment.getDeploymentGroupName());
    try {
      client.setData(path, task.toJsonBytes());
    } catch (Exception e) {
      throw new HeliosRuntimeException("updating deployment " + deployment
                                       + " on host " + host + " failed", e);
    }
  }
910512
private void initDispatcherThreads(Feature.AsynchronousMessageDispatch configuration) {
        for (int i = 0; i < configuration.getNumberOfMessageDispatchers(); i++) {
            // each thread will run forever and process incoming
            // message publication requests
            Thread dispatcher = configuration.getDispatcherThreadFactory().newThread(new Runnable() {
                public void run() {
                    while (true) {
                        IMessagePublication publication = null;
                        try {
                            publication = pendingMessages.take();
                            publication.execute();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            return;
                        } catch(Throwable t){
                            handlePublicationError(new InternalPublicationError(t, "Error in asynchronous dispatch",publication));
                        }
                    }
                }
            });
            dispatcher.setName("MsgDispatcher-"+i);
            dispatchers.add(dispatcher);
            dispatcher.start();
        }
    }
1145763
def stop_deployment(awsclient, deployment_id):
    
    log.info('Deployment: %s - stopping active deployment.', deployment_id)
    client_codedeploy = awsclient.get_client('codedeploy')

    response = client_codedeploy.stop_deployment(
        deploymentId=deployment_id,
        autoRollbackEnabled=True
    )
97390
public void handleUpdateDeployment(String jsonp,
            HttpServletRequest request,
            HttpServletResponse response, AuthenticationResult ar)
            throws IOException, ServletException {
        String deployment = request.getParameter("deployment");
        if (deployment == null || deployment.length() == 0) {
            response.getWriter().print(buildClientResponse(jsonp, ClientResponse.UNEXPECTED_FAILURE, "Failed to get deployment information."));
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        try {
            DeploymentType newDeployment = m_mapper.readValue(deployment, DeploymentType.class);
            if (newDeployment == null) {
                response.getWriter().print(buildClientResponse(jsonp, ClientResponse.UNEXPECTED_FAILURE, "Failed to parse deployment information."));
                return;
            }

            DeploymentType currentDeployment = this.getDeployment();
            if (currentDeployment.getUsers() != null) {
                newDeployment.setUsers(currentDeployment.getUsers());
            }
            // reset the host count so that it wont fail the deployment checks
            newDeployment.getCluster().setHostcount(currentDeployment.getCluster().getHostcount());

            String dep = CatalogUtil.getDeployment(newDeployment);
            if (dep == null || dep.trim().length() <= 0) {
                response.getWriter().print(buildClientResponse(jsonp, ClientResponse.UNEXPECTED_FAILURE, "Failed to build deployment information."));
                return;
            }
            Object[] params = new Object[]{null, dep};
            SyncCallback cb = new SyncCallback();
            httpClientInterface.callProcedure(request.getRemoteHost(), ar, BatchTimeoutOverrideType.NO_TIMEOUT, cb, "@UpdateApplicationCatalog", params);
            cb.waitForResponse();
            ClientResponseImpl r = ClientResponseImpl.class.cast(cb.getResponse());
            if (r.getStatus() == ClientResponse.SUCCESS) {
                response.getWriter().print(buildClientResponse(jsonp, ClientResponse.SUCCESS, "Deployment Updated."));
            } else {
                response.getWriter().print(HTTPClientInterface.asJsonp(jsonp, r.toJSONString()));
            }
        } catch (JsonParseException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().print(buildClientResponse(jsonp, ClientResponse.UNEXPECTED_FAILURE, "Unparsable JSON"));
        } catch (Exception ex) {
            m_log.error("Failed to update deployment from API", ex);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().print(buildClientResponse(jsonp, ClientResponse.UNEXPECTED_FAILURE, Throwables.getStackTraceAsString(ex)));
        }
    }
977431
private synchronized <R> OperationResult<R> executeDdlOperation(AbstractOperationImpl<R> operation, RetryPolicy retry)
             throws OperationException, ConnectionException {
         ConnectionException lastException = null;
         for (int i = 0; i < 2; i++) {
             operation.setPinnedHost(ddlHost);
             try {
                 OperationResult<R> result = connectionPool.executeWithFailover(operation, retry);
                 ddlHost = result.getHost();
                 return result;
             }
             catch (ConnectionException e) {
                lastException = e;
                if (e instanceof IsDeadConnectionException) {
                     ddlHost = null;
                }
             }
         }
         throw lastException;
    }
758810
private synchronized void doNodeLeft(final String nodeID) {
    log.info(String.format("%s - %s left the cluster", this, nodeID));
    context.run(new Runnable() {
      @Override
      public void run() {
        // Redeploy any failed deployments.
        synchronized (deployments) {
          Collection<String> sdeploymentsInfo = deployments.get(group);
          for (final String sdeploymentInfo : sdeploymentsInfo) {
            final JsonObject deploymentInfo = new JsonObject(sdeploymentInfo);
            // If the deployment node is equal to the node that left the cluster then
            // remove the deployment from the deployments list and attempt to redeploy it.
            if (deploymentInfo.getString("node").equals(nodeID)) {
              // If the deployment is an HA deployment then attempt to redeploy it on this node.
              if (deployments.remove(group, sdeploymentInfo) && deploymentInfo.getBoolean("ha", false)) {
                doRedeploy(deploymentInfo);
              }
            }
          }
        }
      }
    });
  }
1116150
@Override
    protected void doExecute() throws Exception {
        if (skip) {
            return;
        }
        
        checkServerHomeExists();
        checkServerDirectoryExists();
        
        UndeployTask undeployTask = (UndeployTask) ant
                .createTask("antlib:net/wasdev/wlp/ant:undeploy");
        
        if (undeployTask == null) {
            throw new IllegalStateException(MessageFormat.format(messages.getString("error.dependencies.not.found"), "undeploy"));
        }
        
        if (appArchive != null || appArtifact != null) {
            
            if (appArchive != null && appArtifact != null) {
                throw new MojoExecutionException(
                        messages.getString("error.app.set.twice"));
            }
            
            if (appArtifact != null) {
                Artifact artifact = getArtifact(appArtifact);
                appArchive = artifact.getFile().getName();
                
                log.info(MessageFormat.format(
                        messages.getString("info.variable.set"),
                        "artifact based application", appArtifact));
                
            } else if (appArchive != null) {
                File file = new File(appArchive);
                if (file.exists()) {
                    appArchive = file.getName();
                }
                
                log.info(MessageFormat.format(
                        messages.getString("info.variable.set"),
                        "non-artifact based application", appArchive));
                
            }
            
            File destFile = new File(serverDirectory, "dropins/" + appArchive);
            if (destFile == null || !destFile.exists()
                    || destFile.isDirectory()) {
                throw new IOException(MessageFormat.format(
                        messages.getString("error.undeploy.app.noexist"),
                        destFile.getCanonicalPath()));
            }
            
            undeployTask.setFile(appArchive);
            log.info(MessageFormat.format(
                    messages.getString("info.undeploy.app"),
                    destFile.getCanonicalPath()));
            
        } else if (patternSet != null && patternSet.hasPatterns(ant.getAnt())) {
            log.info(messages.getString("info.undeploy.patternset"));
            undeployTask.addPatternset(patternSet);
        } else {
            log.info(messages.getString("info.undeploy.all"));
        }
        
        undeployTask.setInstallDir(installDirectory);
        undeployTask.setServerName(serverName);
        undeployTask.setUserDir(userDirectory);
        undeployTask.setOutputDir(outputDirectory);
        
        // Convert from seconds to milliseconds
        undeployTask.setTimeout(Long.toString(timeout * 1000));
        undeployTask.execute();
    }
88991
private void failOnOverlapOfClearedPropagated() {
        HashSet<String> overlap = new HashSet<String>(cleared);
        overlap.retainAll(propagated);
        if (overlap.isEmpty()) // only possible if builder is concurrently modified during build
            throw new ConcurrentModificationException();
        throw new IllegalStateException(Tr.formatMessage(tc, "CWWKC1151.context.lists.overlap", overlap));
    }
363056
@Override
  public void startOnInit(DeployService2Impl<I> deploy, Result<I> result)
  {
    deploy.startImpl(result);
  }
503487
private ConcurrentManaged<T> newManaged() {
    return ConcurrentManaged.newManaged(async, caller, managedOptions, setup, teardown);
  }
1362324
public void waitForDeployments(@Observes(precedence = -100) AfterStart event, OpenShiftAdapter client,
        CEEnvironmentProcessor.TemplateDetails details, TestClass testClass, CubeOpenShiftConfiguration configuration, OpenShiftClient openshiftClient)
        throws Exception {
        if (testClass == null) {
            // nothing to do, since we're not in ClassScoped context
            return;
        }
        if (details == null) {
            log.warning(String.format("No environment for %s", testClass.getName()));
            return;
        }
        log.info(String.format("Waiting for environment for %s", testClass.getName()));
        try {
            delay(client, details.getResources());
        } catch (Throwable t) {
            throw new IllegalArgumentException("Error waiting for template resources to deploy: " + testClass.getName(), t);
        }
    }
1218837
private void doRedeploy(final JsonObject deploymentInfo) {
    if (deploymentInfo.getString("type").equals("module")) {
      log.info(String.format("%s - redeploying module %s", DefaultGroupManager.this, deploymentInfo.getString("module")));
      final CountDownLatch latch = new CountDownLatch(1);
      platform.deployModule(deploymentInfo.getString("module"), deploymentInfo.getObject("config", new JsonObject()), deploymentInfo.getInteger("instances", 1), createRedeployHandler(deploymentInfo, latch));
      try {
        latch.await(10, TimeUnit.SECONDS);
      } catch (InterruptedException e) {
      }
    } else if (deploymentInfo.getString("type").equals("verticle")) {
      log.info(String.format("%s - redeploying verticle %s", DefaultGroupManager.this, deploymentInfo.getString("main")));
      final CountDownLatch latch = new CountDownLatch(1);
      if (deploymentInfo.getBoolean("worker", false)) {
        platform.deployWorkerVerticle(deploymentInfo.getString("main"), deploymentInfo.getObject("config", new JsonObject()), deploymentInfo.getInteger("instances", 1), deploymentInfo.getBoolean("multi-threaded"), createRedeployHandler(deploymentInfo, latch));
      } else {
        platform.deployVerticle(deploymentInfo.getString("main"), deploymentInfo.getObject("config", new JsonObject()), deploymentInfo.getInteger("instances", 1), createRedeployHandler(deploymentInfo, latch));
      }
      try {
        latch.await(10, TimeUnit.SECONDS);
      } catch (InterruptedException e) {
      }
    }
  }
1267936
private boolean handleOverridesAndConflicts(JvmOperation operation, Multimap<String, AbstractResolvedOperation> processedOperations) {
		String simpleName = operation.getSimpleName();
		if (!processedOperations.containsKey(simpleName)) {
			return true;
		}
		List<AbstractResolvedOperation> conflictingOperations = null;
		for (AbstractResolvedOperation candidate : processedOperations.get(simpleName)) {
			OverrideTester overrideTester = candidate.getOverrideTester();
			IOverrideCheckResult checkResult = overrideTester.isSubsignature(candidate, operation, false);
			if (checkResult.getDetails().contains(OverrideCheckDetails.DEFAULT_IMPL_CONFLICT)) {
				// The current operation conflicts with the candidate
				if (conflictingOperations == null)
					conflictingOperations = Lists.newLinkedList();
				conflictingOperations.add(candidate);
			} else if (checkResult.isOverridingOrImplementing()) {
				return false;
			}
		}
		if (conflictingOperations != null) {
			if (conflictingOperations.size() == 1 && conflictingOperations.get(0) instanceof ConflictingDefaultOperation) {
				// The current operation contributes to the already existing conflict
				ConflictingDefaultOperation conflictingDefaultOperation = (ConflictingDefaultOperation) conflictingOperations.get(0);
				boolean isOverridden = false;
				for (IResolvedOperation conflictingOp : conflictingDefaultOperation.getConflictingOperations()) {
					if (conflictingOp.getResolvedDeclarator().isSubtypeOf(operation.getDeclaringType())) {
						isOverridden = true;
						break;
					}
				}
				if (!isOverridden)
					conflictingDefaultOperation.getConflictingOperations().add(createResolvedOperation(operation));
				return false;
			}
			// A new conflict of default implementations was found
			if (operation.isAbstract()) {
				ConflictingDefaultOperation resolvedOperation = createConflictingOperation(conflictingOperations.get(0).getDeclaration());
				resolvedOperation.getConflictingOperations().add(createResolvedOperation(operation));
				for (AbstractResolvedOperation conflictingOp : conflictingOperations) {
					processedOperations.remove(simpleName, conflictingOp);
					if (conflictingOp.getDeclaration() != resolvedOperation.getDeclaration()) {
						resolvedOperation.getConflictingOperations().add(conflictingOp);
					}
				}
				processedOperations.put(simpleName, resolvedOperation);
			} else {
				ConflictingDefaultOperation resolvedOperation = createConflictingOperation(operation);
				for (AbstractResolvedOperation conflictingOp : conflictingOperations) {
					processedOperations.remove(simpleName, conflictingOp);
					resolvedOperation.getConflictingOperations().add(conflictingOp);
				}
				processedOperations.put(simpleName, resolvedOperation);
			}
			return false;
		}
		return true;
	}
103445
public void call() throws LauncherException, PackingException, SubmitDryRunResponse {
    SchedulerStateManagerAdaptor statemgr = Runtime.schedulerStateManagerAdaptor(runtime);
    TopologyAPI.Topology topology = Runtime.topology(runtime);
    String topologyName = Context.topologyName(config);

    PackingPlan packedPlan = LauncherUtils.getInstance().createPackingPlan(config, runtime);

    if (Context.dryRun(config)) {
      throw new SubmitDryRunResponse(topology, config, packedPlan);
    }

    // initialize the launcher
    launcher.initialize(config, runtime);

    // Set topology def first since we determine whether a topology is running
    // by checking the existence of topology def
    // store the trimmed topology definition into the state manager
    // TODO(rli): log-and-false anti-pattern is too nested on this path. will not refactor
    Boolean result = statemgr.setTopology(trimTopology(topology), topologyName);
    if (result == null || !result) {
      throw new LauncherException(String.format(
          "Failed to set topology definition for topology '%s'", topologyName));
    }

    result = statemgr.setPackingPlan(createPackingPlan(packedPlan), topologyName);
    if (result == null || !result) {
      statemgr.deleteTopology(topologyName);
      throw new LauncherException(String.format(
          "Failed to set packing plan for topology '%s'", topologyName));
    }

    // store the execution state into the state manager
    ExecutionEnvironment.ExecutionState executionState = createExecutionState();

    result = statemgr.setExecutionState(executionState, topologyName);
    if (result == null || !result) {
      statemgr.deletePackingPlan(topologyName);
      statemgr.deleteTopology(topologyName);
      throw new LauncherException(String.format(
          "Failed to set execution state for topology '%s'", topologyName));
    }

    // launch the topology, clear the state if it fails
    if (!launcher.launch(packedPlan)) {
      statemgr.deleteExecutionState(topologyName);
      statemgr.deletePackingPlan(topologyName);
      statemgr.deleteTopology(topologyName);
      throw new LauncherException(String.format(
          "Failed to launch topology '%s'", topologyName));
    }
  }
1195601
private void init() {
        final boolean trace = TraceComponent.isAnyTracingEnabled();

        Map<String, Map<String, Object>> threadContextConfigs = new HashMap<String, Map<String, Object>>();

        for (Enumeration<String> keys = properties.keys(); keys.hasMoreElements();) {
            String key = keys.nextElement();
            // Properties of flattened thread context configurations have the form:
            // threadContextConfigRef.0.*
            if (key.length() > 25 && key.charAt(22) == '.') {
                int dot = key.indexOf('.', 23);
                if (dot > 0) {
                    String group = key.substring(23, dot);
                    Map<String, Object> config = threadContextConfigs.get(group);
                    if (config == null)
                        threadContextConfigs.put(group, config = new TreeMap<String, Object>());
                    config.put(key.substring(dot + 1), properties.get(key));
                }
            } else if (trace && tc.isDebugEnabled() && !SUPPORTED_PROPERTIES.contains(key) && key.indexOf('.') < 0) {
                Tr.debug(this, tc, "unrecognized attribute: " + key);
                // TODO: once we have stricter variant of onError, do the following for it:
                //IllegalArgumentException x = ignoreWarnOrFail(null, IllegalArgumentException.class, "CWWKC1000.unrecognized.property", name, key);
                //if (x != null)
                //    throw x;
            }
        }

        threadContextConfigurations = new TreeMap<String, Map<String, ?>>();
        for (Map<String, Object> threadContextConfig : threadContextConfigs.values()) {
            String provider = (String) threadContextConfig.get("threadContextProvider");
            if (provider == null)
                provider = (String) threadContextConfig.get("config.referenceType") + ".provider";
            Map<String, ?> previous = threadContextConfigurations.put(provider, threadContextConfig);
            if (previous != null)
                throw new IllegalArgumentException(Tr.formatMessage(tc, "CWWKC1002.provider.cardinality.violation", name, previous.get("config.referenceType")));
        }

        // Inherit complementary thread context config from base instance
        ContextServiceImpl baseInstance = AccessController.doPrivileged(new PrivilegedAction<ContextServiceImpl>() {
            @Override
            public ContextServiceImpl run() {
                return (ContextServiceImpl) componentContext.locateService(BASE_INSTANCE);
            }
        });
        if (baseInstance != null)
            baseInstance.addComplementaryThreadContextConfigurationsTo(this);

        if (trace && tc.isDebugEnabled())
            Tr.debug(this, tc, "context configuration", threadContextConfigurations);
    }