Example usage for org.springframework.util Assert state

List of usage examples for org.springframework.util Assert state

Introduction

In this page you can find the example usage for org.springframework.util Assert state.

Prototype

public static void state(boolean expression, Supplier<String> messageSupplier) 

Source Link

Document

Assert a boolean expression, throwing an IllegalStateException if the expression evaluates to false .

Usage

From source file:org.opennms.netmgt.statsd.AbstractReportInstance.java

/**
 * <p>afterPropertiesSet</p>
 */// w  ww  . j av  a  2  s . c  o  m
@Override
public void afterPropertiesSet() {
    Assert.state(m_reportDefinition != null, "property reportDefinition must be set to a non-null value");
}

From source file:org.opennms.web.controller.GraphResultsController.java

/**
 * Ensures that required properties are set to valid values.
 *
 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
 * @throws java.lang.Exception if any.//from   w  ww  .ja  v  a 2s.  co  m
 */
@Override
public void afterPropertiesSet() throws Exception {
    Assert.state(m_graphResultsService != null, "graphResultsService property must be set to a non-null value");
}

From source file:org.openspaces.core.config.LocalTxManagerBeanDefinitionParser.java

protected void doParse(Element element, BeanDefinitionBuilder builder) {
    log.warn(//  www.j  a va  2  s  .  c o  m
            "Local transaction manager is deprecated, use distributed transaction manager instead ('distributed-tx-manager')");
    super.doParse(element, builder);
    NamedNodeMap attributes = element.getAttributes();
    for (int x = 0; x < attributes.getLength(); x++) {
        Attr attribute = (Attr) attributes.item(x);
        String name = attribute.getLocalName();
        if (ID_ATTRIBUTE.equals(name)) {
            continue;
        }
        String propertyName = extractPropertyName(name);
        if (SPACE.equals(name)) {
            continue;
        }
        if (CLUSTERED.equals(name)) {
            continue;
        }

        Assert.state(StringUtils.hasText(propertyName),
                "Illegal property name returned from 'extractPropertyName(String)': cannot be null or empty.");
        builder.addPropertyValue(propertyName, attribute.getValue());
    }
}

From source file:org.pentaho.platform.repository2.mt.RepositoryTenantManager.java

public Node createAuthzFolderNode(final Session session, final PentahoJcrConstants pentahoJcrConstants,
        final ITenant tenant) throws RepositoryException {
    Node tenantRootFolderNode = null;
    try {/*from   w  w w .ja v a  2 s  . co m*/
        tenantRootFolderNode = (Node) session.getItem(ServerRepositoryPaths.getTenantRootFolderPath(tenant));
    } catch (PathNotFoundException e) {
        Assert.state(false, Messages.getInstance()
                .getString("JcrRoleAuthorizationPolicyRoleBindingDao.ERROR_0002_REPO_NOT_INITIALIZED")); //$NON-NLS-1$
    }
    Node authzFolderNode = tenantRootFolderNode.addNode(FOLDER_NAME_AUTHZ,
            pentahoJcrConstants.getPHO_NT_INTERNALFOLDER());
    session.save();
    return authzFolderNode;
}

From source file:org.pentaho.platform.repository2.unified.jcr.JcrRepositoryFileUtils.java

private static void preventLostUpdate(final Session session, final PentahoJcrConstants pentahoJcrConstants,
        final RepositoryFile file) throws RepositoryException {
    Node fileNode = session.getNodeByIdentifier(file.getId().toString());
    // guard against using a file retrieved from a more lenient session inside a more strict session
    Assert.notNull(fileNode);//from   w w w .  j a v a 2 s . co  m
    if (isVersioned(session, pentahoJcrConstants, fileNode)) {
        Assert.notNull(file.getVersionId(), "updating a versioned file requires a non-null version id"); //$NON-NLS-1$
        Assert.state(
                session.getWorkspace().getVersionManager().getBaseVersion(fileNode.getPath()).getName()
                        .equals(file.getVersionId().toString()),
                "update to this file has occurred since its last read"); //$NON-NLS-1$
    }
}

