Example usage for java.lang Math toIntExact

List of usage examples for java.lang Math toIntExact

Introduction

In this page you can find the example usage for java.lang Math toIntExact.

Prototype

public static int toIntExact(long value) 

Source Link

Document

Returns the value of the long argument; throwing an exception if the value overflows an int .

Usage

From source file:module.siadap.domain.wrappers.UnitSiadapWrapper.java

private int getTotalPeopleWithSiadapWorkingInUnit(Unit unit, boolean continueToSubUnit) {
    int year = getYear();

    long people = unit.getChildAccountabilityStream()
            .filter(a -> a.getAccountabilityType() == getConfiguration().getWorkingRelation()
                    && a.getChild().isPerson())
            .filter(a -> getConfiguration().getSiadapFor((Person) a.getChild(), year) != null).count();

    if (continueToSubUnit) {
        people += unit.getChildAccountabilityStream()
                .filter(a -> a.getAccountabilityType() == getConfiguration().getUnitRelations()
                        && a.getChild().isUnit())
                .count();//from  w  w w.  jav a  2 s.c o m
    }
    return Math.toIntExact(people);
}

From source file:ddf.catalog.source.solr.SolrMetacardClientImpl.java

private int queryForNumberOfRows(SolrQuery query) throws SolrServerException, IOException {
    int numRows;/*w w  w.java2s. c  o m*/
    query.setRows(0);
    QueryResponse solrResponse = client.query(query, METHOD.POST);
    numRows = Math.toIntExact(solrResponse.getResults().getNumFound());
    return numRows;
}

From source file:io.stallion.settings.Settings.java

