auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testCurrentSize() throws Exception { Neo4jItemReader<String> itemReader = new Neo4jItemReaderBuilder<String>().sessionFactory(this.sessionFactory) .targetType(String.class).startStatement("n=node(*)").orderByStatement("n.age").pageSize(50).name("bar") .returnStatement("m").currentItemCount(5).maxItemCount(5).build(); when(this.sessionFactory.openSession()).thenReturn(this.session); when(this.session.query(String.class, "START n=node(*) RETURN m ORDER BY n.age SKIP 0 LIMIT 50", null)) .thenReturn(result); when(result.iterator()).thenReturn(Arrays.asList("foo", "bar", "baz").iterator()); assertNull("The expected value was not returned by reader.", itemReader.read()); itemReader = new Neo4jItemReaderBuilder<String>().sessionFactory(this.sessionFactory).targetType(String.class) .startStatement("n=node(*)").orderByStatement("n.age").pageSize(50).name("bar").returnStatement("m") .currentItemCount(0).maxItemCount(1).build(); assertEquals("The expected value was not returned by reader.", "foo", itemReader.read()); assertNull("The expected value was not should be null.", itemReader.read()); }

Target:
public void testCurrentSize() throws Exception { Neo4jItemReader<String> itemReader = new Neo4jItemReaderBuilder<String>() .sessionFactory(this.sessionFactory) .targetType(String.class) .startStatement("n=node(*)") .orderByStatement("n.age") .pageSize(50).name("bar") .returnStatement("m") .currentItemCount(0) .maxItemCount(1) .build(); when(this.sessionFactory.openSession()).thenReturn(this.session); when(this.session.query(String.class, "START n=node(*) RETURN m ORDER BY n.age SKIP 0 LIMIT 50", null)) .thenReturn(result); when(result.iterator()).thenReturn(Arrays.asList("foo", "bar", "baz").iterator()); assertEquals("The expected value was not returned by reader.", "foo", itemReader.read()); assertNull("The expected value was not should be null.", itemReader.read()); }
Source:
protected void reset(int retainFlags) { finishDelayedFreeFlags(); retainFlags |= PARSED | retainOnReset; final int clearFlags = ~retainFlags; final FIFORevQueue q = new FIFORevQueue(); for (RevCommit c : roots) { if ((c.flags & clearFlags) == 0) continue; c.flags &= retainFlags; c.reset(); q.add(c); } for (;;) { final RevCommit c = q.next(); if (c == null) break; if (c.parents == null) continue; for (RevCommit p : c.parents) { if ((p.flags & clearFlags) == 0) continue; p.flags &= retainFlags; p.reset(); q.add(p); } } roots.clear(); queue = new DateRevQueue(firstParent); pending = new StartGenerator(this); }

Target:
protected void reset(int retainFlags) { finishDelayedFreeFlags(); retainFlags |= PARSED | retainOnReset; final int clearFlags = ~retainFlags; final FIFORevQueue q = new FIFORevQueue(); for (RevCommit c : roots) { if ((c.flags & clearFlags) == 0) continue; c.flags &= retainFlags; c.reset(); q.add(c); } for (;;) { final RevCommit c = q.next(); if (c == null) break; if (c.parents == null) continue; for (RevCommit p : c.parents) { if ((p.flags & clearFlags) == 0) continue; p.flags &= retainFlags; p.reset(); q.add(p); } } roots.clear(); firstParent = false; queue = new DateRevQueue(firstParent); pending = new StartGenerator(this); }
Source:
public void actionPerformed(ActionEvent e) { setContinue(true); setBreakAll(false); setBreakRequest(false); setBreakResponse(false); setBreakOnJavaScript(isBreakOnJavaScript); setBreakOnCSSAndFonts(isBreakOnCSSAndFonts); setBreakOnMultimedia(isBreakOnMultimedia); setOnlyBreakOnScope(isOnlyBreakOnScope); }

Target:
public void actionPerformed(ActionEvent e) { if (!breakPanel.isValidState()) { return; } setContinue(true); setBreakAll(false); setBreakRequest(false); setBreakResponse(false); }
Source:
@Override public MapColor shade(MapShade newShading) { return this.baseColor.shade(newShading); }

Target:
public MapColor shade(MapShade newShading) { return this.baseColor.shade(newShading); }
Source:
private String computeDigest() { StringBuilder buf = new StringBuilder("rule [" + getRule() + "] rels ["); for (int i = 0; i < rels.length; i++) { if (i > 0) { buf.append(", "); } buf.append("#" + rels[i].getId()); } buf.append("]"); return buf.toString(); }

Target:
private String computeDigest() { StringBuilder buf = new StringBuilder("rule [" + getRule() + "] rels ["); for (int i = 0; i < rels.length; i++) { if (i > 0) { buf.append(','); } buf.append('#').append(rels[i].getId()); } buf.append(']'); return buf.toString(); }
Source:
public int getFontSize() { return fontSize; }

Target:
public int getFontSize() { return getFontSize(FontUtils.FontType.general); }
Source:
public InterruptedException shutDownAll() { pools.forEach( ( group, pool ) -> pool.cancelAllJobs() ); pools.forEach( ( group, pool ) -> pool.shutDown() ); return pools.values().stream().reduce( null, ( e, p ) -> Exceptions.chain( e, p.getShutdownException() ), Exceptions::chain ); }

Target:
public InterruptedException shutDownAll() { pools.forEach( ( group, pool ) -> pool.cancelAllJobs() ); pools.forEach( ( group, pool ) -> pool.shutDown() ); return pools.values().stream() .map( ThreadPool::getShutdownException ) .reduce( null, Exceptions::chain ); }
Source:
PlatformTransactionManager athenaTransactionManager(@Qualifier("athenaEntityManagerFactory") EntityManagerFactory entityManagerFactory) { return new JpaTransactionManager(entityManagerFactory); }

Target:
public PlatformTransactionManager athenaTransactionManager(@Qualifier("athenaEntityManagerFactory") EntityManagerFactory entityManagerFactory) { return new JpaTransactionManager(entityManagerFactory); }
Source:
public void setCodeMiningProviders(ICodeMiningProvider[] codeMiningProviders) { if (fCodeMiningProviders != null) { for (ICodeMiningProvider contentMiningProvider : fCodeMiningProviders) { contentMiningProvider.dispose(); } } fCodeMiningProviders= Arrays.asList(codeMiningProviders); }

