Example usage for java.lang IllegalStateException getMessage

List of usage examples for java.lang IllegalStateException getMessage

Introduction

In this page you can find the example usage for java.lang IllegalStateException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.emc.storageos.api.service.impl.resource.DisasterRecoveryService.java

/**
 * Pause data replication to multiple standby sites.
 *
 * @param idList site uuid list to be removed
 * @return//ww  w .jav a2  s.com
 */
@POST
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@CheckPermission(roles = { Role.SECURITY_ADMIN, Role.RESTRICTED_SECURITY_ADMIN, Role.SYSTEM_ADMIN,
        Role.RESTRICTED_SYSTEM_ADMIN }, blockProxies = true)
@Path("/pause")
public Response pause(SiteIdListParam idList) {
    List<String> siteIdList = idList.getIds();
    String siteIdStr = StringUtils.join(siteIdList, ",");
    log.info("Begin to pause standby site from local vdc by uuid: {}", siteIdStr);
    List<Site> toBePausedSites = new ArrayList<>();
    List<String> siteNameList = new ArrayList<>();
    for (String siteId : siteIdList) {
        Site site;
        try {
            site = drUtil.getSiteFromLocalVdc(siteId);
        } catch (Exception ex) {
            log.error("Can't load site {} from ZK", siteId);
            throw APIException.badRequests.siteIdNotFound();
        }
        SiteState state = site.getState();
        if (state.equals(SiteState.ACTIVE)) {
            log.error("Unable to pause this site {}. It is acitve", siteId);
            throw APIException.badRequests.operationNotAllowedOnActiveSite();
        }
        if (!state.equals(SiteState.STANDBY_SYNCED)) {
            log.error("Unable to pause this site {}. It is in state {}", siteId, state);
            throw APIException.badRequests.operationOnlyAllowedOnSyncedSite(site.getName(), state.toString());
        }
        toBePausedSites.add(site);
        siteNameList.add(site.getName());
    }

    // This String is only used to output human readable message to user when Exception is thrown
    String siteNameStr = StringUtils.join(siteNameList, ',');

    try {
        commonPrecheck(siteIdList);
    } catch (IllegalStateException e) {
        throw APIException.internalServerErrors.pauseStandbyPrecheckFailed(siteNameStr, e.getMessage());
    }

    InterProcessLock lock = drUtil.getDROperationLock();

    // any error is not retry-able beyond this point.
    List<String> sitesString = new ArrayList<>();
    try {
        log.info("Pausing sites");
        long vdcTargetVersion = DrUtil.newVdcConfigVersion();
        coordinator.startTransaction();
        for (Site site : toBePausedSites) {
            site.setState(SiteState.STANDBY_PAUSING);
            site.setLastStateUpdateTime(System.currentTimeMillis());
            coordinator.persistServiceConfiguration(site.toConfiguration());
            drUtil.recordDrOperationStatus(site);
            sitesString.add(site.toBriefString());
            // notify the to-be-paused sites before others.
            drUtil.updateVdcTargetVersion(site.getUuid(), SiteInfo.DR_OP_PAUSE_STANDBY, vdcTargetVersion);
        }
        log.info("Notify all sites for reconfig");
        for (Site site : drUtil.listSites()) {
            if (toBePausedSites.contains(site)) { // Site#equals only compares the site uuid
                // already notified
                continue;
            }
            drUtil.updateVdcTargetVersion(site.getUuid(), SiteInfo.DR_OP_PAUSE_STANDBY, vdcTargetVersion);
        }
        coordinator.commitTransaction();
        auditDisasterRecoveryOps(OperationTypeEnum.PAUSE_STANDBY, AuditLogManager.AUDITLOG_SUCCESS,
                AuditLogManager.AUDITOP_BEGIN, StringUtils.join(sitesString, ','));
        return Response.status(Response.Status.ACCEPTED).build();
    } catch (Exception e) {
        log.error("Failed to pause site {}", siteIdStr, e);
        coordinator.discardTransaction();
        auditDisasterRecoveryOps(OperationTypeEnum.PAUSE_STANDBY, AuditLogManager.AUDITLOG_FAILURE, null,
                StringUtils.join(sitesString, ','));
        throw APIException.internalServerErrors.pauseStandbyFailed(siteNameStr, e.getMessage());
    } finally {
        try {
            lock.release();
        } catch (Exception ignore) {
            log.error(String.format("Lock release failed when pausing standby site: %s", siteIdStr));
        }
    }
}

From source file:com.emc.storageos.api.service.impl.resource.DisasterRecoveryService.java

/**
 * Remove multiple standby sites. After successfully done, it stops data replication to those sites
 * /*from   w w  w . ja  v  a  2s  .c  om*/
 * @param idList site uuid list to be removed
 * @return
 */