protected List convertMapListToObjects(List maps, Class targetClass) {
    if (maps.size() == 0) {
        return maps;
    }/*w ww  .  j ava2  s.c o m*/
    if (targetClass.isAssignableFrom(maps.get(0).getClass())) {
        return maps;
    }
    List items = new ArrayList<>();
    for (Object o : maps) {
        Map<String, Object> map = (Map<String, Object>) o;
        try {
            Object instance = targetClass.newInstance();
            for (Map.Entry<String, Object> e : map.entrySet()) {
                Object value = e.getValue();
                if (e.getKey().equals("basePort") && e.getValue() instanceof Long) {
                    value = Math.toIntExact((Long) value);
                }
                PropertyUtils.setProperty(instance, e.getKey(), value);
            }
            items.add(instance);

        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
    return items;
}

From source file:org.hobbit.storage.queries.SparqlQueries.java

/**
 * Generates one or several SPARQL UPDATE queries based on the differences
 * between the two given models. Triples that are present in the original model
 * but not in the updated model will be put into the DELETE part of the query.
 * Triples that are present in the updated model but can not be found in the
 * original model will be put into the INSERT part of the query. The changes
 * will be carried out using multiple queries if a single query would hit the
 * given maximum number of triples per query.
 *
 * @param original//from   w  w  w.  j  a  v  a 2  s.c om
 *            the original RDF model ({@code null} is interpreted as an empty
 *            model)
 * @param updated
 *            the updated RDF model ({@code null} is interpreted as an empty
 *            model)
 * @param graphUri
 *            the URI of the graph to which the UPDATE query should be applied
 *            or <code>null</code>
 * @param maxTriplesPerQuery
 *            the maximum number of triples a single query should contain
 * @return The SPARQL UPDATE query
 */
public static final String[] getUpdateQueriesFromDiff(Model original, Model updated, String graphUri,
        int maxTriplesPerQuery) {
    if (original == null) {
        original = EMPTY_MODEL;
    }
    if (updated == null) {
        updated = EMPTY_MODEL;
    }
    List<Statement> deleted = original.difference(updated).listStatements().toList();
    List<Statement> inserted = updated.difference(original).listStatements().toList();

    int numberOfDelStmts = deleted.size();
    int totalSize = Math.toIntExact(numberOfDelStmts + inserted.size());
    int queries = (totalSize / maxTriplesPerQuery) + 1;
    String[] results = new String[queries];
    int startIndex = 0;
    int endIndex = Math.min(maxTriplesPerQuery, totalSize);
    List<Statement> delStatements, addStatements;
    List<Statement> emptyList = new ArrayList<>(0);
    for (int i = 0; i < queries; i++) {
        // If we can fill the next query with deleted statements
        if (endIndex < numberOfDelStmts) {
            delStatements = deleted.subList(startIndex, endIndex);
            addStatements = emptyList;
        } else {
            if (startIndex < numberOfDelStmts) {
                delStatements = deleted.subList(startIndex, numberOfDelStmts);
                addStatements = inserted.subList(0, endIndex - numberOfDelStmts);
            } else {
                delStatements = emptyList;
                addStatements = inserted.subList(startIndex - numberOfDelStmts, endIndex - numberOfDelStmts);
            }
        }
        String query = getUpdateQueryFromStatements(delStatements, addStatements,
                original.size() > updated.size() ? original : updated, graphUri);
        results[i] = query;
        // get the indexes of the next query
        startIndex = endIndex;
        endIndex = Math.min(endIndex + maxTriplesPerQuery, totalSize);
    }

    return results;
}

From source file:org.ballerinalang.net.http.HttpUtil.java

private static int validateConfig(long value, String configName) {
    try {/*from w ww .  ja  va  2s  .  com*/
        return Math.toIntExact(value);
    } catch (ArithmeticException e) {
        log.warn("The value set for the configuration needs to be less than {}. The " + configName
                + "value is set to {}", Integer.MAX_VALUE);
        return Integer.MAX_VALUE;
    }
}

From source file:org.ballerinalang.net.http.HttpUtil.java

/**
 * Returns Listener configuration instance populated with endpoint config.
 *
 * @param port              listener port.
 * @param endpointConfig    listener endpoint configuration.
 * @return                  transport listener configuration instance.
 *///from   w w  w  .  j a  va 2 s .  com
public static ListenerConfiguration getListenerConfig(long port, Struct endpointConfig) {
    String host = endpointConfig.getStringField(HttpConstants.ENDPOINT_CONFIG_HOST);
    String keepAlive = endpointConfig.getRefField(HttpConstants.ENDPOINT_CONFIG_KEEP_ALIVE).getStringValue();
    Struct sslConfig = endpointConfig.getStructField(HttpConstants.ENDPOINT_CONFIG_SECURE_SOCKET);
    String httpVersion = endpointConfig.getStringField(HttpConstants.ENDPOINT_CONFIG_VERSION);
    Struct requestLimits = endpointConfig.getStructField(HttpConstants.ENDPOINT_REQUEST_LIMITS);
    long idleTimeout = endpointConfig.getIntField(HttpConstants.ENDPOINT_CONFIG_TIMEOUT);

    ListenerConfiguration listenerConfiguration = new ListenerConfiguration();

    if (host == null || host.trim().isEmpty()) {
        listenerConfiguration.setHost(ConfigRegistry.getInstance().getConfigOrDefault("b7a.http.host",
                HttpConstants.HTTP_DEFAULT_HOST));
    } else {
        listenerConfiguration.setHost(host);
    }

    if (port == 0) {
        throw new BallerinaConnectorException("Listener port is not defined!");
    }
    listenerConfiguration.setPort(Math.toIntExact(port));

    listenerConfiguration.setKeepAliveConfig(HttpUtil.getKeepAliveConfig(keepAlive));

    // Set Request validation limits.
    if (requestLimits != null) {
        setRequestSizeValidationConfig(requestLimits, listenerConfiguration);
    }

    if (idleTimeout < 0) {
        throw new BallerinaConnectorException(
                "Idle timeout cannot be negative. If you want to disable the " + "timeout please use value 0");
    }
    listenerConfiguration.setSocketIdleTimeout(Math.toIntExact(idleTimeout));

    // Set HTTP version
    if (httpVersion != null) {
        listenerConfiguration.setVersion(httpVersion);
    }

    listenerConfiguration.setServerHeader(getServerName());

    if (sslConfig != null) {
        return setSslConfig(sslConfig, listenerConfiguration);
    }

    listenerConfiguration.setPipeliningEnabled(true); //Pipelining is enabled all the time
    listenerConfiguration
            .setPipeliningLimit(endpointConfig.getIntField(HttpConstants.PIPELINING_REQUEST_LIMIT));

    return listenerConfiguration;
}

From source file:org.ballerinalang.net.http.HttpUtil.java

private static void setRequestSizeValidationConfig(Struct requestLimits,
        ListenerConfiguration listenerConfiguration) {
    long maxUriLength = requestLimits.getIntField(HttpConstants.REQUEST_LIMITS_MAXIMUM_URL_LENGTH);
    long maxHeaderSize = requestLimits.getIntField(HttpConstants.REQUEST_LIMITS_MAXIMUM_HEADER_SIZE);
    long maxEntityBodySize = requestLimits.getIntField(HttpConstants.REQUEST_LIMITS_MAXIMUM_ENTITY_BODY_SIZE);
    RequestSizeValidationConfig requestSizeValidationConfig = listenerConfiguration
            .getRequestSizeValidationConfig();

    if (maxUriLength != -1) {
        if (maxUriLength >= 0) {
            requestSizeValidationConfig.setMaxUriLength(Math.toIntExact(maxUriLength));
        } else {/*from w  w w. ja va 2 s  . c o m*/
            throw new BallerinaConnectorException(
                    "Invalid configuration found for maxUriLength : " + maxUriLength);
        }
    }

    if (maxHeaderSize != -1) {
        if (maxHeaderSize >= 0) {
            requestSizeValidationConfig.setMaxHeaderSize(Math.toIntExact(maxHeaderSize));
        } else {
            throw new BallerinaConnectorException(
                    "Invalid configuration found for maxHeaderSize : " + maxHeaderSize);
        }
    }

    if (maxEntityBodySize != -1) {
        if (maxEntityBodySize >= 0) {
            requestSizeValidationConfig.setMaxEntityBodySize(maxEntityBodySize);
        } else {
            throw new BallerinaConnectorException(
                    "Invalid configuration found for maxEntityBodySize : " + maxEntityBodySize);
        }
    }
}

From source file:org.ballerinalang.net.http.HttpUtil.java

private static ListenerConfiguration setSslConfig(Struct sslConfig,
        ListenerConfiguration listenerConfiguration) {
    listenerConfiguration.setScheme(PROTOCOL_HTTPS);
    Struct trustStore = sslConfig.getStructField(ENDPOINT_CONFIG_TRUST_STORE);
    Struct keyStore = sslConfig.getStructField(ENDPOINT_CONFIG_KEY_STORE);
    Struct protocols = sslConfig.getStructField(ENDPOINT_CONFIG_PROTOCOLS);
    Struct validateCert = sslConfig.getStructField(ENDPOINT_CONFIG_VALIDATE_CERT);
    Struct ocspStapling = sslConfig.getStructField(ENDPOINT_CONFIG_OCSP_STAPLING);
    String keyFile = sslConfig.getStringField(ENDPOINT_CONFIG_KEY);
    String certFile = sslConfig.getStringField(ENDPOINT_CONFIG_CERTIFICATE);
    String trustCerts = sslConfig.getStringField(ENDPOINT_CONFIG_TRUST_CERTIFICATES);
    String keyPassword = sslConfig.getStringField(ENDPOINT_CONFIG_KEY_PASSWORD);

    if (keyStore != null && StringUtils.isNotBlank(keyFile)) {
        throw new BallerinaException("Cannot configure both keyStore and keyFile at the same time.");
    } else if (keyStore == null && (StringUtils.isBlank(keyFile) || StringUtils.isBlank(certFile))) {
        throw new BallerinaException(
                "Either keystore or certificateKey and server certificates must be provided "
                        + "for secure connection");
    }//from ww w . ja  v a  2  s  .c o  m
    if (keyStore != null) {
        String keyStoreFile = keyStore.getStringField(FILE_PATH);
        if (StringUtils.isBlank(keyStoreFile)) {
            throw new BallerinaException("Keystore file location must be provided for secure connection.");
        }
        String keyStorePassword = keyStore.getStringField(PASSWORD);
        if (StringUtils.isBlank(keyStorePassword)) {
            throw new BallerinaException("Keystore password must be provided for secure connection");
        }
        listenerConfiguration.setKeyStoreFile(keyStoreFile);
        listenerConfiguration.setKeyStorePass(keyStorePassword);
    } else {
        listenerConfiguration.setServerKeyFile(keyFile);
        listenerConfiguration.setServerCertificates(certFile);
        if (StringUtils.isNotBlank(keyPassword)) {
            listenerConfiguration.setServerKeyPassword(keyPassword);
        }
    }
    String sslVerifyClient = sslConfig.getStringField(SSL_CONFIG_SSL_VERIFY_CLIENT);
    listenerConfiguration.setVerifyClient(sslVerifyClient);
    listenerConfiguration
            .setSslSessionTimeOut((int) sslConfig.getDefaultableIntField(ENDPOINT_CONFIG_SESSION_TIMEOUT));
    listenerConfiguration
            .setSslHandshakeTimeOut(sslConfig.getDefaultableIntField(ENDPOINT_CONFIG_HANDSHAKE_TIMEOUT));
    if (trustStore == null && StringUtils.isNotBlank(sslVerifyClient) && StringUtils.isBlank(trustCerts)) {
        throw new BallerinaException(
                "Truststore location or trustCertificates must be provided to enable Mutual SSL");
    }
    if (trustStore != null) {
        String trustStoreFile = trustStore.getStringField(FILE_PATH);
        String trustStorePassword = trustStore.getStringField(PASSWORD);
        if (StringUtils.isBlank(trustStoreFile) && StringUtils.isNotBlank(sslVerifyClient)) {
            throw new BallerinaException("Truststore location must be provided to enable Mutual SSL");
        }
        if (StringUtils.isBlank(trustStorePassword) && StringUtils.isNotBlank(sslVerifyClient)) {
            throw new BallerinaException("Truststore password value must be provided to enable Mutual SSL");
        }
        listenerConfiguration.setTrustStoreFile(trustStoreFile);
        listenerConfiguration.setTrustStorePass(trustStorePassword);
    } else if (StringUtils.isNotBlank(trustCerts)) {
        listenerConfiguration.setServerTrustCertificates(trustCerts);
    }
    List<Parameter> serverParamList = new ArrayList<>();
    Parameter serverParameters;
    if (protocols != null) {
        List<Value> sslEnabledProtocolsValueList = Arrays.asList(protocols.getArrayField(ENABLED_PROTOCOLS));
        if (!sslEnabledProtocolsValueList.isEmpty()) {
            String sslEnabledProtocols = sslEnabledProtocolsValueList.stream().map(Value::getStringValue)
                    .collect(Collectors.joining(",", "", ""));
            serverParameters = new Parameter(ANN_CONFIG_ATTR_SSL_ENABLED_PROTOCOLS, sslEnabledProtocols);
            serverParamList.add(serverParameters);
        }

        String sslProtocol = protocols.getStringField(PROTOCOL_VERSION);
        if (StringUtils.isNotBlank(sslProtocol)) {
            listenerConfiguration.setSSLProtocol(sslProtocol);
        }
    }

    List<Value> ciphersValueList = Arrays.asList(sslConfig.getArrayField(HttpConstants.SSL_CONFIG_CIPHERS));
    if (!ciphersValueList.isEmpty()) {
        String ciphers = ciphersValueList.stream().map(Value::getStringValue)
                .collect(Collectors.joining(",", "", ""));
        serverParameters = new Parameter(HttpConstants.CIPHERS, ciphers);
        serverParamList.add(serverParameters);
    }
    if (validateCert != null) {
        boolean validateCertificateEnabled = validateCert.getBooleanField(HttpConstants.ENABLE);
        long cacheSize = validateCert.getIntField(HttpConstants.SSL_CONFIG_CACHE_SIZE);
        long cacheValidationPeriod = validateCert.getIntField(HttpConstants.SSL_CONFIG_CACHE_VALIDITY_PERIOD);
        listenerConfiguration.setValidateCertEnabled(validateCertificateEnabled);
        if (validateCertificateEnabled) {
            if (cacheSize != 0) {
                listenerConfiguration.setCacheSize(Math.toIntExact(cacheSize));
            }
            if (cacheValidationPeriod != 0) {
                listenerConfiguration.setCacheValidityPeriod(Math.toIntExact(cacheValidationPeriod));
            }
        }
    }
    if (ocspStapling != null) {
        boolean ocspStaplingEnabled = ocspStapling.getBooleanField(HttpConstants.ENABLE);
        listenerConfiguration.setOcspStaplingEnabled(ocspStaplingEnabled);
        long cacheSize = ocspStapling.getIntField(HttpConstants.SSL_CONFIG_CACHE_SIZE);
        long cacheValidationPeriod = ocspStapling.getIntField(HttpConstants.SSL_CONFIG_CACHE_VALIDITY_PERIOD);
        listenerConfiguration.setValidateCertEnabled(ocspStaplingEnabled);
        if (ocspStaplingEnabled) {
            if (cacheSize != 0) {
                listenerConfiguration.setCacheSize(Math.toIntExact(cacheSize));
            }
            if (cacheValidationPeriod != 0) {
                listenerConfiguration.setCacheValidityPeriod(Math.toIntExact(cacheValidationPeriod));
            }
        }
    }
    listenerConfiguration.setTLSStoreType(PKCS_STORE_TYPE);
    String serverEnableSessionCreation = String
            .valueOf(sslConfig.getBooleanField(SSL_CONFIG_ENABLE_SESSION_CREATION));
    Parameter enableSessionCreationParam = new Parameter(SSL_CONFIG_ENABLE_SESSION_CREATION,
            serverEnableSessionCreation);
    serverParamList.add(enableSessionCreationParam);
    if (!serverParamList.isEmpty()) {
        listenerConfiguration.setParameters(serverParamList);
    }

    listenerConfiguration.setId(
            HttpUtil.getListenerInterface(listenerConfiguration.getHost(), listenerConfiguration.getPort()));

    return listenerConfiguration;
}