Target:
public void setCodeMiningProviders(ICodeMiningProvider[] codeMiningProviders) { List<CodeMiningProviderWrapper> oldCodeMiningProviders= fCodeMiningProviders; fCodeMiningProviders= Stream.of(codeMiningProviders).map(provider -> new CodeMiningProviderWrapper(provider)).collect(Collectors.toList()); if (oldCodeMiningProviders != null) { for (CodeMiningProviderWrapper provider : oldCodeMiningProviders) { provider.dispose(); } } }
Source:
public SubscriptionMetrics() { }

Target:
private SubscriptionMetrics() { }
Source:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_form_display, container, false); getActivity().getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); mParent = (LinearLayout) root.findViewById(R.id.sectionContainer); mPresenter.subscribe(); return root; }

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_form_display, container, false); getActivity().getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); mParent = (LinearLayout) root.findViewById(R.id.sectionContainer); return root; }
Source:
public void shouldThrowException_WhenNoParameters() throws Exception { when(network.isConnected()).thenReturn(true); ExternalViewPresenter mock_up_presenter = new ExternalViewPresenter(view, network){ @Override protected boolean invalidParam(String url) { return true; } }; mock_up_presenter.onViewCreated(); }

Target:
public void shouldThrowException_WhenNoParameters() throws Exception { when(network.isConnected()).thenReturn(true); when(view.extractTitle()).thenReturn(null); when(view.extractUrl()).thenReturn(null); presenter.onViewCreated(); }
Source:
public void shouldThrowStreamsExceptionWithTimeoutHintOnProducerTimeoutWithDefaultExceptionHandler() { final RecordCollector collector = new RecordCollectorImpl( "test", logContext, new DefaultProductionExceptionHandler(), new Metrics().sensor("skipped-records")); collector.init(new MockProducer(cluster, true, new DefaultPartitioner(), byteArraySerializer, byteArraySerializer) { @Override public synchronized Future<RecordMetadata> send(final ProducerRecord record, final Callback callback) { callback.onCompletion(null, new TimeoutException()); return null; } }); collector.send("topic1", "3", "0", null, null, stringSerializer, stringSerializer, streamPartitioner); try { collector.flush(); fail("Should have thrown StreamsException"); } catch (final StreamsException expected) { assertTrue(expected.getCause() instanceof TimeoutException); assertTrue(expected.getMessage().endsWith(topic1TimeoutHint)); } }

Target:
public void shouldThrowStreamsExceptionWithTimeoutHintOnProducerTimeoutWithDefaultExceptionHandler() { final RecordCollector collector = new RecordCollectorImpl( "test", logContext, new DefaultProductionExceptionHandler(), new Metrics().sensor("skipped-records")); collector.init(new MockProducer<byte[], byte[]>(cluster, true, new DefaultPartitioner(), byteArraySerializer, byteArraySerializer) { @Override public synchronized Future<RecordMetadata> send(final ProducerRecord record, final Callback callback) { callback.onCompletion(null, new TimeoutException()); return null; } }); collector.send("topic1", "3", "0", null, null, stringSerializer, stringSerializer, streamPartitioner); final StreamsException expected = assertThrows(StreamsException.class, () -> collector.flush()); assertTrue(expected.getCause() instanceof TimeoutException); assertTrue(expected.getMessage().endsWith(topic1TimeoutHint)); }
Source:
public void onMessageReceived(RemoteMessage remoteMessage) { IEdxEnvironment environment = MainApplication.getEnvironment(this); if(!environment.getConfig().areNotificationsEnabled()){ return; } super.onMessageReceived(remoteMessage); if (remoteMessage.getNotification() != null) { Log.d(this.getClass().getSimpleName(), "Message Notification Body: " + remoteMessage.getNotification().getBody()); } NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(remoteMessage.getNotification().getTitle()) .setContentText(remoteMessage.getNotification().getBody()); Intent resultIntent = new Intent(this, MainDashboardActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(MainDashboardActivity.class); stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT ); builder.setContentIntent(resultPendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); try { notificationManager.notify(99, builder.build()); } catch (NullPointerException ex) { Log.e(this.getClass().getSimpleName(), ex.getMessage()); } }

Target:
public void onMessageReceived(RemoteMessage remoteMessage) { final IEdxEnvironment environment = MainApplication.getEnvironment(this); if (!environment.getConfig().areFirebasePushNotificationsEnabled()) { return; } if (remoteMessage.getNotification() != null) { logger.debug( "Message Notification Body: " + remoteMessage.getNotification().getBody() ); } sendNotification( remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody() ); }
Source:
private boolean hasRemoteSiteName(Metacard metacard) { Optional<String> sourceId = Optional.ofNullable(metacard.getSourceId()); if (sourceId.isPresent()) { String sourceIdLowerCase = sourceId.get(); return !sourceIdLowerCase.equalsIgnoreCase(getLocalSiteName()); } else { LOGGER.debug( "Unable to determine if the source id in metacard matches the local site name because the " + " metacard did not contain a source id attribute.", metacard.getId()); return false; } }

Target:
private boolean hasRemoteSiteName(Metacard metacard) { Optional<String> sourceId = Optional.ofNullable(metacard.getSourceId()); if (sourceId.isPresent()) { return !sourceId.get().equalsIgnoreCase(getLocalSiteName()); } else { LOGGER.debug( "Unable to determine if the source id in metacard matches the local site name because the " + " metacard did not contain a source id attribute.", metacard.getId()); return false; } }
Source:
private void updateContent() { final TextPosition currentCursor = getCursorPosition(); this.documentStorage.getDocument(document.getFile(), new DocumentCallback() { @Override public void onDocumentReceived(final String content) { editorWidget.setValue(content, new ContentInitializedHandler() { @Override public void onContentInitialized() { document.setCursorPosition(currentCursor); generalEventBus.fireEvent(new FileContentUpdatedEvent(document.getFile())); } }); } @Override public void onDocumentLoadFailure(final Throwable caught) { displayErrorPanel(constant.editorFileErrorMessage()); } }); }

Target:
private void updateContent() { final TextPosition currentCursor = getCursorPosition(); this.documentStorage.getDocument(document.getFile(), new DocumentCallback() { @Override public void onDocumentReceived(final String content) { editorWidget.setValue(content, new ContentInitializedHandler() { @Override public void onContentInitialized() { document.setCursorPosition(currentCursor); } }); } @Override public void onDocumentLoadFailure(final Throwable caught) { displayErrorPanel(constant.editorFileErrorMessage()); } }); }
Source:
public boolean isRunning() { try { return MongoDBClientSupport.forServer((AbstractMongoDBServer) entity).getServerStatus().get("ok").equals(1.0); } catch (Exception e) { return false; } }