From source file:org.shept.org.springframework.web.servlet.mvc.support.ConfigurableLocaleDependentFormatResolver.java

public void afterPropertiesSet() throws Exception {
    Assert.notEmpty(this.dateTimeLocales, "The dateTimeLocales definitions have not yet been initialized");
    Assert.state(this.dateTimeLocales.containsKey(this.defaultLocale),
            "The default locale '" + this.defaultLocale + "' is not properly configured");
}

From source file:org.springframework.amqp.rabbit.admin.RabbitBrokerAdmin.java

/**
 * Create an instance by supplying the erlang node name, port number and cookie (unique string). If the node name
 * does not contain an <code>@</code> character, it will be prepended with an alivename <code>rabbit@</code>
 * (interpreting the supplied value as just the hostname).
 *
 * @param nodeName the node name or hostname to use
 * @param port the port number (overriding the default which is 5672)
 * @param cookie the cookie value to use
 *//*  w ww  .  j  av a 2  s.  co  m*/
public RabbitBrokerAdmin(String nodeName, int port, String cookie) {

    if (!nodeName.contains("@")) {
        nodeName = "rabbit@" + nodeName; // it was just the host
    }

    String[] parts = nodeName.split("@");
    Assert.state(parts.length == 2, "The node name should be in the form alivename@host, e.g. rabbit@myserver");
    if (Os.isFamily("windows") && !DEFAULT_NODE_NAME.equals(nodeName)) {
        nodeName = parts[0] + "@" + parts[1].toUpperCase();
    }

    this.port = port;
    this.cookie = cookie;
    this.nodeName = nodeName;
    SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor();
    executor.setDaemon(true);
    this.executor = executor;

}

From source file:org.springframework.amqp.rabbit.admin.RabbitBrokerAdmin.java

@ManagedOperation
public void startNode() {

    RabbitStatus status = getStatus();//from w ww. ja  v  a 2 s .  co m
    if (status.isAlive()) {
        logger.info("Rabbit Process already running.");
        startBrokerApplication();
        return;
    }

    if (!status.isRunning() && status.isReady()) {
        logger.info("Rabbit Process not running but status is ready.  Restarting.");
        stopNode();
    }

    logger.info("Starting RabbitMQ node by shelling out command line.");
    final Execute execute = new Execute();

    String rabbitStartScript = null;
    String hint = "";
    if (Os.isFamily("windows") || Os.isFamily("dos")) {
        rabbitStartScript = "sbin/rabbitmq-server.bat";
    } else if (Os.isFamily("unix") || Os.isFamily("mac")) {
        rabbitStartScript = "bin/rabbitmq-server";
        hint = "Depending on your platform it might help to set RABBITMQ_LOG_BASE and RABBITMQ_MNESIA_BASE System properties to an empty directory.";
    }
    Assert.notNull(rabbitStartScript, "unsupported OS family");

    String rabbitHome = System.getProperty("RABBITMQ_HOME", System.getenv("RABBITMQ_HOME"));
    if (rabbitHome == null) {
        if (Os.isFamily("windows") || Os.isFamily("dos")) {
            rabbitHome = findDirectoryName("c:/Program Files", "rabbitmq");
        } else if (Os.isFamily("unix") || Os.isFamily("mac")) {
            rabbitHome = "/usr/lib/rabbitmq";
        }
    }
    Assert.notNull(rabbitHome, "RABBITMQ_HOME system property (or environment variable) not set.");

    rabbitHome = StringUtils.cleanPath(rabbitHome);
    String rabbitStartCommand = rabbitHome + "/" + rabbitStartScript;
    String[] commandline = new String[] { rabbitStartCommand };

    List<String> env = new ArrayList<String>();

    if (rabbitLogBaseDirectory != null) {
        env.add("RABBITMQ_LOG_BASE=" + rabbitLogBaseDirectory);
    } else {
        addEnvironment(env, "RABBITMQ_LOG_BASE");
    }
    if (rabbitMnesiaBaseDirectory != null) {
        env.add("RABBITMQ_MNESIA_BASE=" + rabbitMnesiaBaseDirectory);
    } else {
        addEnvironment(env, "RABBITMQ_MNESIA_BASE");
    }
    addEnvironment(env, "ERLANG_HOME");

    // Make the nodename explicitly the same so the erl process knows who we are
    env.add("RABBITMQ_NODENAME=" + nodeName);

    // Set the port number for the new process
    env.add("RABBITMQ_NODE_PORT=" + port);

    // Ask for a detached erl process so stdout doesn't get diverted to a black hole when the JVM dies (without this
    // you can start the Rabbit broker form Java but if you forget to stop it, the erl process is hosed).
    env.add("RABBITMQ_SERVER_ERL_ARGS=-detached");

    execute.setCommandline(commandline);
    execute.setEnvironment(env.toArray(new String[0]));

    final CountDownLatch running = new CountDownLatch(1);
    final AtomicBoolean finished = new AtomicBoolean(false);
    final String errorHint = hint;

    executor.execute(new Runnable() {
        public void run() {
            try {
                running.countDown();
                int exit = execute.execute();
                finished.set(true);
                logger.info("Finished broker launcher process with exit code=" + exit);
                if (exit != 0) {
                    throw new IllegalStateException("Could not start process." + errorHint);
                }
            } catch (Exception e) {
                logger.error("Failed to start node", e);
            }
        }
    });

    try {
        logger.info("Waiting for Rabbit process to be started");
        Assert.state(running.await(1000L, TimeUnit.MILLISECONDS),
                "Timed out waiting for thread to start Rabbit process.");
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }

    if (finished.get()) {
        // throw new
        // IllegalStateException("Expected broker process to start in background, but it has exited early.");
    }

    if (timeout > 0) {
        waitForReadyState();
    }

}

