List of usage examples for java.lang Math toIntExact
public static int toIntExact(long value)
From source file:org.apache.nifi.controller.livy.LivySessionController.java
@OnEnabled public void onConfigured(final ConfigurationContext context) { ComponentLog log = getLogger();/* w ww .jav a 2s .co m*/ final String livyHost = context.getProperty(LIVY_HOST).evaluateAttributeExpressions().getValue(); final String livyPort = context.getProperty(LIVY_PORT).evaluateAttributeExpressions().getValue(); final String sessionPoolSize = context.getProperty(SESSION_POOL_SIZE).evaluateAttributeExpressions() .getValue(); final String sessionKind = context.getProperty(SESSION_TYPE).getValue(); final long sessionManagerStatusInterval = context.getProperty(SESSION_MGR_STATUS_INTERVAL) .asTimePeriod(TimeUnit.MILLISECONDS); final String jars = context.getProperty(JARS).evaluateAttributeExpressions().getValue(); final String files = context.getProperty(FILES).evaluateAttributeExpressions().getValue(); sslContextService = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class); sslContext = sslContextService == null ? null : sslContextService.createSSLContext(SSLContextService.ClientAuth.NONE); connectTimeout = Math.toIntExact(context.getProperty(CONNECT_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS)); this.livyUrl = "http" + (sslContextService != null ? "s" : "") + "://" + livyHost + ":" + livyPort; this.controllerKind = sessionKind; this.jars = jars; this.files = files; this.sessionPoolSize = Integer.valueOf(sessionPoolSize); this.enabled = true; livySessionManagerThread = new Thread(() -> { while (enabled) { try { manageSessions(); Thread.sleep(sessionManagerStatusInterval); } catch (InterruptedException e) { Thread.currentThread().interrupt(); enabled = false; } catch (IOException ioe) { throw new ProcessException(ioe); } } }); livySessionManagerThread.setName("Livy-Session-Manager-" + controllerKind); livySessionManagerThread.start(); }
From source file:org.eclipse.hawkbit.repository.jpa.ArtifactManagementTest.java
@Test @Description("Verifies that the quota specifying the maximum artifact storage is enforced (across software modules).") public void createArtifactsUntilStorageQuotaIsExceeded() throws NoSuchAlgorithmException, IOException { // create as many small artifacts as possible w/o violating the storage // quota// w ww.j a v a 2 s .com final long maxBytes = quotaManagement.getMaxArtifactStorage(); final List<Long> artifactIds = Lists.newArrayList(); // choose an artifact size which does not violate the max file size final int artifactSize = Math.toIntExact(quotaManagement.getMaxArtifactSize() / 10); final int numArtifacts = Math.toIntExact(maxBytes / artifactSize); for (int i = 0; i < numArtifacts; ++i) { final JpaSoftwareModule sm = softwareModuleRepository .save(new JpaSoftwareModule(osType, "smd" + i, "1.0", null, null)); artifactIds.add(createArtifactForSoftwareModule("file" + i, sm.getId(), artifactSize).getId()); } // upload one more artifact to trigger the quota exceeded error final JpaSoftwareModule sm = softwareModuleRepository .save(new JpaSoftwareModule(osType, "smd" + numArtifacts, "1.0", null, null)); assertThatExceptionOfType(QuotaExceededException.class) .isThrownBy(() -> createArtifactForSoftwareModule("file" + numArtifacts, sm.getId(), artifactSize)); // delete one of the artifacts artifactManagement.delete(artifactIds.get(0)); // now we should be able to create an artifact again createArtifactForSoftwareModule("fileXYZ", sm.getId(), artifactSize); }
From source file:org.pentaho.big.data.kettle.plugins.formats.orc.output.OrcOutputMetaBase.java
@Override public void readRep(Repository rep, IMetaStore metaStore, ObjectId id_step, List<DatabaseMeta> databases) throws KettleException { try {//from w w w . j a va 2s .c o m filename = rep.getStepAttributeString(id_step, FieldNames.FILE_NAME); overrideOutput = rep.getStepAttributeBoolean(id_step, FieldNames.OVERRIDE_OUTPUT); compressionType = rep.getStepAttributeString(id_step, FieldNames.COMPRESSION); stripeSize = Math.toIntExact(rep.getStepAttributeInteger(id_step, FieldNames.STRIPE_SIZE)); compressSize = Math.toIntExact(rep.getStepAttributeInteger(id_step, FieldNames.COMPRESS_SIZE)); rowsBetweenEntries = Math .toIntExact(rep.getStepAttributeInteger(id_step, FieldNames.ROWS_BETWEEN_ENTRIES)); dateTimeFormat = rep.getStepAttributeString(id_step, FieldNames.DATE_FORMAT); dateInFileName = rep.getStepAttributeBoolean(id_step, FieldNames.DATE_IN_FILE_NAME); timeInFileName = rep.getStepAttributeBoolean(id_step, FieldNames.TIME_IN_FILE_NAME); // using the "type" column to get the number of field rows because "type" is guaranteed not to be null. int nrfields = rep.countNrStepAttributes(id_step, "type"); List<OrcOutputField> orcOutputFields = new ArrayList<>(); for (int i = 0; i < nrfields; i++) { OrcOutputField outputField = new OrcOutputField(); outputField.setFormatFieldName(rep.getStepAttributeString(id_step, i, "path")); outputField.setPentahoFieldName(rep.getStepAttributeString(id_step, i, "name")); outputField.setFormatType(rep.getStepAttributeString(id_step, i, "type")); outputField.setPrecision(rep.getStepAttributeString(id_step, i, "precision")); outputField.setScale(rep.getStepAttributeString(id_step, i, "scale")); outputField.setAllowNull(rep.getStepAttributeString(id_step, i, "nullable")); outputField.setDefaultValue(rep.getStepAttributeString(id_step, i, "default")); orcOutputFields.add(outputField); } this.outputFields = orcOutputFields; } catch (Exception e) { throw new KettleException("Unexpected error reading step information from the repository", e); } }
From source file:org.ballerinalang.net.grpc.nativeimpl.serviceendpoint.Init.java
private void setSslConfig(Struct sslConfig, ListenerConfiguration listenerConfiguration) { listenerConfiguration.setScheme(GrpcConstants.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); if (keyStore != null) { String keyStoreFile = keyStore.getStringField(FILE_PATH); String keyStorePassword = keyStore.getStringField(PASSWORD); if (StringUtils.isBlank(keyStoreFile)) { throw new BallerinaConnectorException("Keystore location must be provided for secure connection"); }//from w w w . j a v a2s . com if (StringUtils.isBlank(keyStorePassword)) { throw new BallerinaConnectorException( "Keystore password value must be provided for secure connection"); } listenerConfiguration.setKeyStoreFile(keyStoreFile); listenerConfiguration.setKeyStorePass(keyStorePassword); } String sslVerifyClient = sslConfig.getStringField(SSL_CONFIG_SSL_VERIFY_CLIENT); listenerConfiguration.setVerifyClient(sslVerifyClient); 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); } 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(GrpcConstants.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(SSL_CONFIG_CIPHERS)); if (!ciphersValueList.isEmpty()) { String ciphers = ciphersValueList.stream().map(Value::getStringValue) .collect(Collectors.joining(",", "", "")); serverParameters = new Parameter(GrpcConstants.CIPHERS, ciphers); serverParamList.add(serverParameters); } if (validateCert != null) { boolean validateCertificateEnabled = validateCert.getBooleanField(ENABLE); long cacheSize = validateCert.getIntField(SSL_CONFIG_CACHE_SIZE); long cacheValidationPeriod = validateCert.getIntField(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(ENABLE); listenerConfiguration.setOcspStaplingEnabled(ocspStaplingEnabled); long cacheSize = ocspStapling.getIntField(SSL_CONFIG_CACHE_SIZE); long cacheValidationPeriod = ocspStapling.getIntField(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(GrpcConstants.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(getListenerInterface(listenerConfiguration.getHost(), listenerConfiguration.getPort())); }
From source file:org.apache.pulsar.sql.presto.PulsarSplitManager.java
@VisibleForTesting Collection<PulsarSplit> getSplitsForTopic(String topicNamePersistenceEncoding, ManagedLedgerFactory managedLedgerFactory, int numSplits, PulsarTableHandle tableHandle, SchemaInfo schemaInfo, String tableName, TupleDomain<ColumnHandle> tupleDomain) throws ManagedLedgerException, InterruptedException { ReadOnlyCursor readOnlyCursor = null; try {/* www . ja va2 s . c o m*/ readOnlyCursor = managedLedgerFactory.openReadOnlyCursor(topicNamePersistenceEncoding, PositionImpl.earliest, new ManagedLedgerConfig()); long numEntries = readOnlyCursor.getNumberOfEntries(); if (numEntries <= 0) { return Collections.EMPTY_LIST; } PredicatePushdownInfo predicatePushdownInfo = PredicatePushdownInfo.getPredicatePushdownInfo( this.connectorId, tupleDomain, managedLedgerFactory, topicNamePersistenceEncoding, numEntries); PositionImpl initialStartPosition; if (predicatePushdownInfo != null) { numEntries = predicatePushdownInfo.getNumOfEntries(); initialStartPosition = predicatePushdownInfo.getStartPosition(); } else { initialStartPosition = (PositionImpl) readOnlyCursor.getReadPosition(); } readOnlyCursor.close(); readOnlyCursor = managedLedgerFactory.openReadOnlyCursor(topicNamePersistenceEncoding, initialStartPosition, new ManagedLedgerConfig()); long remainder = numEntries % numSplits; long avgEntriesPerSplit = numEntries / numSplits; List<PulsarSplit> splits = new LinkedList<>(); for (int i = 0; i < numSplits; i++) { long entriesForSplit = (remainder > i) ? avgEntriesPerSplit + 1 : avgEntriesPerSplit; PositionImpl startPosition = (PositionImpl) readOnlyCursor.getReadPosition(); readOnlyCursor.skipEntries(Math.toIntExact(entriesForSplit)); PositionImpl endPosition = (PositionImpl) readOnlyCursor.getReadPosition(); splits.add(new PulsarSplit(i, this.connectorId, tableHandle.getSchemaName(), tableName, entriesForSplit, new String(schemaInfo.getSchema()), schemaInfo.getType(), startPosition.getEntryId(), endPosition.getEntryId(), startPosition.getLedgerId(), endPosition.getLedgerId(), tupleDomain)); } return splits; } finally { if (readOnlyCursor != null) { try { readOnlyCursor.close(); } catch (Exception e) { log.error(e); } } } }
From source file:org.eclipse.hawkbit.mgmt.rest.resource.MgmtSoftwareModuleResourceTest.java
@Test @Description("Verifies that artifacts which exceed the configured maximum size cannot be uploaded.") public void uploadArtifactFailsIfTooLarge() throws Exception { final SoftwareModule sm = testdataFactory.createSoftwareModule("quota", "quota"); final long maxSize = quotaManagement.getMaxArtifactSize(); // create a file which exceeds the configured maximum size final byte[] randomBytes = randomBytes(Math.toIntExact(maxSize) + 1024); final MockMultipartFile file = new MockMultipartFile("file", "origFilename", null, randomBytes); // try to upload mvc.perform(fileUpload("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file) .accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isForbidden()); }
From source file:net.longfalcon.newsj.service.MovieService.java
public int getMovieCount(List<Category> searchCategories, int maxAgeDays, List<Integer> userExCatIds, String titleSearch, String genreSearch, String actorsSearch, String directorSearch, String yearSearch) { List<Integer> categoryIds = searchCategories.stream().map(Category::getId).collect(Collectors.toList()); List<Long> imdbIds = releaseDAO.getDistinctImdbIds(categoryIds, maxAgeDays, userExCatIds); long movieCount = movieInfoDAO.getMovieCount(imdbIds, titleSearch, genreSearch, actorsSearch, directorSearch, yearSearch); return Math.toIntExact(movieCount); }
From source file:org.wso2.siddhi.extension.input.transport.kafka.KafkaSourceTestCase.java
@Test public void testRecoveryOnFailureOfSingleNodeWithKafka() throws InterruptedException { try {//from w w w.j a v a2 s .c om log.info( "Test to verify recovering process of a Siddhi node on a failure when Kafka is the event source"); String topics[] = new String[] { "kafka_topic4" }; createTopic(topics, 1); PersistenceStore persistenceStore = new InMemoryPersistenceStore(); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.setPersistenceStore(persistenceStore); siddhiManager.setExtension("source.mapper:text", TextSourceMapper.class); String query = "@Plan:name('TestExecutionPlan') " + "define stream BarStream (count long); " + "@info(name = 'query1') " + "@source(type='kafka', topic='kafka_topic4', group.id='test', " + "threading.option='topic.wise', bootstrap.servers='localhost:9092', partition.no.list='0', " + "@map(type='text'))" + "Define stream FooStream (symbol string, price float, volume long);" + "from FooStream select count(symbol) as count insert into BarStream;"; ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(query); executionPlanRuntime.addCallback("BarStream", new StreamCallback() { @Override public void receive(Event[] events) { for (Event event : events) { eventArrived = true; System.out.println(event); count = Math.toIntExact((long) event.getData(0)); } } }); // start publishing events to Kafka Future eventSender = executorService.submit(new Runnable() { @Override public void run() { kafkaPublisher(topics, 1, 50, 1000); } }); Thread.sleep(2000); // start the execution plan executionPlanRuntime.start(); // wait for some time Thread.sleep(28000); // initiate a checkpointing task Future perisistor = executionPlanRuntime.persist(); // waits till the checkpointing task is done while (!perisistor.isDone()) { Thread.sleep(100); } // let few more events to be published Thread.sleep(5000); // initiate a execution plan shutdown - to demonstrate a node failure executionPlanRuntime.shutdown(); // let few events to be published while the execution plan is down Thread.sleep(5000); // recreate the execution plan executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(query); executionPlanRuntime.addCallback("BarStream", new StreamCallback() { @Override public void receive(Event[] events) { for (Event event : events) { eventArrived = true; System.out.println(event); count = Math.toIntExact((long) event.getData(0)); } } }); // start the execution plan executionPlanRuntime.start(); // immediately trigger a restore from last revision executionPlanRuntime.restoreLastRevision(); Thread.sleep(5000); // waits till all the events are published while (!eventSender.isDone()) { Thread.sleep(2000); } Thread.sleep(20000); assertTrue(eventArrived); // assert the count assertEquals(50, count); executionPlanRuntime.shutdown(); } catch (ZkTimeoutException ex) { log.warn("No zookeeper may not be available.", ex); } }
From source file:org.ballerinalang.net.http.serviceendpoint.InitEndpoint.java
private ListenerConfiguration setSslConfig(Struct sslConfig, ListenerConfiguration listenerConfiguration) { listenerConfiguration.setScheme(HttpConstants.PROTOCOL_HTTPS); Struct trustStore = sslConfig.getStructField(HttpConstants.ENDPOINT_CONFIG_TRUST_STORE); Struct keyStore = sslConfig.getStructField(HttpConstants.ENDPOINT_CONFIG_KEY_STORE); Struct protocols = sslConfig.getStructField(HttpConstants.ENDPOINT_CONFIG_PROTOCOLS); Struct validateCert = sslConfig.getStructField(HttpConstants.ENDPOINT_CONFIG_VALIDATE_CERT); Struct ocspStapling = sslConfig.getStructField(HttpConstants.ENDPOINT_CONFIG_OCSP_STAPLING); if (keyStore != null) { String keyStoreFile = keyStore.getStringField(HttpConstants.FILE_PATH); String keyStorePassword = keyStore.getStringField(HttpConstants.PASSWORD); if (StringUtils.isBlank(keyStoreFile)) { //TODO get from language pack, and add location throw new BallerinaConnectorException("Keystore location must be provided for secure connection"); }/*from w w w.java 2 s .c o m*/ if (StringUtils.isBlank(keyStorePassword)) { //TODO get from language pack, and add location throw new BallerinaConnectorException( "Keystore password value must be provided for secure connection"); } listenerConfiguration.setKeyStoreFile(keyStoreFile); listenerConfiguration.setKeyStorePass(keyStorePassword); } String sslVerifyClient = sslConfig.getStringField(HttpConstants.SSL_CONFIG_SSL_VERIFY_CLIENT); listenerConfiguration.setVerifyClient(sslVerifyClient); if (trustStore != null) { String trustStoreFile = trustStore.getStringField(HttpConstants.FILE_PATH); String trustStorePassword = trustStore.getStringField(HttpConstants.PASSWORD); if (StringUtils.isBlank(trustStoreFile) && StringUtils.isNotBlank(sslVerifyClient)) { //TODO get from language pack, and add location throw new BallerinaException("Truststore location must be provided to enable Mutual SSL"); } if (StringUtils.isBlank(trustStorePassword) && StringUtils.isNotBlank(sslVerifyClient)) { //TODO get from language pack, and add location throw new BallerinaException("Truststore password value must be provided to enable Mutual SSL"); } listenerConfiguration.setTrustStoreFile(trustStoreFile); listenerConfiguration.setTrustStorePass(trustStorePassword); } List<Parameter> serverParamList = new ArrayList<>(); Parameter serverParameters; if (protocols != null) { List<Value> sslEnabledProtocolsValueList = Arrays .asList(protocols.getArrayField(HttpConstants.ENABLED_PROTOCOLS)); if (!sslEnabledProtocolsValueList.isEmpty()) { String sslEnabledProtocols = sslEnabledProtocolsValueList.stream().map(Value::getStringValue) .collect(Collectors.joining(",", "", "")); serverParameters = new Parameter(HttpConstants.ANN_CONFIG_ATTR_SSL_ENABLED_PROTOCOLS, sslEnabledProtocols); serverParamList.add(serverParameters); } String sslProtocol = protocols.getStringField(HttpConstants.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(HttpConstants.PKCS_STORE_TYPE); String serverEnableSessionCreation = String .valueOf(sslConfig.getBooleanField(HttpConstants.SSL_CONFIG_ENABLE_SESSION_CREATION)); Parameter enableSessionCreationParam = new Parameter(HttpConstants.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; }