Target:
public boolean isRunning() { try { return MongoDBClientSupport.forServer((AbstractMongoDBServer) entity).ping(); } catch (Exception e) { Exceptions.propagateIfFatal(e); return false; } }
Source:
public void shouldInstallPageModel() throws Exception { String componentCode = "de_test_page_model"; String componentAssociatedLabel = "DE_TEST_LABEL"; try { installAndCheckForCompletion(componentCode); assertThat(pageModelService.getPageModel(componentCode)).isNotNull(); assertThat(i18nManager.getLabel("DE_TEST_LABEL", "en")).isEqualTo("Test label DE"); assertThat(storageManager.exists("components/de_test_page_model/test.css", false)).isTrue(); } finally { if (pageModelService.getPageModel(componentCode) != null) { pageModelService.removePageModel(componentCode); } if (labelService.getLabelGroup(componentAssociatedLabel) != null) { labelService.removeLabelGroup(componentAssociatedLabel); } } }

Target:
public void shouldInstallPageModel() throws Exception { String componentCode = "de_test_page_model"; String componentAssociatedLabel = "DE_TEST_LABEL"; try { installAndCheckForCompletion(componentCode); assertThat(pageModelService.getPageModel(componentCode)).isNotNull(); assertThat(i18nManager.getLabel("DE_TEST_LABEL", "en")).isEqualTo("Test label DE"); assertThat(storageManager.exists("components/de_test_page_model/test.css", false)).isTrue(); } finally { try { pageModelService.removePageModel(componentCode); } catch (ValidationGenericException ignored) try { labelService.removeLabelGroup(componentAssociatedLabel); } catch (ValidationGenericException ignored) } }
Source:
protected void loadCategories(final Contentlet con, final Map<String,String> m) throws DotDataException, DotSecurityException { ContentType type = APILocator.getContentTypeAPI(APILocator.systemUser()).find(con.getContentTypeId()); List<com.dotcms.contenttype.model.field.Field> catFields = type.fields().stream().filter(field -> field instanceof CategoryField).collect(Collectors.toList()); if(catFields.size()==0) return; List<Category> myCats = APILocator.getCategoryAPI().getParents(con, APILocator.systemUser(), false); StringWriter myCatsString=new StringWriter(); for(Category me : myCats){ myCatsString.append(me.getCategoryVelocityVarName()).append(" "); } m.put(ESMappingConstants.CATEGORIES, myCatsString.toString()); for(com.dotcms.contenttype.model.field.Field f : catFields){ m.put(type.variable() + "." + f.variable(), myCatsString.toString()); } }

Target:
protected void loadCategories(final Contentlet con, final Map<String,String> m) throws DotDataException, DotSecurityException { final ContentType type = APILocator.getContentTypeAPI(APILocator.systemUser()).find(con.getContentTypeId()); List<com.dotcms.contenttype.model.field.Field> catFields = type.fields().stream() .filter(field -> field instanceof CategoryField).collect(CollectionsUtils.toImmutableList()); if(catFields.isEmpty()) { return; } List<Category> myCats = APILocator.getCategoryAPI().getParents(con, APILocator.systemUser(), false); final StringWriter myCatsString=new StringWriter(); for(final Category me : myCats){ myCatsString.append(me.getCategoryVelocityVarName()).append(" "); } m.put(ESMappingConstants.CATEGORIES, myCatsString.toString()); for(final com.dotcms.contenttype.model.field.Field f : catFields){ m.put(type.variable() + "." + f.variable(), myCatsString.toString()); } }
Source:
protected boolean validate() { if (!canRunActionOnNonManagedVm()) { return false; } if (!isInternalExecution() && !ObjectIdentityChecker.canUpdateField(getVm(), "clusterId", getVm().getStatus())) { addValidationMessage(EngineMessage.VM_STATUS_NOT_VALID_FOR_UPDATE); return false; } ChangeVmClusterValidator validator = Injector.injectMembers(new ChangeVmClusterValidator(this, getParameters().getClusterId(), getParameters().getVmCustomCompatibilityVersion(), getVmDeviceUtils())); return validator.validate(); }

Target:
protected boolean validate() { if (!canRunActionOnNonManagedVm()) { return false; } if (!isInternalExecution() && !ObjectIdentityChecker.canUpdateField(getVm(), "clusterId", getVm().getStatus())) { addValidationMessage(EngineMessage.VM_STATUS_NOT_VALID_FOR_UPDATE); return false; } ChangeVmClusterValidator validator = ChangeVmClusterValidator.create(this, getParameters().getClusterId(), getParameters().getVmCustomCompatibilityVersion()); return validator.validate(); }
Source:
public void shouldBeAbleToStartUpIfCassandraIsDownAndRunTransactionsWhenCassandraIsUp() throws IOException, InterruptedException { EteSetup.runCliCommand("service/bin/init.sh stop"); runOnCassandraNodes(MultiCassandraTestSuite::killCassandraContainer); EteSetup.runCliCommand("service/bin/init.sh start"); if (cassandraNodesToStartOrStop.size() > 1) { assertThatThrownBy(this::addATodo) .isInstanceOf(RuntimeException.class) .hasMessageStartingWith("Error 500. Reason: Internal Server Error.") .hasNoCause(); } else { addATodo(); } runOnCassandraNodes(MultiCassandraTestSuite::startCassandraContainer); addATodo(); }

Target:
public void shouldBeAbleToStartUpIfCassandraIsDownAndRunTransactionsWhenCassandraIsUp() throws IOException, InterruptedException { Assert.assertTrue(canAddTodo()); stopTheAtlasServer(); runOnCassandraNodes(MultiCassandraTestSuite::killCassandraContainer); startTheAtlasServer(); waitUntil(this::serverStarted); runOnCassandraNodes(MultiCassandraTestSuite::startCassandraContainer); waitUntil(this::canAddTodo); Assert.assertTrue(canAddTodo()); }
Source:
public void addListener(LockListener listener) { if (notifier.isDone()) { listener.onEvent(notifier.join()); } else { notifier.thenAccept(listener::onEvent); } }