From source file:org.springframework.amqp.rabbit.admin.RabbitBrokerAdmin.java

/**
 * Convenience method for lazy initialization of the {@link ErlangTemplate} and associated trimmings. All RPC calls
 * should go through this method./*w w  w. ja va 2 s .  co m*/
 *
 * @param <T> the type of the result
 * @param module the module to address remotely
 * @param function the function to call
 * @param args the arguments to pass
 *
 * @return the result from the remote erl process converted to the correct type
 */
@SuppressWarnings("unchecked")
private <T> T executeAndConvertRpc(String module, String function, Object... args) {

    if (erlangTemplate == null) {
        synchronized (this) {
            if (erlangTemplate == null) {
                initializeDefaultErlangTemplate();
            }
        }
    }

    String key = module + "%" + function;
    if (moduleAdapter.containsKey(key)) {
        String adapter = moduleAdapter.get(key);
        String[] values = adapter.split("%");
        Assert.state(values.length == 2,
                "The module adapter should be a map from 'module%function' to 'module%function'. "
                        + "This one contained [" + adapter
                        + "] which cannot be parsed to a module, function pair.");
        module = values[0];
        function = values[1];
    }

    return (T) erlangTemplate.executeAndConvertRpc(module, function, args);

}

From source file:org.springframework.amqp.rabbit.admin.RabbitControlErlangConverter.java

protected void registerConverter(String module, String function, ErlangConverter listUsersConverter) {
    String key = generateKey(module, function);
    if (moduleAdapter.containsKey(key)) {
        String adapter = moduleAdapter.get(key);
        String[] values = adapter.split("%");
        Assert.state(values.length == 2,
                "The module adapter should be a map from 'module%function' to 'module%function'. "
                        + "This one contained [" + adapter
                        + "] which cannot be parsed to a module, function pair.");
        module = values[0];/*from www . j a va2s.c om*/
        function = values[1];
    }
    converterMap.put(generateKey(module, function), listUsersConverter);
}