@POST
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@CheckPermission(roles = { Role.SECURITY_ADMIN, Role.RESTRICTED_SECURITY_ADMIN }, blockProxies = true)
@Path("/remove")
public Response remove(SiteIdListParam idList) {
    List<String> siteIdList = idList.getIds();
    String siteIdStr = StringUtils.join(siteIdList, ",");
    log.info("Begin to remove standby site from local vdc by uuid: {}", siteIdStr);
    List<Site> toBeRemovedSites = new ArrayList<>();
    for (String siteId : siteIdList) {
        Site site;
        try {
            site = drUtil.getSiteFromLocalVdc(siteId);
        } catch (Exception ex) {
            log.error("Can't load site {} from ZK", siteId);
            throw APIException.badRequests.siteIdNotFound();
        }
        if (site.getState().equals(SiteState.ACTIVE)) {
            log.error("Unable to remove this site {}. It is acitve", siteId);
            throw APIException.badRequests.operationNotAllowedOnActiveSite();
        }
        if (site.getState().isDROperationOngoing() && !site.getState().equals(SiteState.STANDBY_SYNCING)) {
            log.error(
                    "Unable to remove this site {} in state {}. "
                            + "DR operation other than STANDBY_SYNCING is ongoing",
                    siteId, site.getState().name());
            throw APIException.internalServerErrors.concurrentDROperationNotAllowed(site.getName(),
                    site.getState().toString());
        }
        toBeRemovedSites.add(site);
    }

    // Build a site names' string for more human-readable Exception error message
    StringBuilder siteNamesSb = new StringBuilder();
    for (Site site : toBeRemovedSites) {
        if (siteNamesSb.length() != 0) {
            siteNamesSb.append(", ");
        }
        siteNamesSb.append(site.getName());
    }
    String SiteNamesStr = siteNamesSb.toString();

    try {
        commonPrecheck(siteIdList);
    } catch (IllegalStateException e) {
        throw APIException.internalServerErrors.removeStandbyPrecheckFailed(SiteNamesStr, e.getMessage());
    }

    InterProcessLock lock = drUtil.getDROperationLock(false);

    List<String> sitesString = new ArrayList<>();
    try {
        log.info("Removing sites");
        coordinator.startTransaction();
        for (Site site : toBeRemovedSites) {
            site.setState(SiteState.STANDBY_REMOVING);
            coordinator.persistServiceConfiguration(site.toConfiguration());
            drUtil.recordDrOperationStatus(site);
            sitesString.add(site.toBriefString());
        }
        log.info("Notify all sites for reconfig");
        long vdcTargetVersion = DrUtil.newVdcConfigVersion();
        for (Site standbySite : drUtil.listSites()) {
            drUtil.updateVdcTargetVersion(standbySite.getUuid(), SiteInfo.DR_OP_REMOVE_STANDBY,
                    vdcTargetVersion);
        }
        coordinator.commitTransaction();
        auditDisasterRecoveryOps(OperationTypeEnum.REMOVE_STANDBY, AuditLogManager.AUDITLOG_SUCCESS,
                AuditLogManager.AUDITOP_BEGIN, StringUtils.join(sitesString, ','));
        return Response.status(Response.Status.ACCEPTED).build();
    } catch (Exception e) {
        log.error("Failed to remove site {}", siteIdStr, e);
        coordinator.discardTransaction();
        auditDisasterRecoveryOps(OperationTypeEnum.REMOVE_STANDBY, AuditLogManager.AUDITLOG_FAILURE, null,
                StringUtils.join(sitesString, ','));
        throw APIException.internalServerErrors.removeStandbyFailed(SiteNamesStr, e.getMessage());
    } finally {
        try {
            lock.release();
        } catch (Exception ignore) {
            log.error(String.format("Lock release failed when removing standby sites: %s", siteIdStr));
        }
    }
}

From source file:com.oakesville.mythling.MediaActivity.java

protected void handleEmptyMediaList() {
    if (isSplitView()) {
        try {//w w w  .ja  va 2s  .c  om
            showSubListPane(null);
        } catch (IllegalStateException ex) {
            // "Can not perform this action after onSaveInstanceState"
            Log.e(TAG, ex.getMessage(), ex);
            if (getAppSettings().isErrorReportingEnabled())
                new Reporter(ex).send();
        }
    }
    if (getAppSettings().isTv()) {
        // empty list - set focus on action bar
        setFocusOnActionBar();
    }
}

From source file:com.emc.storageos.api.service.impl.resource.DisasterRecoveryService.java