Target:
public void addListener(LockListener listener) { if (notifier.isDone() && !notifier.isCompletedExceptionally()) { listener.onEvent(notifier.join()); } else { notifier.thenAccept(listener::onEvent); } }
Source:
protected String getPDFConversionURL(Blob blob) { BlobManager blobManager = Framework.getService(BlobManager.class); try { URI uri = blobManager.getAvailableConversions(blob, UsageHint.DOWNLOAD).get(MimetypeRegistry.PDF_MIMETYPE); if (uri != null) { return uri.toString(); } } catch (IOException e) { log.error("Failed to retrieve available conversions", e); } return null; }

Target:
protected String getPDFConversionURL(Blob blob) { BlobManager blobManager = Framework.getService(BlobManager.class); try { URI uri = blobManager.getAvailableConversions(blob, UsageHint.DOWNLOAD).get(PDF_MIMETYPE); if (uri != null) { return uri.toString(); } } catch (IOException e) { log.error("Failed to retrieve available conversions", e); } return null; }
Source:
public static void close(InputStream response) { try { if(response != null) { response.close(); } } catch (Exception e) { } }

Target:
public static void close(InputStream response) { IOUtils.closeQuietly(response); }
Source:
public void setSize(int width, int height) { super.setSize(width, height); validate(); if (isDisplayable()) { scrollView(); loadBackgroundImage(); } }

Target:
public void setSize(int width, int height) { super.setSize(width, height); validate(); if (isDisplayable()) { scrollView(); } }
Source:
public SurveyAnsweredRatio getSurveyAnsweredRatio() { if(mSurveyAnsweredRatio==null){ mSurveyAnsweredRatio = SurveyAnsweredRatio.getModelToEntity(SurveyAnsweredRatioDB.getSurveyAnsweredRatioBySurveyId(id)); } return mSurveyAnsweredRatio; }

Target:
public SurveyAnsweredRatio getSurveyAnsweredRatio() { return mSurveyAnsweredRatio; }
Source:
public void addAndTrimUptoMaxSize(ComplexEventChunk<StreamEvent> addingEventChunk) { ComplexEventChunk<StreamEvent> addingEventChunkForCache = new ComplexEventChunk<>(true); addingEventChunk.reset(); while (addingEventChunk.hasNext()) { StreamEvent event = addingEventChunk.next(); addingEventChunkForCache.add((StreamEvent) generateEventWithRequiredFields(event, siddhiAppContext, cacheExpiryEnabled)); } readWriteLock.writeLock().lock(); try { super.add(addingEventChunkForCache); while (this.size() > maxSize) { this.deleteOneEntryUsingCachePolicy(); } } finally { readWriteLock.writeLock().unlock(); } }

Target:
public void addAndTrimUptoMaxSize(ComplexEventChunk<StreamEvent> addingEventChunk) { ComplexEventChunk<StreamEvent> addingEventChunkForCache = new ComplexEventChunk<>(true); addingEventChunk.reset(); while (addingEventChunk.hasNext()) { StreamEvent event = addingEventChunk.next(); addingEventChunkForCache.add((StreamEvent) generateEventWithRequiredFields(event, siddhiAppContext, cacheExpiryEnabled)); } readWriteLock.writeLock().lock(); try { super.add(addingEventChunkForCache); if (this.size() > maxSize) { this.deleteEntriesUsingCachePolicy(this.size() - maxSize); } } finally { readWriteLock.writeLock().unlock(); } }
Source:
private Optional<CheckpointTriggerRequest> chooseRequestToExecute(boolean isTriggering, long lastCompletionMs) { Preconditions.checkState(Thread.holdsLock(lock)); if (isTriggering || queuedRequests.isEmpty()) { return Optional.empty(); } if (pendingCheckpointsSizeSupplier.get() >= maxConcurrentCheckpointAttempts) { return Optional.of(queuedRequests.first()) .filter(CheckpointTriggerRequest::isForce) .map(unused -> queuedRequests.pollFirst()); } CheckpointTriggerRequest first = queuedRequests.first(); if (first.isForce() || !first.isPeriodic) { return Optional.of(queuedRequests.pollFirst()); } long nextTriggerDelayMillis = nextTriggerDelayMillis(lastCompletionMs); if (nextTriggerDelayMillis > 0) { return onTooEarly(nextTriggerDelayMillis); } return Optional.of(queuedRequests.pollFirst()); }

Target:
private Optional<CheckpointTriggerRequest> chooseRequestToExecute(boolean isTriggering, long lastCompletionMs) { Preconditions.checkState(Thread.holdsLock(lock)); if (isTriggering || queuedRequests.isEmpty()) { return Optional.empty(); } if (pendingCheckpointsSizeSupplier.get() >= maxConcurrentCheckpointAttempts) { return Optional.of(queuedRequests.first()) .filter(CheckpointTriggerRequest::isForce) .map(unused -> queuedRequests.pollFirst()); } CheckpointTriggerRequest first = queuedRequests.first(); if (!first.isForce() && first.isPeriodic) { long nextTriggerDelayMillis = nextTriggerDelayMillis(lastCompletionMs); if (nextTriggerDelayMillis > 0) { queuedRequests.pollFirst().completeExceptionally(new CheckpointException(MINIMUM_TIME_BETWEEN_CHECKPOINTS)); rescheduleTrigger.accept(nextTriggerDelayMillis); return Optional.empty(); } } return Optional.of(queuedRequests.pollFirst()); }
Source:
protected void endTransaction(final TransactionManager tm, final Transaction tx) { try { if (tx != tm.getTransaction()) { throw EjbLogger.ROOT_LOGGER.wrongTxOnThread(tx, tm.getTransaction()); } final int txStatus = tx.getStatus(); if (txStatus == Status.STATUS_ACTIVE || txStatus == Status.STATUS_PREPARED || txStatus == Status.STATUS_PREPARING || txStatus == Status.STATUS_COMMITTING || txStatus == Status.STATUS_COMMITTED) { tm.commit(); } else if (txStatus == Status.STATUS_MARKED_ROLLBACK) { tm.rollback(); } else if (txStatus == Status.STATUS_ROLLEDBACK || txStatus == Status.STATUS_ROLLING_BACK) { tm.rollback(); throw EjbLogger.ROOT_LOGGER.transactionAlreadyRolledBack(tx); } else if (txStatus == Status.STATUS_UNKNOWN) { tm.rollback(); throw EjbLogger.ROOT_LOGGER.transactionInUnexpectedState(tx, statusAsString(txStatus)); } else { tm.suspend(); throw EjbLogger.ROOT_LOGGER.transactionInUnexpectedState(tx, statusAsString(txStatus)); } } catch (RollbackException e) { handleEndTransactionException(e); } catch (HeuristicMixedException e) { handleEndTransactionException(e); } catch (HeuristicRollbackException e) { handleEndTransactionException(e); } catch (SystemException e) { handleEndTransactionException(e); } }

