Example usage for org.springframework.util Assert hasLength

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

Introduction

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

Prototype

public static void hasLength(@Nullable String text, Supplier<String> messageSupplier) 

Source Link

Document

Assert that the given String is not empty; that is, it must not be null and not the empty String.

Usage

From source file:org.springframework.social.linkedin.api.impl.LinkedInTemplate.java

/**
 * Creates a new LinkedInTemplate given the minimal amount of information needed to sign requests with OAuth 1 credentials.
 * @param accessToken an access token acquired through OAuth authentication with LinkedIn
 *//*from  w  w w .  j  av a  2s .c  o m*/
public LinkedInTemplate(String accessToken) {
    super(accessToken);
    Assert.hasLength(accessToken, "Access token cannot be null or empty.");
    registerOAuth2Interceptor(accessToken);
    registerLinkedInJsonModule();
    registerJsonFormatInterceptor();
    initSubApis();
}

From source file:org.springframework.util.ClassUtils.java

/**
 * Get the class name without the qualified package name.
 * @param className the className to get the short name for
 * @return the class name of the class without the package name
 * @throws IllegalArgumentException if the className is empty
 *///from w  w w .j  a va  2s .  c  o  m
public static String getShortName(String className) {
    Assert.hasLength(className, "Class name must not be empty");
    int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR);
    int nameEndIndex = className.indexOf(CGLIB_CLASS_SEPARATOR);
    if (nameEndIndex == -1) {
        nameEndIndex = className.length();
    }
    String shortName = className.substring(lastDotIndex + 1, nameEndIndex);
    shortName = shortName.replace(INNER_CLASS_SEPARATOR, PACKAGE_SEPARATOR);
    return shortName;
}

From source file:org.springframework.web.reactive.function.server.RouterFunctions.java

/**
 * Route requests that match the given pattern to resources relative to the given root location.
 * For instance/*w  w w  .j av a2 s .  com*/
 * <pre class="code">
 * Resource location = new FileSystemResource("public-resources/");
 * RoutingFunction&lt;ServerResponse&gt; resources = RouterFunctions.resources("/resources/**", location);
  * </pre>
 * @param pattern the pattern to match
 * @param location the location directory relative to which resources should be resolved
 * @return a router function that routes to resources
 */
public static RouterFunction<ServerResponse> resources(String pattern, Resource location) {
    Assert.hasLength(pattern, "'pattern' must not be empty");
    Assert.notNull(location, "'location' must not be null");
    return resources(new PathResourceLookupFunction(pattern, location));
}

From source file:org.springframework.ws.client.core.WebServiceTemplate.java

