List of usage examples for java.lang Math toIntExact
public static int toIntExact(long value)
From source file:org.ballerinalang.net.http.serviceendpoint.InitEndpoint.java
private 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 {/* w w w . j a v a 2 s .c om*/ 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:com.netflix.genie.web.rpc.grpc.services.impl.v4.GRpcAgentFileStreamServiceImpl.java
/** * {@inheritDoc}/* www. ja va 2 s . c om*/ */ @Override public Optional<AgentFileResource> getResource(final String jobId, final Path relativePath, final URI uri) { final ControlStreamObserver streamObserver = this.jobIdControlStreamMap.get(jobId); if (streamObserver == null) { log.warn("Stream Record not found for job id: {}", jobId); return Optional.empty(); } final JobDirectoryManifest manifest = streamObserver.manifestRef.get(); if (manifest == null) { log.warn("Stream record for job id: {} does not have a manifest", jobId); return Optional.empty(); } final JobDirectoryManifest.ManifestEntry manifestEntry = manifest.getEntry(relativePath.toString()) .orElse(null); if (manifestEntry == null) { // File does not exist according to manifest log.warn("Requesting a file that does not exist in the manifest for job id: {}: ", jobId, relativePath); return Optional.of(AgentFileResourceImpl.forNonExistingResource()); } // A unique ID for this file transfer final String fileTransferId = UUID.randomUUID().toString(); // TODO: code upstream of here assumes files is requested in its entirety. // But rest of the code downstream actually treats everything as a range request. final int startOffset = 0; final int endOffset = Math.toIntExact(manifestEntry.getSize()); // Allocate and park the buffer that will store the data in transit. final StreamBuffer buffer = new StreamBuffer(); if (endOffset - startOffset == 0) { // When requesting an empty file (or a range of 0 bytes), short-circuit and just return an empty resource. buffer.closeForCompleted(); } else { // Expecting some data. Track this stream and its buffer so incoming chunks can be appended. this.pendingTransferBuffersMap.put(fileTransferId, buffer); // Request file over control channel streamObserver.responseObserver.onNext(ServerControlMessage.newBuilder() .setServerFileRequest(ServerFileRequestMessage.newBuilder().setStreamId(fileTransferId) .setRelativePath(relativePath.toString()).setStartOffset(startOffset) .setEndOffset(endOffset).build()) .build()); // Schedule a timeout for this transfer to start (first chunk received) this.taskScheduler.schedule(() -> { final StreamBuffer b = pendingTransferBuffersMap.remove(fileTransferId); // Is this stream/buffer still in the 'pending' map? if (b != null) { b.closeForError(new TimeoutException("Timeout waiting for transfer to start")); } }, Instant.now().plusMillis(FILE_TRANSFER_BEGIN_TIMEOUT_MILLIS)); } final AgentFileResource resource = AgentFileResourceImpl.forAgentFile(uri, manifestEntry.getSize(), manifestEntry.getLastModifiedTime(), Paths.get(manifestEntry.getPath()), jobId, buffer.getInputStream()); return Optional.of(resource); }
From source file:com.marklogic.hub.HubTestBase.java
protected static int getDocCount(String database) { int count = 0; EvalResultIterator resultItr = runInDatabase("xdmp:estimate(fn:doc())", database); if (resultItr == null || !resultItr.hasNext()) { return count; }/* w w w. j a v a2s.c o m*/ EvalResult res = resultItr.next(); count = Math.toIntExact((long) res.getNumber()); return count; }
From source file:net.longfalcon.newsj.Releases.java
public List<ReleaseRegex> getRegexesWithStatistics(boolean activeOnly, String groupName, boolean userReleaseRegexes) { List<ReleaseRegex> releaseRegexList = releaseRegexDAO.getRegexes(activeOnly, groupName, userReleaseRegexes); for (ReleaseRegex releaseRegex : releaseRegexList) { long releaseRegexId = releaseRegex.getId(); int releaseCount = Math.toIntExact(releaseDAO.countReleasesByRegexId(releaseRegexId)); releaseRegex.setNumberReleases(releaseCount); releaseRegex.setLastReleaseDate(releaseDAO.getLastReleaseDateByRegexId(releaseRegexId)); }/*from w w w . j a v a2 s .c om*/ return releaseRegexList; }
From source file:io.pravega.segmentstore.storage.impl.extendeds3.S3FileSystemImpl.java
@Override public InputStream readObjectStream(String bucketName, String key, Range range) { byte[] bytes = new byte[Math.toIntExact(range.getLast() + 1 - range.getFirst())]; Path path = Paths.get(this.baseDir, bucketName, key); FileInputStream returnStream; try {//from w ww .j av a 2s . c om returnStream = new FileInputStream(path.toFile()); if (range.getFirst() != 0) { long bytesSkipped = 0; do { bytesSkipped += returnStream.skip(range.getFirst()); } while (bytesSkipped < range.getFirst()); } StreamHelpers.readAll(returnStream, bytes, 0, bytes.length); return new ByteArrayInputStream(bytes); } catch (IOException e) { throw new S3Exception("NoSuchKey", HttpStatus.SC_NOT_FOUND, "NoSuchKey", ""); } }
From source file:org.elasticsearch.xpack.watcher.common.http.HttpClient.java
public HttpResponse execute(HttpRequest request) throws IOException { URI uri = createURI(request); HttpRequestBase internalRequest;/*ww w . j a v a2s. com*/ if (request.method == HttpMethod.HEAD) { internalRequest = new HttpHead(uri); } else { HttpMethodWithEntity methodWithEntity = new HttpMethodWithEntity(uri, request.method.name()); if (request.hasBody()) { ByteArrayEntity entity = new ByteArrayEntity(request.body.getBytes(StandardCharsets.UTF_8)); String contentType = request.headers().get(HttpHeaders.CONTENT_TYPE); if (Strings.hasLength(contentType)) { entity.setContentType(contentType); } else { entity.setContentType(ContentType.TEXT_PLAIN.toString()); } methodWithEntity.setEntity(entity); } internalRequest = methodWithEntity; } internalRequest.setHeader(HttpHeaders.ACCEPT_CHARSET, StandardCharsets.UTF_8.name()); // headers if (request.headers().isEmpty() == false) { for (Map.Entry<String, String> entry : request.headers.entrySet()) { internalRequest.setHeader(entry.getKey(), entry.getValue()); } } // BWC - hack for input requests made to elasticsearch that do not provide the right content-type header! if (request.hasBody() && internalRequest.containsHeader("Content-Type") == false) { XContentType xContentType = XContentFactory.xContentType(request.body()); if (xContentType != null) { internalRequest.setHeader("Content-Type", xContentType.mediaType()); } } RequestConfig.Builder config = RequestConfig.custom(); setProxy(config, request, settingsProxy); HttpClientContext localContext = HttpClientContext.create(); // auth if (request.auth() != null) { ApplicableHttpAuth applicableAuth = httpAuthRegistry.createApplicable(request.auth); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); applicableAuth.apply(credentialsProvider, new AuthScope(request.host, request.port)); localContext.setCredentialsProvider(credentialsProvider); // preemptive auth, no need to wait for a 401 first AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(new HttpHost(request.host, request.port, request.scheme.scheme()), basicAuth); localContext.setAuthCache(authCache); } // timeouts if (request.connectionTimeout() != null) { config.setConnectTimeout(Math.toIntExact(request.connectionTimeout.millis())); } else { config.setConnectTimeout(Math.toIntExact(defaultConnectionTimeout.millis())); } if (request.readTimeout() != null) { config.setSocketTimeout(Math.toIntExact(request.readTimeout.millis())); config.setConnectionRequestTimeout(Math.toIntExact(request.readTimeout.millis())); } else { config.setSocketTimeout(Math.toIntExact(defaultReadTimeout.millis())); config.setConnectionRequestTimeout(Math.toIntExact(defaultReadTimeout.millis())); } internalRequest.setConfig(config.build()); try (CloseableHttpResponse response = SocketAccess .doPrivileged(() -> client.execute(internalRequest, localContext))) { // headers Header[] headers = response.getAllHeaders(); Map<String, String[]> responseHeaders = new HashMap<>(headers.length); for (Header header : headers) { if (responseHeaders.containsKey(header.getName())) { String[] old = responseHeaders.get(header.getName()); String[] values = new String[old.length + 1]; System.arraycopy(old, 0, values, 0, old.length); values[values.length - 1] = header.getValue(); responseHeaders.put(header.getName(), values); } else { responseHeaders.put(header.getName(), new String[] { header.getValue() }); } } final byte[] body; // not every response has a content, i.e. 204 if (response.getEntity() == null) { body = new byte[0]; } else { try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { try (InputStream is = new SizeLimitInputStream(maxResponseSize, response.getEntity().getContent())) { Streams.copy(is, outputStream); } body = outputStream.toByteArray(); } } return new HttpResponse(response.getStatusLine().getStatusCode(), body, responseHeaders); } }
From source file:org.apache.beam.sdk.extensions.sql.impl.udf.BuiltinStringFunctions.java
@UDF(funcName = "RPAD", parameterArray = { TypeName.STRING, TypeName.INT64, TypeName.STRING }, returnType = TypeName.STRING) public String rpad(String originalValue, Long returnLength, String pattern) { if (originalValue == null || returnLength == null || pattern == null) { return null; }//from w ww.j a v a 2s .co m 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 right return StringUtils.rightPad(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.cgiar.ccafs.marlo.action.center.monitoring.project.ProjectListAction.java
@Override public String add() { /**//from www.jav a 2 s. c o m * Add Project sync information */ Map<String, Parameter> parameters = this.getParameters(); syncTypeID = Long.parseLong( StringUtils.trim(parameters.get(APConstants.CENTER_PROJECT_SYNC_TYPE).getMultipleValues()[0])); syncCode = StringUtils.trim(parameters.get(APConstants.CENTER_PROJECT_SYNC_CODE).getMultipleValues()[0]); switch (Math.toIntExact(syncTypeID)) { case 1: this.addOcsProjectInformation(projectID); break; case 2: if (syncCode.toUpperCase().contains("P")) { syncCode = syncCode.toUpperCase().replaceFirst("P", ""); } this.addCrpProjectInformation(projectID); break; default: this.createEmptyProject(); break; } if (projectID > 0) { return SUCCESS; } else { return NOT_FOUND; } }
From source file:org.zanata.dao.GlossaryDAO.java
/** * Returns map of statistics group by locale id. * Object[0] - HLocale// ww w .j ava 2 s . co m * Object[1] - Integer word count */ private Map<LocaleId, Integer> generateLocaleStats(List<Object[]> list) { Map<LocaleId, Integer> localeStats = Maps.newHashMap(); for (Object[] obj : list) { HLocale locale = (HLocale) obj[0]; Long count = (Long) obj[1]; int countInt = count == null ? 0 : Math.toIntExact(count); localeStats.put(locale.getLocaleId(), countInt); } return localeStats; }
From source file:org.apache.beam.sdk.extensions.sql.impl.udf.BuiltinStringFunctions.java
@UDF(funcName = "RPAD", parameterArray = { TypeName.BYTES, TypeName.INT64, TypeName.BYTES }, returnType = TypeName.BYTES) public byte[] rpad(byte[] originalValue, Long returnLength, byte[] pattern) { if (originalValue == null || returnLength == null || pattern == null) { return null; }// ww w . ja v a 2s . co m 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 right byte[] ret = new byte[returnLengthInt]; // step one: copy originalValue. System.arraycopy(originalValue, 0, ret, 0, originalValue.length); // step one: pad #(returnLengthInt - originalValue.length) bytes to right side. int paddingOff = originalValue.length; int paddingLeftBytes = returnLengthInt - originalValue.length; byteArrayPadding(ret, pattern, paddingOff, paddingLeftBytes); 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; } }