Target:
protected void endTransaction(final TransactionManager tm, final Transaction tx) { try { if (tx != tm.getTransaction()) { throw EjbLogger.ROOT_LOGGER.wrongTxOnThread(tx, tm.getTransaction()); } final int txStatus = tx.getStatus(); if (txStatus == Status.STATUS_ACTIVE) { tm.commit(); } else if (txStatus == Status.STATUS_MARKED_ROLLBACK) { tm.rollback(); } else if (txStatus == Status.STATUS_ROLLEDBACK || txStatus == Status.STATUS_ROLLING_BACK) { tm.rollback(); throw EjbLogger.ROOT_LOGGER.transactionAlreadyRolledBack(tx); } else if (txStatus == Status.STATUS_UNKNOWN) { tm.rollback(); throw EjbLogger.ROOT_LOGGER.transactionInUnexpectedState(tx, statusAsString(txStatus)); } else { tm.suspend(); throw EjbLogger.ROOT_LOGGER.transactionInUnexpectedState(tx, statusAsString(txStatus)); } } catch (RollbackException e) { handleEndTransactionException(e); } catch (HeuristicMixedException e) { handleEndTransactionException(e); } catch (HeuristicRollbackException e) { handleEndTransactionException(e); } catch (SystemException e) { handleEndTransactionException(e); } }
Source:
private void checkPermission(ComponentDto project) { userSession.hasComponentPermission(UserRole.ADMIN, project); }

Target:
private void checkPermission(ComponentDto project) { userSession.checkComponentPermission(UserRole.ADMIN, project); }
Source:
StreamSpec getStreamSpec() { StreamSpec spec = (partitions == PARTITIONS_UNKNOWN) ? streamSpec : streamSpec.copyWithPartitionCount(partitions); if (isIntermediate) { ApplicationConfig appConfig = new ApplicationConfig(config); if (appConfig.getAppMode() == ApplicationConfig.ApplicationMode.BATCH && appConfig.getRunId() != null) { spec = spec.copyWithPhysicalName(spec.getPhysicalName() + "-" + appConfig.getRunId()); } } return spec; }

Target:
StreamSpec getStreamSpec() { StreamSpec spec = (partitions == PARTITIONS_UNKNOWN) ? streamSpec : streamSpec.copyWithPartitionCount(partitions); if (isIntermediate) { String physicalName = StreamManager.createUniqueNameForBatch(spec.getPhysicalName(), config); if (!physicalName.equals(spec.getPhysicalName())) { spec = spec.copyWithPhysicalName(physicalName); } } return spec; }
Source:
public boolean readMsg() throws Exception { int bytesAvailable = serial.available(); if (bytesAvailable > 0) { for (int i = 0; i < bytesAvailable; i++) { int newByte = serial.read(); ++byteCount; if (byteCount == 1 && newByte != VirtualMsg.MAGIC_NUMBER) { publishError(F("error serial")); byteCount = 0; } if (byteCount == 2) { if (newByte > 64) { byteCount = 0; System.out.println("TO BIG"); continue; } msgSize = newByte; } if (byteCount > 2) { ioCmd[byteCount - 3] = newByte; } if (byteCount == 2 + msgSize) { System.out.println("GOT " + msgSize + " BYTES"); byteCount = 0; return true; } } } return false; }

Target:
public boolean readMsg() throws Exception { int bytesAvailable = serial.available(); if (bytesAvailable > 0) { for (int i = 0; i < bytesAvailable; i++) { int newByte = serial.read(); ++byteCount; if (byteCount == 1 && newByte != VirtualMsg.MAGIC_NUMBER) { publishError(F("error serial")); byteCount = 0; } if (byteCount == 2) { if (newByte > 64) { byteCount = 0; continue; } msgSize = newByte; } if (byteCount > 2) { ioCmd[byteCount - 3] = newByte; } if (byteCount == 2 + msgSize) { System.out.println("GOT " + msgSize + " BYTES"); byteCount = 0; return true; } } } return false; }
Source:
public RecordMaterializer<T> prepareForRead( Configuration configuration, Map<String, String> keyValueMetaData, MessageType fileSchema, ReadContext readContext) { Map<String, String> metadata = readContext.getReadSupportMetadata(); MessageType parquetSchema = readContext.getRequestedSchema(); Schema avroSchema; if (readContext.getReadSupportMetadata().get(AVRO_READ_SCHEMA_METADATA_KEY) != null) { avroSchema = new Schema.Parser().parse(metadata.get(AVRO_READ_SCHEMA_METADATA_KEY)); } else if (keyValueMetaData.get(AVRO_SCHEMA_METADATA_KEY) != null) { avroSchema = new Schema.Parser().parse(keyValueMetaData.get(AVRO_SCHEMA_METADATA_KEY)); } else if (keyValueMetaData.get(OLD_AVRO_SCHEMA_METADATA_KEY) != null) { avroSchema = new Schema.Parser().parse(keyValueMetaData.get(OLD_AVRO_SCHEMA_METADATA_KEY)); } else { avroSchema = new AvroSchemaConverter(configuration).convert(parquetSchema); } GenericData model = getDataModel(configuration); String compatEnabled = metadata.get(AvroReadSupport.AVRO_COMPATIBILITY); if (compatEnabled != null && Boolean.valueOf(compatEnabled)) { return newCompatMaterializer(parquetSchema, avroSchema, model); } return new AvroRecordMaterializer<T>(parquetSchema, avroSchema, model); }

