List of usage examples for java.lang Math toIntExact
public static int toIntExact(long value)
From source file:org.apache.beam.sdk.extensions.sql.impl.udf.BuiltinStringFunctions.java
@UDF(funcName = "LPAD", parameterArray = { TypeName.STRING, TypeName.INT64, TypeName.STRING }, returnType = TypeName.STRING) public String lpad(String originalValue, Long returnLength, String pattern) { if (originalValue == null || returnLength == null || pattern == null) { return null; }/*from w w w . j av a2s . com*/ if (returnLength < -1 || pattern.isEmpty()) { throw new IllegalArgumentException("returnLength cannot be 0 or pattern cannot be empty."); } if (originalValue.length() == returnLength) { return originalValue; } else if (originalValue.length() < returnLength) { // add padding to left return StringUtils.leftPad(originalValue, Math.toIntExact(returnLength), pattern); } else { // truncating string by str.substring // Java String can only hold a string with Integer.MAX_VALUE as longest length. return originalValue.substring(0, Math.toIntExact(returnLength)); } }
From source file:org.ballerinalang.net.http.serviceendpoint.InitEndpoint.java
private ListenerConfiguration getListenerConfig(Struct endpointConfig) { String host = endpointConfig.getStringField(HttpConstants.ENDPOINT_CONFIG_HOST); long port = endpointConfig.getIntField(HttpConstants.ENDPOINT_CONFIG_PORT); 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/*from w w w. j av a 2 s . c o m*/ .setHost(configRegistry.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); } if (sslConfig != null) { return setSslConfig(sslConfig, listenerConfiguration); } listenerConfiguration.setServerHeader(getServerName()); return listenerConfiguration; }
From source file:org.cgiar.ccafs.marlo.action.center.json.monitoring.project.SuggestedProjectsAction.java
@Override public String execute() throws Exception { this.suggestedProjects = new ArrayList<>(); switch (Math.toIntExact(syncTypeID)) { case 1:/*from w w w .j a va 2s .c o m*/ this.crpSuggestions(); break; case 2: this.ocsSuggestions(); break; } return SUCCESS; }
From source file:com.atypon.wayf.verticle.routing.UserRouting.java
public Single<AuthorizationToken> login(RoutingContext routingContext) { return RequestReader.readRequestBody(routingContext, PasswordCredentials.class) .flatMap((credentials) -> passwordCredentialsFacade.generateSessionToken(credentials)) .map((authorizationToken) -> { Cookie cookie = new CookieImpl("adminToken", authorizationToken.getValue()) .setDomain(wayfDomain) .setMaxAge(Math.toIntExact(authorizationToken.getValidUntil().getTime() / 1000L)) .setPath("/"); routingContext.addCookie(cookie); return authorizationToken; });//from w ww. j av a 2s.c o m }
From source file:org.openlmis.fulfillment.domain.ProofOfDeliveryLineItem.java
/** * Validate if this line item has correct values. The following validations will be done: * <ul>/* w w w.j av a2 s . c o m*/ * <li><strong>quantityAccepted</strong> - must be zero or greater than zero</li> * <li><strong>quantityRejected</strong> - must be zero or greater than zero</li> * <li>if <strong>quantityAccepted</strong> is greater than zero and <strong>useVvm</strong> flag * is set, the <strong>vvmStatus</strong> must be less or equal to two</li> * <li>if <strong>quantityRejected</strong> is greater than zero, reason id must be provided</li> * <li>sum of <strong>quantityAccepted</strong> and <strong>quantityRejected</strong> must be * equals to <strong>quantityShipped</strong></li> * </ul> * * @param quantityShipped this value should be from related shipment line item. * @throws ValidationException if any validation does not match. */ void validate(Long quantityShipped) { Validations.throwIfLessThanZeroOrNull(quantityAccepted, "quantityAccepted"); Validations.throwIfLessThanZeroOrNull(quantityRejected, "quantityRejected"); if (quantityAccepted > 0 && useVvm && (null == vvmStatus || vvmStatus.isGreaterThan(2))) { throw new ValidationException(ERROR_INCORRECT_VVM_STATUS); } if (quantityRejected > 0 && null == rejectionReasonId) { throw new ValidationException(ERROR_MISSING_REASON); } if (quantityAccepted + quantityRejected != Math.toIntExact(quantityShipped)) { throw new ValidationException(ERROR_INCORRECT_QUANTITIES); } }
From source file:net.longfalcon.web.SearchController.java
@RequestMapping("/search/{searchToken}") public String searchView(@PathVariable("searchToken") String search, @RequestParam(value = "t", required = false) String categories, @RequestParam(value = "g", required = false) String groupName, @RequestParam(value = "offset", required = false, defaultValue = "0") Integer offset, @RequestParam(value = "ob", required = false) String orderBy, Model model) throws NoSuchResourceException { List<Integer> categoryIds = new ArrayList<>(); if (ValidatorUtil.isNotNull(categories)) { String[] categoryIdStrings = categories.split(","); for (String categoryIdString : categoryIdStrings) { try { int categoryId = Integer.parseInt(categoryIdString); Category category = categoryService.getCategory(categoryId); if (category != null) { categoryIds.add(categoryId); } else { throw new NoSuchResourceException(); }//from w w w . ja v a 2s . c om } catch (NumberFormatException nfe) { _log.warn(categoryIdString + " is not a number " + nfe.toString()); } } } long groupId = -1; if (ValidatorUtil.isNotNull(groupName)) { Group group = groupDAO.getGroupByName(groupName); if (group != null) { groupId = group.getId(); } } User user = userDAO.findByUserId(getUserId()); if (user != null) { model.addAttribute("lastVisit", user.getLastLogin()); } List<Integer> userExCats = userExCatDAO.getUserExCatIds(getUserId()); List<Release> releaseList = new ArrayList<>(); int pagerTotalItems = 0; if (ValidatorUtil.isNotNull(search)) { pagerTotalItems = Math .toIntExact(searchService.getSearchCount(search, categoryIds, -1, userExCats, groupId)); if (ValidatorUtil.isNull(orderBy)) { releaseList = searchService.getSearchReleases(search, categoryIds, -1, userExCats, groupId, "postDate", true, offset, PAGE_SIZE); } else { String propertyName = getOrderByProperty(orderBy); boolean descending = getOrderByOrder(orderBy); if (ValidatorUtil.isNotNull(propertyName)) { releaseList = searchService.getSearchReleases(search, categoryIds, -1, userExCats, groupId, propertyName, descending, offset, PAGE_SIZE); } } } model.addAttribute("search", search); model.addAttribute("searchCategories", categories); model.addAttribute("groupName", groupName); model.addAttribute("releaseList", releaseList); model.addAttribute("pagerTotalItems", pagerTotalItems); model.addAttribute("pagerOffset", offset); model.addAttribute("pagerItemsPerPage", PAGE_SIZE); model.addAttribute("orderBy", orderBy); model.addAttribute("now", new Date()); return "search"; }
From source file:org.apache.beam.sdk.extensions.sql.impl.udf.BuiltinStringFunctions.java
@UDF(funcName = "LPAD", parameterArray = { TypeName.BYTES, TypeName.INT64, TypeName.BYTES }, returnType = TypeName.BYTES) public byte[] lpad(byte[] originalValue, Long returnLength, byte[] pattern) { if (originalValue == null || returnLength == null || pattern == null) { return null; }/*from w ww. ja va 2s . com*/ if (returnLength < -1 || pattern.length == 0) { throw new IllegalArgumentException("returnLength cannot be 0 or pattern cannot be empty."); } int returnLengthInt = Math.toIntExact(returnLength); if (originalValue.length == returnLengthInt) { return originalValue; } else if (originalValue.length < returnLengthInt) { // add padding to left byte[] ret = new byte[returnLengthInt]; // step one: pad #(returnLengthInt - originalValue.length) bytes to left side. int paddingOff = 0; int paddingLeftBytes = returnLengthInt - originalValue.length; byteArrayPadding(ret, pattern, paddingOff, paddingLeftBytes); // step two: copy originalValue. System.arraycopy(originalValue, 0, ret, returnLengthInt - originalValue.length, originalValue.length); return ret; } else { // truncating string by str.substring // Java String can only hold a string with Integer.MAX_VALUE as longest length. byte[] ret = new byte[returnLengthInt]; System.arraycopy(originalValue, 0, ret, 0, returnLengthInt); return ret; } }
From source file:io.logspace.hq.core.solr.report.SolrReportService.java
@Override public Reports getReports(int start, int count, String sort) { this.logger.debug("Retrieving {} reports from {}, sorted by '{}'.", count, start, sort); SolrQuery solrQuery = new SolrQuery("*:*"); solrQuery.addFilterQuery(FILTER_REPORT); solrQuery.addFilterQuery(FILTER_UNDELETED); solrQuery.addFilterQuery(FILTER_TIP_OF_BRANCH); SolrQueryHelper.addSort(solrQuery, sort, this.getFieldDefinitions()); SolrQueryHelper.setRange(solrQuery, start, count); try {//from w ww .j a v a 2 s . c om List<Report> reports = new ArrayList<>(); QueryResponse queryResponse = this.solrClient.query(solrQuery); SolrDocumentList results = queryResponse.getResults(); for (SolrDocument eachSolrDocument : results) { reports.add(createReport(eachSolrDocument)); } return Reports.create(reports, start, Math.toIntExact(results.getNumFound())); } catch (SolrServerException | IOException e) { throw new DataRetrievalException("Could not retrieve reports.", e); } }
From source file:org.elasticsearch.xpack.security.authc.kerberos.KerberosAuthenticationIT.java
private static void configureRestClientBuilder(final RestClientBuilder restClientBuilder, final Settings settings) throws IOException { final String requestTimeoutString = settings.get(CLIENT_RETRY_TIMEOUT); if (requestTimeoutString != null) { final TimeValue maxRetryTimeout = TimeValue.parseTimeValue(requestTimeoutString, CLIENT_RETRY_TIMEOUT); restClientBuilder.setMaxRetryTimeoutMillis(Math.toIntExact(maxRetryTimeout.getMillis())); }//from w w w . j av a2 s . com final String socketTimeoutString = settings.get(CLIENT_SOCKET_TIMEOUT); if (socketTimeoutString != null) { final TimeValue socketTimeout = TimeValue.parseTimeValue(socketTimeoutString, CLIENT_SOCKET_TIMEOUT); restClientBuilder.setRequestConfigCallback( conf -> conf.setSocketTimeout(Math.toIntExact(socketTimeout.getMillis()))); } if (settings.hasValue(CLIENT_PATH_PREFIX)) { restClientBuilder.setPathPrefix(settings.get(CLIENT_PATH_PREFIX)); } }
From source file:org.ballerinalang.net.grpc.nativeimpl.serviceendpoint.Init.java
private ListenerConfiguration getListenerConfig(Struct endpointConfig) { String host = endpointConfig.getStringField(GrpcConstants.ENDPOINT_CONFIG_HOST); long port = endpointConfig.getIntField(GrpcConstants.ENDPOINT_CONFIG_PORT); Struct sslConfig = endpointConfig.getStructField(GrpcConstants.ENDPOINT_CONFIG_SECURE_SOCKET); ListenerConfiguration listenerConfiguration = new ListenerConfiguration(); if (host == null || host.trim().isEmpty()) { listenerConfiguration/*from w ww . j ava2 s .com*/ .setHost(configRegistry.getConfigOrDefault("b7a.http.host", GrpcConstants.HTTP_DEFAULT_HOST)); } else { listenerConfiguration.setHost(host); } if (port == 0) { throw new BallerinaConnectorException("Listener port is not defined!"); } listenerConfiguration.setPort(Math.toIntExact(port)); if (sslConfig != null) { setSslConfig(sslConfig, listenerConfiguration); } listenerConfiguration.setServerHeader(getServerName()); listenerConfiguration.setVersion(String.valueOf(Constants.HTTP_2_0)); return listenerConfiguration; }