/**
 * Resume data replication for a paused standby site
 * //from ww  w  .j a va 2 s.c om
 * @param uuid site UUID
 * @return updated standby site representation
 */
@POST
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@CheckPermission(roles = { Role.SECURITY_ADMIN, Role.RESTRICTED_SECURITY_ADMIN, Role.SYSTEM_ADMIN,
        Role.RESTRICTED_SYSTEM_ADMIN }, blockProxies = true)
@Path("/{uuid}/resume")
public SiteRestRep resumeStandby(@PathParam("uuid") String uuid) {
    log.info("Begin to resume data sync to standby site identified by uuid: {}", uuid);
    Site standby = validateSiteConfig(uuid);
    if (!standby.getState().equals(SiteState.STANDBY_PAUSED)) {
        log.error("site {} is in state {}, should be STANDBY_PAUSED", uuid, standby.getState());
        throw APIException.badRequests.operationOnlyAllowedOnPausedSite(standby.getName(),
                standby.getState().toString());
    }

    try (InternalSiteServiceClient client = createInternalSiteServiceClient(standby)) {
        commonPrecheck(uuid);

        client.setCoordinatorClient(coordinator);
        client.setKeyGenerator(apiSignatureGenerator);
        client.resumePrecheck();
    } catch (IllegalStateException e) {
        throw APIException.internalServerErrors.resumeStandbyPrecheckFailed(standby.getName(), e.getMessage());
    }

    // Do this before tx get started which might write key to zk.
    SecretKey secretKey = apiSignatureGenerator.getSignatureKey(SignatureKeyType.INTERVDC_API);

    InterProcessLock lock = drUtil.getDROperationLock();

    long vdcTargetVersion = DrUtil.newVdcConfigVersion();
    try {
        coordinator.startTransaction();
        for (Site site : drUtil.listStandbySites()) {
            long dataRevision = 0;
            if (site.getUuid().equals(uuid)) {
                int gcGracePeriod = DbConfigConstants.DEFAULT_GC_GRACE_PERIOD;
                String strVal = dbCommonInfo.getProperty(DbClientImpl.DB_CASSANDRA_INDEX_GC_GRACE_PERIOD);
                if (strVal != null) {
                    gcGracePeriod = Integer.parseInt(strVal);
                }
                // last state update should be PAUSED
                if ((System.currentTimeMillis() - site.getLastStateUpdateTime()) / 1000 >= gcGracePeriod) {
                    log.error("site {} has been paused for too long, we will re-init the target standby", uuid);

                    // init the to-be resumed standby site
                    dataRevision = System.currentTimeMillis();
                    List<Site> standbySites = drUtil.listStandbySites();
                    SiteConfigParam configParam = prepareSiteConfigParam(standbySites,
                            ipsecConfig.getPreSharedKey(), uuid, dataRevision, vdcTargetVersion, secretKey);
                    try (InternalSiteServiceClient internalSiteServiceClient = new InternalSiteServiceClient()) {
                        internalSiteServiceClient.setCoordinatorClient(coordinator);
                        internalSiteServiceClient.setServer(site.getVipEndPoint());
                        internalSiteServiceClient.initStandby(configParam);
                    }
                }

                // update the site state AFTER checking the last state update time
                site.setState(SiteState.STANDBY_RESUMING);
                coordinator.persistServiceConfiguration(site.toConfiguration());
                drUtil.recordDrOperationStatus(site);
            }

            if (dataRevision != 0) {
                drUtil.updateVdcTargetVersion(site.getUuid(), SiteInfo.DR_OP_CHANGE_DATA_REVISION, dataRevision,
                        vdcTargetVersion);
            } else {
                drUtil.updateVdcTargetVersion(site.getUuid(), SiteInfo.DR_OP_RESUME_STANDBY, vdcTargetVersion);
            }
        }

        // update the local(acitve) site last
        drUtil.updateVdcTargetVersion(coordinator.getSiteId(), SiteInfo.DR_OP_RESUME_STANDBY, vdcTargetVersion);
        coordinator.commitTransaction();
        auditDisasterRecoveryOps(OperationTypeEnum.RESUME_STANDBY, AuditLogManager.AUDITLOG_SUCCESS,
                AuditLogManager.AUDITOP_BEGIN, standby.toBriefString());

        return siteMapper.map(standby);
    } catch (Exception e) {
        log.error("Error resuming site {}", uuid, e);
        coordinator.discardTransaction();
        auditDisasterRecoveryOps(OperationTypeEnum.RESUME_STANDBY, AuditLogManager.AUDITLOG_FAILURE, null,
                standby.toBriefString());
        InternalServerErrorException resumeStandbyFailedException = APIException.internalServerErrors
                .resumeStandbyFailed(standby.getName(), e.getMessage());
        throw resumeStandbyFailedException;
    } finally {
        try {
            lock.release();
        } catch (Exception ignore) {
            log.error(String.format("Lock release failed when resuming standby site: %s", uuid));
        }
    }
}