Target:
public RecordMaterializer<T> prepareForRead( Configuration configuration, Map<String, String> keyValueMetaData, MessageType fileSchema, ReadContext readContext) { Map<String, String> metadata = readContext.getReadSupportMetadata(); MessageType parquetSchema = readContext.getRequestedSchema(); Schema avroSchema; if (metadata.get(AVRO_READ_SCHEMA_METADATA_KEY) != null) { avroSchema = new Schema.Parser().parse(metadata.get(AVRO_READ_SCHEMA_METADATA_KEY)); } else if (keyValueMetaData.get(AVRO_SCHEMA_METADATA_KEY) != null) { avroSchema = new Schema.Parser().parse(keyValueMetaData.get(AVRO_SCHEMA_METADATA_KEY)); } else if (keyValueMetaData.get(OLD_AVRO_SCHEMA_METADATA_KEY) != null) { avroSchema = new Schema.Parser().parse(keyValueMetaData.get(OLD_AVRO_SCHEMA_METADATA_KEY)); } else { avroSchema = new AvroSchemaConverter(configuration).convert(parquetSchema); } GenericData model = getDataModel(configuration); String compatEnabled = metadata.get(AvroReadSupport.AVRO_COMPATIBILITY); if (compatEnabled != null && Boolean.valueOf(compatEnabled)) { return newCompatMaterializer(parquetSchema, avroSchema, model); } return new AvroRecordMaterializer<T>(parquetSchema, avroSchema, model); }
Source:
public boolean getJmxEnabledOnJobCoordinator() { if (containsKey(CLUSTER_MANAGER_JMX_ENABLED)) { log.info("Configuration is deprecated. Please use {}", CLUSTER_MANAGER_JMX_ENABLED, JOB_JMX_ENABLED); return getBoolean(CLUSTER_MANAGER_JMX_ENABLED); } else if (containsKey(AM_JMX_ENABLED)) { log.info("Configuration is deprecated. Please use {}", AM_JMX_ENABLED, JOB_JMX_ENABLED); return getBoolean(AM_JMX_ENABLED); } else if (containsKey(JOB_JMX_ENABLED)) { return getBoolean(JOB_JMX_ENABLED); } else { return true; } }

Target:
public boolean getJmxEnabledOnJobCoordinator() { if (containsKey(CLUSTER_MANAGER_JMX_ENABLED)) { log.warn("Configuration is deprecated. Please use {}", CLUSTER_MANAGER_JMX_ENABLED, JOB_JMX_ENABLED); return getBoolean(CLUSTER_MANAGER_JMX_ENABLED); } else if (containsKey(AM_JMX_ENABLED)) { log.warn("Configuration is deprecated. Please use {}", AM_JMX_ENABLED, JOB_JMX_ENABLED); return getBoolean(AM_JMX_ENABLED); } else if (containsKey(JOB_JMX_ENABLED)) { return getBoolean(JOB_JMX_ENABLED); } else { return true; } }
Source:
public boolean handleExtraButtonPressed(int buttonId) { if (buttonId == QueryWizardDialog.REFRESH_BUTTON_ID) { if (getTaskRepository() != null) { refreshConfiguration(true); } else { MessageDialog.openInformation( Display.getCurrent().getActiveShell(), Messages.AbstractRepositoryQueryPage2_Update_Attributes_Failed, Messages.AbstractRepositoryQueryPage2_No_repository_available_please_add_one_using_the_Task_Repositories_view); } return true; } else if (buttonId == QueryWizardDialog.CLEAR_BUTTON_ID) { if (!innerComposite.isDisposed()) { doClearControls(); return false; } return true; } return false; }

Target:
public boolean handleExtraButtonPressed(int buttonId) { if (buttonId == QueryWizardDialog.REFRESH_BUTTON_ID) { if (getTaskRepository() != null) { refreshConfiguration(true); } else { MessageDialog.openInformation( Display.getCurrent().getActiveShell(), Messages.AbstractRepositoryQueryPage2_Update_Attributes_Failed, Messages.AbstractRepositoryQueryPage2_No_repository_available_please_add_one_using_the_Task_Repositories_view); } return true; } else if (buttonId == QueryWizardDialog.CLEAR_BUTTON_ID) { doClearControls(); return true; } return false; }
Source:
public static void entriesMapCleanUp() { Timer cleanUpTimer = new Timer(); cleanUpTimer.schedule(new TimerTask() { @Override public void run() { CleanUp(); } }, Constants.KALTURA_ENTRY_PERSISTENCE_CLEANUP_START); logger.info("Persistence hash map cleanup will start in " + Constants.KALTURA_ENTRY_PERSISTENCE_CLEANUP_START / 1000 + " seconds"); }

Target:
public static void entriesMapCleanUp() { synchronized (_cleanUpLock) { long currentTime = System.currentTimeMillis(); if (currentTime - _lastMapCleanUp > Constants.KALTURA_TIME_BETWEEN_PERSISTENCE_CLEANUP) { _lastMapCleanUp = currentTime; Timer cleanUpTimer = new Timer(); cleanUpTimer.schedule(new TimerTask() { @Override public void run() { CleanUp(); } }, Constants.KALTURA_ENTRY_PERSISTENCE_CLEANUP_START); logger.debug("Persistence hash map cleanup will start in " + Constants.KALTURA_ENTRY_PERSISTENCE_CLEANUP_START / 1000 + " seconds"); } else { logger.debug("Persistence cleanup was called less than " + Constants.KALTURA_TIME_BETWEEN_PERSISTENCE_CLEANUP / 1000 + " seconds ago. Ignoring call!"); } } }
Source:
public void handle(S3GuardFsck.ComparePair comparePair) { if (!comparePair.containsViolation()) { LOG.debug("There is no violation in the compare pair: " + toString()); return; } StringBuilder sB = new StringBuilder(); sB.append(newLine) .append("On path: ").append(comparePair.getPath()).append(newLine); for (S3GuardFsck.Violation violation : comparePair.getViolations()) { try { ViolationHandler handler = violation.getHandler() .getDeclaredConstructor(S3GuardFsck.ComparePair.class) .newInstance(comparePair); final String errorStr = handler.getError(); sB.append(errorStr); } catch (NoSuchMethodException e) { LOG.error("Can not find declared constructor for handler: {}", violation.getHandler()); } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { LOG.error("Can not instantiate handler: {}", violation.getHandler()); } sB.append(newLine); } LOG.error(sB.toString()); }

Target:
public void handle(S3GuardFsck.ComparePair comparePair) { if (!comparePair.containsViolation()) { LOG.debug("There is no violation in the compare pair: {}", comparePair); return; } StringBuilder sB = new StringBuilder(); sB.append(newLine) .append("On path: ").append(comparePair.getPath()).append(newLine); handleComparePair(comparePair, sB); LOG.error(sB.toString()); }
Source:
private ValueHelper getHelperByType(String type) { ValueHelper valueHelper; try { if (type == null) { type = "String"; } Class<?> cls = Class.forName("org.ovirt.engine.core.config.entity.helper." + type + "ValueHelper"); valueHelper = (ValueHelper) cls.newInstance(); } catch (Exception e) { LoggerFactory.getLogger(EngineConfig.class).debug("Unable to find " + type + " type. Using default string type."); valueHelper = new StringValueHelper(); } return valueHelper; }