public <T> T sendAndReceive(String uriString, WebServiceMessageCallback requestCallback,
        WebServiceMessageExtractor<T> responseExtractor) {
    Assert.notNull(responseExtractor, "'responseExtractor' must not be null");
    Assert.hasLength(uriString, "'uri' must not be empty");
    TransportContext previousTransportContext = TransportContextHolder.getTransportContext();
    WebServiceConnection connection = null;
    try {/*  w w w.  j  a  va  2  s .  c o m*/
        connection = createConnection(URI.create(uriString));
        TransportContextHolder.setTransportContext(new DefaultTransportContext(connection));
        MessageContext messageContext = new DefaultMessageContext(getMessageFactory());

        return doSendAndReceive(messageContext, connection, requestCallback, responseExtractor);
    } catch (TransportException ex) {
        throw new WebServiceTransportException("Could not use transport: " + ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new WebServiceIOException("I/O error: " + ex.getMessage(), ex);
    } finally {
        TransportUtils.closeConnection(connection);
        TransportContextHolder.setTransportContext(previousTransportContext);
    }
}

From source file:org.springframework.ws.samples.airline.service.impl.AirlineServiceImpl.java

@Transactional(readOnly = false, rollbackFor = { NoSuchFlightException.class, NoSeatAvailableException.class,
        NoSuchFrequentFlyerException.class })
public Ticket bookFlight(String flightNumber, DateTime departureTime, List<Passenger> passengers)
        throws NoSuchFlightException, NoSeatAvailableException, NoSuchFrequentFlyerException {
    Assert.notEmpty(passengers, "No passengers given");
    if (logger.isDebugEnabled()) {
        logger.debug("Booking flight '" + flightNumber + "' on '" + departureTime + "' for " + passengers);
    }/* w w  w. j a  v a  2 s  . com*/
    Flight flight = flightDao.getFlight(flightNumber, departureTime);
    if (flight == null) {
        throw new NoSuchFlightException(flightNumber, departureTime);
    } else if (flight.getSeatsAvailable() < passengers.size()) {
        throw new NoSeatAvailableException(flight);
    }
    Ticket ticket = new Ticket();
    ticket.setIssueDate(new LocalDate());
    ticket.setFlight(flight);
    for (Passenger passenger : passengers) {
        // frequent flyer service is not required
        if (passenger instanceof FrequentFlyer && frequentFlyerSecurityService != null) {
            String username = ((FrequentFlyer) passenger).getUsername();
            Assert.hasLength(username, "No username specified");
            FrequentFlyer frequentFlyer = frequentFlyerSecurityService.getFrequentFlyer(username);
            frequentFlyer.addMiles(flight.getMiles());
            ticket.addPassenger(frequentFlyer);
        } else {
            ticket.addPassenger(passenger);
        }
    }
    flight.substractSeats(passengers.size());
    flightDao.update(flight);
    ticketDao.save(ticket);
    return ticket;
}

From source file:org.springframework.ws.transport.mail.MailSenderConnection.java

@Override
protected void onReceiveBeforeRead() throws IOException {
    try {/*from w w w  .  j  av a2  s.c  om*/
        String requestMessageId = requestMessage.getMessageID();
        Assert.hasLength(requestMessageId, "No Message-ID found on request message [" + requestMessage + "]");
        try {
            Thread.sleep(receiveTimeout);
        } catch (InterruptedException e) {
            // Re-interrupt current thread, to allow other threads to react.
            Thread.currentThread().interrupt();
        }
        openFolder();
        SearchTerm searchTerm = new HeaderTerm(MailTransportConstants.HEADER_IN_REPLY_TO, requestMessageId);
        Message[] responses = folder.search(searchTerm);
        if (responses.length > 0) {
            if (responses.length > 1) {
                logger.warn("Received more than one response for request with ID [" + requestMessageId + "]");
            }
            responseMessage = responses[0];
        }
        if (deleteAfterReceive) {
            responseMessage.setFlag(Flags.Flag.DELETED, true);
        }
    } catch (MessagingException ex) {
        throw new MailTransportException(ex);
    }
}

From source file:org.springframework.xd.extension.process.ShellCommandProcessor.java

/**
 * Creates a process to invoke a shell command to send and receive messages from the processes using the process's stdin and stdout.
 *
 * @param serializer an {@link org.springframework.integration.ip.tcp.serializer.AbstractByteArraySerializer} to delimit messages
 * @param command the shell command with command line arguments as separate strings
 *///from  w  ww. j av  a  2 s.  c o m
public ShellCommandProcessor(AbstractByteArraySerializer serializer, String command) {
    Assert.hasLength(command, "A shell command is required");
    Assert.notNull(serializer, "'serializer' cannot be null");
    this.command = command;
    List<String> commandPlusArgs = parse(command);
    Assert.notEmpty(commandPlusArgs, "The shell command is invalid: '" + command + "'");
    this.serializer = serializer;
    processBuilder = new ProcessBuilder(commandPlusArgs);
}

From source file:org.springframework.xml.validation.XmlValidatorFactory.java

/**
 * Create a {@link XmlValidator} with the given schema resources and schema language type. The schema language must
 * be one of the <code>SCHEMA_XXX</code> constants.
 *
 * @param schemaResources an array of resource that locate the schemas to validate against
 * @param schemaLanguage  the language of the schemas
 * @return a validator/*from w w w. j  a va  2  s.c o  m*/
 * @throws IOException              if the schema resource cannot be read
 * @throws IllegalArgumentException if the schema language is not supported
 * @throws IllegalStateException    if JAXP 1.0 cannot be located
 * @throws XmlValidationException   if a <code>XmlValidator</code> cannot be created
 * @see #SCHEMA_RELAX_NG
 * @see #SCHEMA_W3C_XML
 */
public static XmlValidator createValidator(Resource[] schemaResources, String schemaLanguage)
        throws IOException {
    Assert.notEmpty(schemaResources, "No resources given");
    Assert.hasLength(schemaLanguage, "No schema language provided");
    Assert.isTrue(SCHEMA_W3C_XML.equals(schemaLanguage) || SCHEMA_RELAX_NG.equals(schemaLanguage),
            "Invalid schema language: " + schemaLanguage);
    for (Resource schemaResource : schemaResources) {
        Assert.isTrue(schemaResource.exists(), "schema [" + schemaResource + "] does not exist");
    }
    if (JaxpVersion.getJaxpVersion() >= JaxpVersion.JAXP_13) {
        logger.trace("Creating JAXP 1.3 XmlValidator");
        return Jaxp13ValidatorFactory.createValidator(schemaResources, schemaLanguage);
    } else {
        throw new IllegalStateException("Could not locate JAXP 1.3.");
    }
}

From source file:org.springframework.xml.xpath.XPathExpressionFactory.java

/**
 * Create a compiled XPath expression using the given string and namespaces. The namespace map should consist of
 * string prefixes mapped to string namespaces.
 *
 * @param expression the XPath expression
 * @param namespaces a map that binds string prefixes to string namespaces
 * @return the compiled XPath expression
 * @throws IllegalStateException if neither JAXP 1.3+, or Jaxen are available
 * @throws XPathParseException   if the given expression cannot be parsed
 *///from  ww w .  ja va  2s .co  m
public static XPathExpression createXPathExpression(String expression, Map<String, String> namespaces)
        throws IllegalStateException, XPathParseException {
    Assert.hasLength(expression, "expression is empty");
    if (namespaces == null) {
        namespaces = Collections.emptyMap();
    }
    try {
        logger.trace("Creating [javax.xml.xpath.XPathExpression]");
        return Jaxp13XPathExpressionFactory.createXPathExpression(expression, namespaces);
    } catch (XPathException e) {
        throw e;
    }
}

From source file:org.thingsboard.server.service.cluster.discovery.ZkDiscoveryService.java

@PostConstruct
public void init() {
    log.info("Initializing...");
    Assert.hasLength(zkUrl, MiscUtils.missingProperty("zk.url"));
    Assert.notNull(zkRetryInterval, MiscUtils.missingProperty("zk.retry_interval_ms"));
    Assert.notNull(zkConnectionTimeout, MiscUtils.missingProperty("zk.connection_timeout_ms"));
    Assert.notNull(zkSessionTimeout, MiscUtils.missingProperty("zk.session_timeout_ms"));

    log.info("Initializing discovery service using ZK connect string: {}", zkUrl);

    zkNodesDir = zkDir + "/nodes";
    try {// ww  w  .j  a  v a  2  s . co  m
        client = CuratorFrameworkFactory.newClient(zkUrl, zkSessionTimeout, zkConnectionTimeout,
                new RetryForever(zkRetryInterval));
        client.start();
        client.blockUntilConnected();
        cache = new PathChildrenCache(client, zkNodesDir, true);
        cache.getListenable().addListener(this);
        cache.start();
    } catch (Exception e) {
        log.error("Failed to connect to ZK: {}", e.getMessage(), e);
        CloseableUtils.closeQuietly(cache);
        CloseableUtils.closeQuietly(client);
        throw new RuntimeException(e);
    }
}