From source file:ch.cyberduck.core.pool.DefaultSessionPool.java

@Override
public Session<?> borrow(final BackgroundActionState callback) throws BackgroundException {
    final Integer numActive = pool.getNumActive();
    if (numActive > POOL_WARNING_THRESHOLD) {
        log.warn(String.format("Possibly large number of open connections (%d) in pool %s", numActive, this));
    }/*from w w  w  .  j  av a  2  s .  co  m*/
    try {
        /*
         * The number of times this action has been run
         */
        int repeat = 0;
        while (!callback.isCanceled()) {
            try {
                if (log.isInfoEnabled()) {
                    log.info(String.format("Borrow session from pool %s", this));
                }
                final Session<?> session = pool.borrowObject();
                if (log.isInfoEnabled()) {
                    log.info(String.format("Borrowed session %s from pool %s", session, this));
                }
                if (DISCONNECTED == features) {
                    features = new StatelessSessionPool(connect, session, cache, transcript, registry);
                }
                return session.withListener(transcript);
            } catch (IllegalStateException e) {
                throw new ConnectionCanceledException(e);
            } catch (NoSuchElementException e) {
                if (pool.isClosed()) {
                    throw new ConnectionCanceledException(e);
                }
                final Throwable cause = e.getCause();
                if (null == cause) {
                    log.warn(String.format("Timeout borrowing session from pool %s. Wait for another %dms",
                            this, BORROW_MAX_WAIT_INTERVAL));
                    // Timeout
                    continue;
                }
                if (cause instanceof BackgroundException) {
                    final BackgroundException failure = (BackgroundException) cause;
                    log.warn(String.format("Failure %s obtaining connection for %s", failure, this));
                    if (diagnostics.determine(failure) == FailureDiagnostics.Type.network) {
                        final int max = Math.max(1, pool.getMaxIdle() - 1);
                        log.warn(String.format("Lower maximum idle pool size to %d connections.", max));
                        pool.setMaxIdle(max);
                        // Clear pool from idle connections
                        pool.clear();
                    }
                    throw failure;
                }
                log.error(String.format("Borrowing session from pool %s failed with %s", this, e));
                throw new DefaultExceptionMappingService().map(cause);
            }
        }
        throw new ConnectionCanceledException();
    } catch (BackgroundException e) {
        throw e;
    } catch (Exception e) {
        if (e.getCause() instanceof BackgroundException) {
            throw ((BackgroundException) e.getCause());
        }
        throw new BackgroundException(e.getMessage(), e);
    }
}

From source file:com.oakesville.mythling.MediaActivity.java

protected void downloadItem(final Item item) {
    try {/* w  ww .j  av  a  2 s . co  m*/
        final URL baseUrl = getAppSettings().getMythTvServicesBaseUrlWithCredentials();

        String fileUrl = baseUrl + "/Content/GetFile?";
        if (item.getStorageGroup() == null)
            fileUrl += "StorageGroup=None&";
        else
            fileUrl += "StorageGroup=" + item.getStorageGroup().getName() + "&";
        fileUrl += "FileName=" + URLEncoder.encode(item.getFilePath(), "UTF-8");

        Uri uri = Uri.parse(fileUrl.toString());
        ProxyInfo proxyInfo = MediaStreamProxy.needsAuthProxy(uri);
        if (proxyInfo != null) {
            // needs proxying to support authentication since DownloadManager doesn't support
            MediaStreamProxy proxy = new MediaStreamProxy(proxyInfo,
                    AuthType.valueOf(appSettings.getMythTvServicesAuthType()));
            proxy.init();
            proxy.start();
            fileUrl = "http://" + proxy.getLocalhost().getHostAddress() + ":" + proxy.getPort() + uri.getPath();
            if (uri.getQuery() != null)
                fileUrl += "?" + uri.getQuery();
        }

        Log.i(TAG, "Media download URL: " + fileUrl);

        stopProgress();

        DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        Request request = new Request(Uri.parse(fileUrl));
        request.setTitle(item.getOneLineTitle());
        String downloadFilePath = null;
        try {
            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                File downloadDir = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                if (downloadDir.exists()) {
                    String downloadPath = AppSettings.getExternalStorageDir() + "/";
                    if (getPath() != null && !getPath().isEmpty() && !getPath().equals("/"))
                        downloadPath += getPath() + "/";
                    File destDir = new File(downloadDir + "/" + downloadPath);
                    if (destDir.isDirectory() || destDir.mkdirs()) {
                        downloadFilePath = downloadPath + item.getDownloadFilename();
                        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                downloadFilePath);
                        request.allowScanningByMediaScanner();
                    }
                }
            }
        } catch (IllegalStateException ex) {
            // store internal
        } catch (Exception ex) {
            // log, report and store internal
            Log.e(TAG, ex.getMessage(), ex);
            if (getAppSettings().isErrorReportingEnabled())
                new Reporter(ex).send();
            Toast.makeText(getApplicationContext(), getString(R.string.error_) + ex.toString(),
                    Toast.LENGTH_LONG).show();
        }
        long downloadId = dm.enqueue(request);
        registerDownloadReceiver(item, downloadId);
        Toast.makeText(getApplicationContext(), getString(R.string.downloading_) + item.getOneLineTitle(),
                Toast.LENGTH_LONG).show();
        getAppData().addDownload(new Download(item.getId(), downloadId, downloadFilePath, new Date()));
        if (item.isRecording() && (mediaList.isMythTv28() || getAppSettings().isMythlingMediaServices()))
            new GetCutListTask((Recording) item, downloadId).execute();
    } catch (Exception ex) {
        stopProgress();
        Log.e(TAG, ex.getMessage(), ex);
        if (getAppSettings().isErrorReportingEnabled())
            new Reporter(ex).send();
        Toast.makeText(getApplicationContext(), getString(R.string.error_) + ex.toString(), Toast.LENGTH_LONG)
                .show();
    }
}