Target:
private ValueHelper getHelperByType(String type) { ValueHelper valueHelper; try { if (type == null) { type = "String"; } Class<?> cls = Class.forName("org.ovirt.engine.core.config.entity.helper." + type + "ValueHelper"); valueHelper = (ValueHelper) cls.newInstance(); } catch (Exception e) { LoggerFactory.getLogger(EngineConfig.class) .debug("Unable to find type. Using default string type.", type); valueHelper = new StringValueHelper(); } return valueHelper; }
Source:
private synchronized void scheduleTxnPolling() { List<Integer> keysToBeReaped = subscriptions.entrySet() .stream() .filter(e -> e.getValue().isReadyToBeReaped()) .map(e -> e.getKey()) .collect(Collectors.toList()); keysToBeReaped.forEach(k -> subscriptions.remove(k)); List<StreamingSubscriptionContext> lockedStreamingSubscriptionContexts = subscriptions.values() .stream() .filter(sc -> sc.acquire()) .collect(Collectors.toList()); if (!lockedStreamingSubscriptionContexts.isEmpty()) { log.trace("Locked StreamingSubscriptionContexts for processing", lockedStreamingSubscriptionContexts.size()); if (transactionPoller != null) { runtime.getStreamsView().getOpenedStreams().remove(transactionPoller.getTxnStream()); } transactionPoller = new TransactionPoller(runtime, lockedStreamingSubscriptionContexts); pollerExecutor.submit(transactionPoller); } }

Target:
private synchronized void scheduleTxnPolling() { List<Integer> keysToBeReaped = subscriptions.entrySet() .stream() .filter(e -> e.getValue().isReadyToBeReaped()) .map(e -> e.getKey()) .collect(Collectors.toList()); keysToBeReaped.forEach(k -> subscriptions.remove(k)); List<StreamingSubscriptionContext> lockedStreamingSubscriptionContexts = subscriptions.values() .stream() .filter(sc -> sc.acquire()) .collect(Collectors.toList()); if (!lockedStreamingSubscriptionContexts.isEmpty()) { log.trace("Locked StreamingSubscriptionContexts for processing", lockedStreamingSubscriptionContexts.size()); pollerExecutor.submit(new TransactionPoller(runtime, lockedStreamingSubscriptionContexts)); } }
Source:
public boolean requestRouteToHost(int networkType, int hostAddress) { enforceChangePermission(); if (!ConnectivityManager.isNetworkTypeValid(networkType)) { return false; } NetworkStateTracker tracker = mNetTrackers[networkType]; if (tracker == null || !tracker.getNetworkInfo().isConnected() || tracker.isTeardownRequested()) { if (DBG) { Slog.d(TAG, "requestRouteToHost on down network (" + networkType + ") - dropped"); } return false; } return tracker.requestRouteToHost(hostAddress); }

Target:
public boolean requestRouteToHost(int networkType, int hostAddress) { InetAddress inetAddress = NetworkUtils.lookupHost(hostAddress); if (inetAddress == null) { return false; } return requestRouteToHostAddress(networkType, inetAddress.getHostAddress()); }
Source:
public String toHaskellType(final int fixity) { StringBuilder out = new StringBuilder(); out.append(this.constructor); for (Type arg : this.args) { out.append(" "); out.append(arg.toHaskellType(10)); } if (fixity > 9 && this.args.length > 0) return "(" + out.toString() + ")"; return out.toString(); }

Target:
public String toHaskellType(final int fixity) { StringBuilder out = new StringBuilder(); out.append(this.constructor); for (Type arg : this.args) { out.append(" "); out.append(arg.toHaskellType(10)); } if (fixity > 9 && this.args.length > 0) { return "(" + out.toString() + ")"; } return out.toString(); }
Source:
public FenceExecutor(VDS vds) { if (! vds.getId().equals(Guid.Empty)) { VDS dbVds = DbFacade.getInstance().getVdsDao().get(vds.getId()); if (vds.getVdsGroupId() == null) { vds.setVdsGroupId(dbVds.getVdsGroupId()); } if (vds.getPmProxyPreferences() == null) { vds.setPmProxyPreferences(dbVds.getPmProxyPreferences()); } } this._vds = vds; this.proxyLocator = new FenceProxyLocator(_vds, fencingPolicy); this.architectureHelper = new VdsArchitectureHelper(); }

Target:
public FenceExecutor(VDS vds) { this(vds, null); }
Source:
public void refresh() { Map<IOpenShiftConnection, ConnectionWrapper> updated = new HashMap<>(); boolean changed = false; synchronized (connections) { HashMap<IOpenShiftConnection, ConnectionWrapper> oldWrappers = new HashMap<>(connections); connections.clear(); for (IConnection r : ConnectionsRegistrySingleton.getInstance().getAll()) { if (!(r instanceof IOpenShiftConnection)) { return; } IOpenShiftConnection connection= (IOpenShiftConnection) r; ConnectionWrapper existingWrapper = oldWrappers.remove(connection); if (existingWrapper == null) { ConnectionWrapper newWrapper = new ConnectionWrapper(this, connection); connections.put(connection, newWrapper); changed = true; } else { connections.put(connection, existingWrapper); updated.put(connection, existingWrapper); } } if (!oldWrappers.isEmpty()) { changed = true; } } if (changed) { fireChanged(); } updated.keySet().forEach(r -> { ConnectionWrapper wrapper = updated.get(r); wrapper.updateWith(r); }); for (ConnectionWrapper connection : connections.values()) { connection.refresh(); } }