From source file:me.azenet.UHPlugin.UHPluginCommand.java

/**
 * This commands broadcast the winner(s) of the game and sends some fireworks at these players.
 * It fails if there is more than one team alive.
 * //from  ww  w.  j a  v  a2  s  .  c o m
 * Usage: /uh finish
 * 
 * @param sender
 * @param command
 * @param label
 * @param args
 */
@SuppressWarnings("unused")
private void doFinish(CommandSender sender, Command command, String label, String[] args) {

    try {
        p.getGameManager().finishGame();

    } catch (IllegalStateException e) {

        if (e.getMessage().equals(UHGameManager.FINISH_ERROR_NOT_STARTED)) {
            sender.sendMessage(i.t("finish.notStarted"));
        } else if (e.getMessage().equals(UHGameManager.FINISH_ERROR_NOT_FINISHED)) {
            sender.sendMessage(i.t("finish.notFinished"));
        } else {
            throw e;
        }
    }

}

From source file:org.apache.nifi.web.api.VersionsResource.java

private VersionControlInformationEntity updateFlowVersion(final String groupId,
        final ComponentLifecycle componentLifecycle, final URI exampleUri,
        final Set<AffectedComponentEntity> affectedComponents, final boolean replicateRequest,
        final Revision revision, final VersionControlInformationEntity requestEntity,
        final VersionedFlowSnapshot flowSnapshot,
        final AsynchronousWebRequest<VersionControlInformationEntity> asyncRequest,
        final String idGenerationSeed, final boolean verifyNotModified,
        final boolean updateDescendantVersionedFlows) throws LifecycleManagementException, ResumeFlowException {

    // Steps 6-7: Determine which components must be stopped and stop them.
    final Set<String> stoppableReferenceTypes = new HashSet<>();
    stoppableReferenceTypes.add(AffectedComponentDTO.COMPONENT_TYPE_PROCESSOR);
    stoppableReferenceTypes.add(AffectedComponentDTO.COMPONENT_TYPE_REMOTE_INPUT_PORT);
    stoppableReferenceTypes.add(AffectedComponentDTO.COMPONENT_TYPE_REMOTE_OUTPUT_PORT);
    stoppableReferenceTypes.add(AffectedComponentDTO.COMPONENT_TYPE_INPUT_PORT);
    stoppableReferenceTypes.add(AffectedComponentDTO.COMPONENT_TYPE_OUTPUT_PORT);

    final Set<AffectedComponentEntity> runningComponents = affectedComponents.stream()
            .filter(dto -> stoppableReferenceTypes.contains(dto.getComponent().getReferenceType()))
            .filter(dto -> "Running".equalsIgnoreCase(dto.getComponent().getState()))
            .collect(Collectors.toSet());

    logger.info("Stopping {} Processors", runningComponents.size());
    final CancellableTimedPause stopComponentsPause = new CancellableTimedPause(250, Long.MAX_VALUE,
            TimeUnit.MILLISECONDS);
    asyncRequest.setCancelCallback(stopComponentsPause::cancel);
    componentLifecycle.scheduleComponents(exampleUri, groupId, runningComponents, ScheduledState.STOPPED,
            stopComponentsPause);//from w  w w . j  ava 2 s  . c o  m

    if (asyncRequest.isCancelled()) {
        return null;
    }
    asyncRequest.update(new Date(), "Disabling Affected Controller Services", 20);

    // Steps 8-9. Disable enabled controller services that are affected
    final Set<AffectedComponentEntity> enabledServices = affectedComponents.stream()
            .filter(dto -> AffectedComponentDTO.COMPONENT_TYPE_CONTROLLER_SERVICE
                    .equals(dto.getComponent().getReferenceType()))
            .filter(dto -> "Enabled".equalsIgnoreCase(dto.getComponent().getState()))
            .collect(Collectors.toSet());

    logger.info("Disabling {} Controller Services", enabledServices.size());
    final CancellableTimedPause disableServicesPause = new CancellableTimedPause(250, Long.MAX_VALUE,
            TimeUnit.MILLISECONDS);
    asyncRequest.setCancelCallback(disableServicesPause::cancel);
    componentLifecycle.activateControllerServices(exampleUri, groupId, enabledServices,
            ControllerServiceState.DISABLED, disableServicesPause);

    if (asyncRequest.isCancelled()) {
        return null;
    }
    asyncRequest.update(new Date(), "Updating Flow", 40);

    logger.info("Updating Process Group with ID {} to version {} of the Versioned Flow", groupId,
            flowSnapshot.getSnapshotMetadata().getVersion());

    // If replicating request, steps 10-12 are performed on each node individually, and this is accomplished
    // by replicating a PUT to /nifi-api/versions/process-groups/{groupId}
    try {
        if (replicateRequest) {
            final NiFiUser user = NiFiUserUtils.getNiFiUser();

            final URI updateUri;
            try {
                updateUri = new URI(exampleUri.getScheme(), exampleUri.getUserInfo(), exampleUri.getHost(),
                        exampleUri.getPort(), "/nifi-api/versions/process-groups/" + groupId, null,
                        exampleUri.getFragment());
            } catch (URISyntaxException e) {
                throw new RuntimeException(e);
            }

            final Map<String, String> headers = new HashMap<>();
            headers.put("content-type", MediaType.APPLICATION_JSON);

            final VersionedFlowSnapshotEntity snapshotEntity = new VersionedFlowSnapshotEntity();
            snapshotEntity.setProcessGroupRevision(dtoFactory.createRevisionDTO(revision));
            snapshotEntity.setRegistryId(requestEntity.getVersionControlInformation().getRegistryId());
            snapshotEntity.setVersionedFlow(flowSnapshot);
            snapshotEntity.setUpdateDescendantVersionedFlows(updateDescendantVersionedFlows);

            final NodeResponse clusterResponse;
            try {
                logger.debug("Replicating PUT request to {} for user {}", updateUri, user);

                if (getReplicationTarget() == ReplicationTarget.CLUSTER_NODES) {
                    clusterResponse = getRequestReplicator()
                            .replicate(user, HttpMethod.PUT, updateUri, snapshotEntity, headers)
                            .awaitMergedResponse();
                } else {
                    clusterResponse = getRequestReplicator().forwardToCoordinator(getClusterCoordinatorNode(),
                            user, HttpMethod.PUT, updateUri, snapshotEntity, headers).awaitMergedResponse();
                }
            } catch (final InterruptedException ie) {
                logger.warn("Interrupted while replicating PUT request to {} for user {}", updateUri, user);
                Thread.currentThread().interrupt();
                throw new LifecycleManagementException("Interrupted while updating flows across cluster", ie);
            }

            final int updateFlowStatus = clusterResponse.getStatus();
            if (updateFlowStatus != Status.OK.getStatusCode()) {
                final String explanation = getResponseEntity(clusterResponse, String.class);
                logger.error(
                        "Failed to update flow across cluster when replicating PUT request to {} for user {}. Received {} response with explanation: {}",
                        updateUri, user, updateFlowStatus, explanation);
                throw new LifecycleManagementException(
                        "Failed to update Flow on all nodes in cluster due to " + explanation);
            }

        } else {
            // Step 10: Ensure that if any connection exists in the flow and does not exist in the proposed snapshot,
            // that it has no data in it. Ensure that no Input Port was removed, unless it currently has no incoming connections.
            // Ensure that no Output Port was removed, unless it currently has no outgoing connections.
            serviceFacade.verifyCanUpdate(groupId, flowSnapshot, true, verifyNotModified);

            // Step 11-12. Update Process Group to the new flow and update variable registry with any Variables that were added or removed
            final VersionControlInformationDTO requestVci = requestEntity.getVersionControlInformation();

            final Bucket bucket = flowSnapshot.getBucket();
            final VersionedFlow flow = flowSnapshot.getFlow();

            final VersionedFlowSnapshotMetadata metadata = flowSnapshot.getSnapshotMetadata();
            final VersionControlInformationDTO vci = new VersionControlInformationDTO();
            vci.setBucketId(metadata.getBucketIdentifier());
            vci.setBucketName(bucket.getName());
            vci.setFlowDescription(flow.getDescription());
            vci.setFlowId(flow.getIdentifier());
            vci.setFlowName(flow.getName());
            vci.setGroupId(groupId);
            vci.setRegistryId(requestVci.getRegistryId());
            vci.setRegistryName(serviceFacade.getFlowRegistryName(requestVci.getRegistryId()));
            vci.setVersion(metadata.getVersion());
            vci.setState(flowSnapshot.isLatest() ? VersionedFlowState.UP_TO_DATE.name()
                    : VersionedFlowState.STALE.name());

            serviceFacade.updateProcessGroupContents(revision, groupId, vci, flowSnapshot, idGenerationSeed,
                    verifyNotModified, false, updateDescendantVersionedFlows);
        }
    } finally {
        if (!asyncRequest.isCancelled()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Re-Enabling {} Controller Services: {}", enabledServices.size(), enabledServices);
            }

            asyncRequest.update(new Date(), "Re-Enabling Controller Services", 60);

            // Step 13. Re-enable all disabled controller services
            final CancellableTimedPause enableServicesPause = new CancellableTimedPause(250, Long.MAX_VALUE,
                    TimeUnit.MILLISECONDS);
            asyncRequest.setCancelCallback(enableServicesPause::cancel);
            final Set<AffectedComponentEntity> servicesToEnable = getUpdatedEntities(enabledServices);
            logger.info("Successfully updated flow; re-enabling {} Controller Services",
                    servicesToEnable.size());

            try {
                componentLifecycle.activateControllerServices(exampleUri, groupId, servicesToEnable,
                        ControllerServiceState.ENABLED, enableServicesPause);
            } catch (final IllegalStateException ise) {
                // Component Lifecycle will re-enable the Controller Services only if they are valid. If IllegalStateException gets thrown, we need to provide
                // a more intelligent error message as to exactly what happened, rather than indicate that the flow could not be updated.
                throw new ResumeFlowException(
                        "Failed to re-enable Controller Services because " + ise.getMessage(), ise);
            }
        }

        if (!asyncRequest.isCancelled()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Restart {} Processors: {}", runningComponents.size(), runningComponents);
            }

            asyncRequest.update(new Date(), "Restarting Processors", 80);

            // Step 14. Restart all components
            final Set<AffectedComponentEntity> componentsToStart = getUpdatedEntities(runningComponents);

            // If there are any Remote Group Ports that are supposed to be started and have no connections, we want to remove those from our Set.
            // This will happen if the Remote Group Port is transmitting when the version change happens but the new flow version does not have
            // a connection to the port. In such a case, the Port still is included in the Updated Entities because we do not remove them
            // when updating the flow (they are removed in the background).
            final Set<AffectedComponentEntity> avoidStarting = new HashSet<>();
            for (final AffectedComponentEntity componentEntity : componentsToStart) {
                final AffectedComponentDTO componentDto = componentEntity.getComponent();
                final String referenceType = componentDto.getReferenceType();
                if (!AffectedComponentDTO.COMPONENT_TYPE_REMOTE_INPUT_PORT.equals(referenceType)
                        && !AffectedComponentDTO.COMPONENT_TYPE_REMOTE_OUTPUT_PORT.equals(referenceType)) {
                    continue;
                }

                boolean startComponent;
                try {
                    startComponent = serviceFacade.isRemoteGroupPortConnected(componentDto.getProcessGroupId(),
                            componentDto.getId());
                } catch (final ResourceNotFoundException rnfe) {
                    // Could occur if RPG is refreshed at just the right time.
                    startComponent = false;
                }

                // We must add the components to avoid starting to a separate Set and then remove them below,
                // rather than removing the component here, because doing so would result in a ConcurrentModificationException.
                if (!startComponent) {
                    avoidStarting.add(componentEntity);
                }
            }
            componentsToStart.removeAll(avoidStarting);

            final CancellableTimedPause startComponentsPause = new CancellableTimedPause(250, Long.MAX_VALUE,
                    TimeUnit.MILLISECONDS);
            asyncRequest.setCancelCallback(startComponentsPause::cancel);
            logger.info("Restarting {} Processors", componentsToStart.size());

            try {
                componentLifecycle.scheduleComponents(exampleUri, groupId, componentsToStart,
                        ScheduledState.RUNNING, startComponentsPause);
            } catch (final IllegalStateException ise) {
                // Component Lifecycle will restart the Processors only if they are valid. If IllegalStateException gets thrown, we need to provide
                // a more intelligent error message as to exactly what happened, rather than indicate that the flow could not be updated.
                throw new ResumeFlowException("Failed to restart components because " + ise.getMessage(), ise);
            }
        }
    }

    asyncRequest.setCancelCallback(null);
    if (asyncRequest.isCancelled()) {
        return null;
    }
    asyncRequest.update(new Date(), "Complete", 100);

    return serviceFacade.getVersionControlInformation(groupId);
}