Target:
public void refresh() { Map<IOpenShiftConnection, ConnectionWrapper> updated = new HashMap<>(); boolean changed = false; synchronized (connections) { HashMap<IOpenShiftConnection, ConnectionWrapper> oldWrappers = new HashMap<>(connections); connections.clear(); for (IOpenShiftConnection connection : ConnectionsRegistrySingleton.getInstance().getAll(IOpenShiftConnection.class)) { ConnectionWrapper existingWrapper = oldWrappers.remove(connection); if (existingWrapper == null) { ConnectionWrapper newWrapper = new ConnectionWrapper(this, connection); connections.put(connection, newWrapper); changed = true; } else { connections.put(connection, existingWrapper); updated.put(connection, existingWrapper); } } if (!oldWrappers.isEmpty()) { changed = true; } } if (changed) { fireChanged(this); } updated.keySet().forEach(r -> { ConnectionWrapper wrapper = updated.get(r); wrapper.updateWith(r); }); for (ConnectionWrapper connection : getConnections()) { connection.refresh(); } }
Source:
public void normalize(DockerEnvironment dockerEnvironment, RuntimeIdentity identity) throws InfrastructureException { String networkId = identity.getWorkspaceId() + "_" + identity.getEnvName(); dockerEnvironment.setNetwork(networkId); Map<String, DockerContainerConfig> containers = dockerEnvironment.getContainers(); for (Map.Entry<String, DockerContainerConfig> containerEntry : containers.entrySet()) { DockerContainerConfig containerConfig = containerEntry.getValue(); String userName; try { User user = userDao.getById(identity.getOwnerId()); userName = user == null ? identity.getOwnerId() : user.getName(); } catch (NotFoundException | ServerException e) { userName = identity.getOwnerId(); } containerConfig.setContainerName( containerNameGenerator.generateContainerName( identity.getWorkspaceId(), containerConfig.getId(), userName, containerEntry.getKey())); } normalizeNames(dockerEnvironment); }

Target:
public void normalize(DockerEnvironment dockerEnvironment, RuntimeIdentity identity) throws InfrastructureException { String networkId = identity.getWorkspaceId() + "_" + identity.getEnvName(); dockerEnvironment.setNetwork(networkId); Map<String, DockerContainerConfig> containers = dockerEnvironment.getContainers(); for (Map.Entry<String, DockerContainerConfig> containerEntry : containers.entrySet()) { DockerContainerConfig containerConfig = containerEntry.getValue(); containerConfig.setContainerName( containerNameGenerator.generateContainerName( identity.getWorkspaceId(), containerConfig.getId(), identity.getOwnerId(), containerEntry.getKey())); } normalizeNames(dockerEnvironment); }
Source:
public OptionPointSensitivity priceSensitivityNormalVolatility(IborFutureOption futureOption, RatesProvider prov, NormalVolatilityIborFutureParameters parameters, double futurePrice) { ArgChecker.isTrue(futureOption.getPremiumStyle().equals(FutureOptionPremiumStyle.DAILY_MARGIN), "premium style should be DAILY_MARGIN"); NormalVolatilityIborFutureParameters normalParameters = (NormalVolatilityIborFutureParameters) parameters; EuropeanVanillaOption option = createOption(futureOption, parameters); IborFutureOptionSensitivityKey key = createKey(futureOption, futurePrice, parameters); NormalFunctionData normalPoint = createData(key, normalParameters); double[] priceAdjoint = new double[3]; NORMAL_FUNCTION.getPriceAdjoint(option, normalPoint, priceAdjoint); return new OptionPointSensitivity(key, priceAdjoint[1], futureOption.getUnderlying().getProduct().getCurrency()); }

Target:
public OptionPointSensitivity priceSensitivityNormalVolatility(IborFutureOption futureOption, RatesProvider prov, NormalVolatilityIborFutureParameters parameters, double futurePrice) { ArgChecker.isTrue(futureOption.getPremiumStyle().equals(FutureOptionPremiumStyle.DAILY_MARGIN), "premium style should be DAILY_MARGIN"); NormalVolatilityIborFutureParameters normalParameters = (NormalVolatilityIborFutureParameters) parameters; EuropeanVanillaOption option = createOption(futureOption, parameters); IborFutureOptionSensitivityKey key = createKey(futureOption, futurePrice, parameters); NormalFunctionData normalPoint = createData(key, normalParameters); return new OptionPointSensitivity(key, NORMAL_FUNCTION.getVega(option, normalPoint), futureOption.getUnderlying().getProduct().getCurrency()); }
Source:
public void testConfigManualPercent() { final Injector injector = createInjector(); final String propertyPrefix = "druid.query.scheduler"; final JsonConfigProvider<QuerySchedulerProvider> provider = JsonConfigProvider.of( propertyPrefix, QuerySchedulerProvider.class ); final Properties properties = new Properties(); properties.put(propertyPrefix + ".numThreads", "10"); properties.put(propertyPrefix + ".laning.strategy", "manual"); properties.put(propertyPrefix + ".laning.isLimitPercent", "true"); properties.put(propertyPrefix + ".laning.lanes.one", "1"); properties.put(propertyPrefix + ".laning.lanes.twenty", "20"); provider.inject(properties, injector.getInstance(JsonConfigurator.class)); final QueryScheduler scheduler = provider.get().get().get(); Assert.assertEquals(10, scheduler.getTotalAvailableCapacity()); Assert.assertEquals(1, scheduler.getLaneAvailableCapacity("one")); Assert.assertEquals(2, scheduler.getLaneAvailableCapacity("twenty")); }

Target:
public void testConfigManualPercent() { final Injector injector = createInjector(); final String propertyPrefix = "druid.query.scheduler"; final JsonConfigProvider<QuerySchedulerProvider> provider = JsonConfigProvider.of( propertyPrefix, QuerySchedulerProvider.class ); final Properties properties = new Properties(); properties.put(propertyPrefix + ".numThreads", "10"); properties.put(propertyPrefix + ".laning.strategy", "manual"); properties.put(propertyPrefix + ".laning.isLimitPercent", "true"); properties.put(propertyPrefix + ".laning.lanes.one", "1"); properties.put(propertyPrefix + ".laning.lanes.twenty", "20"); provider.inject(properties, injector.getInstance(JsonConfigurator.class)); final QueryScheduler scheduler = provider.get().get().get(); Assert.assertEquals(10, scheduler.getTotalAvailableCapacity()); Assert.assertEquals(1, scheduler.getLaneAvailableCapacity("one")); Assert.assertEquals(2, scheduler.getLaneAvailableCapacity("twenty")); Assert.assertEquals(QueryScheduler.UNAVAILABLE, scheduler.getLaneAvailableCapacity("non-existent")); }
Source:
public XACML3HigherOrderFunction(String functionName) { Integer i = (Integer) (idMap.get(functionName)); if (i == null) { throw new IllegalArgumentException("Unknown function: " + functionName); } functionId = i.intValue(); try { identifier = new URI(functionName); } catch (URISyntaxException use) { throw new IllegalArgumentException("Invalid URI"); } }

Target:
public XACML3HigherOrderFunction(String functionName) { Integer i = ID_MAP.get(functionName); if (i == null) { throw new IllegalArgumentException("Unknown function: " + functionName); } functionId = i; try { identifier = new URI(functionName); } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid URI", e); } }