From source file:com.ciphertool.genetics.algorithms.MultigenerationalGeneticAlgorithmTest.java

@Test
public void testValidateParameters_AllErrors() {
    MultigenerationalGeneticAlgorithm multigenerationalGeneticAlgorithm = new MultigenerationalGeneticAlgorithm();

    GeneticAlgorithmStrategy strategyToSet = new GeneticAlgorithmStrategy();
    strategyToSet.setGeneticStructure(null);
    strategyToSet.setPopulationSize(0);//from  w  ww  .ja v a2 s . c  o  m
    strategyToSet.setLifespan(null);

    /*
     * This must be set via reflection because the setter method does its
     * own validation
     */
    Field survivalRateField = ReflectionUtils.findField(GeneticAlgorithmStrategy.class, "survivalRate");
    ReflectionUtils.makeAccessible(survivalRateField);
    ReflectionUtils.setField(survivalRateField, strategyToSet, -0.1);

    /*
     * This must be set via reflection because the setter method does its
     * own validation
     */
    Field mutationRateField = ReflectionUtils.findField(GeneticAlgorithmStrategy.class, "mutationRate");
    ReflectionUtils.makeAccessible(mutationRateField);
    ReflectionUtils.setField(mutationRateField, strategyToSet, -0.1);

    strategyToSet.setMaxMutationsPerIndividual(-1);

    /*
     * This must be set via reflection because the setter method does its
     * own validation
     */
    Field crossoverRateField = ReflectionUtils.findField(GeneticAlgorithmStrategy.class, "crossoverRate");
    ReflectionUtils.makeAccessible(crossoverRateField);
    ReflectionUtils.setField(crossoverRateField, strategyToSet, -0.1);

    strategyToSet.setMutateDuringCrossover(null);
    strategyToSet.setMaxGenerations(0);
    strategyToSet.setCrossoverAlgorithm(null);
    strategyToSet.setFitnessEvaluator(null);
    strategyToSet.setMutationAlgorithm(null);
    strategyToSet.setSelectionAlgorithm(null);
    strategyToSet.setSelector(null);

    Field strategyField = ReflectionUtils.findField(MultigenerationalGeneticAlgorithm.class, "strategy");
    ReflectionUtils.makeAccessible(strategyField);
    ReflectionUtils.setField(strategyField, multigenerationalGeneticAlgorithm, strategyToSet);

    boolean exceptionCaught = false;

    try {
        multigenerationalGeneticAlgorithm.validateParameters();
    } catch (IllegalStateException ise) {
        String expectedMessage = "Unable to execute genetic algorithm because one or more of the required parameters are missing.  The validation errors are:";
        expectedMessage += "\n\t-Parameter 'geneticStructure' cannot be null.";
        expectedMessage += "\n\t-Parameter 'populationSize' must be greater than zero.";
        expectedMessage += "\n\t-Parameter 'lifespan' cannot be null.";
        expectedMessage += "\n\t-Parameter 'survivalRate' must be greater than zero.";
        expectedMessage += "\n\t-Parameter 'mutationRate' must be greater than or equal to zero.";
        expectedMessage += "\n\t-Parameter 'maxMutationsPerIndividual' must be greater than or equal to zero.";
        expectedMessage += "\n\t-Parameter 'crossoverRate' must be greater than or equal to zero.";
        expectedMessage += "\n\t-Parameter 'mutateDuringCrossover' cannot be null.";
        expectedMessage += "\n\t-Parameter 'maxGenerations' cannot be null and must not equal zero.";
        expectedMessage += "\n\t-Parameter 'crossoverAlgorithm' cannot be null.";
        expectedMessage += "\n\t-Parameter 'fitnessEvaluator' cannot be null.";
        expectedMessage += "\n\t-Parameter 'mutationAlgorithm' cannot be null.";
        expectedMessage += "\n\t-Parameter 'selectionAlgorithm' cannot be null.";
        expectedMessage += "\n\t-Parameter 'selectorMethod' cannot be null.";

        assertEquals(expectedMessage, ise.getMessage());

        exceptionCaught = true;
    }

    assertTrue(exceptionCaught);
}